1 //===-- RISCVISelLowering.cpp - RISCV 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 RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.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"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/DiagnosticPrinter.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/IntrinsicsRISCV.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/KnownBits.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "riscv-lower"
45 
46 STATISTIC(NumTailCalls, "Number of tail calls");
47 
48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
49                                          const RISCVSubtarget &STI)
50     : TargetLowering(TM), Subtarget(STI) {
51 
52   if (Subtarget.isRV32E())
53     report_fatal_error("Codegen not yet implemented for RV32E");
54 
55   RISCVABI::ABI ABI = Subtarget.getTargetABI();
56   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
57 
58   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
59       !Subtarget.hasStdExtF()) {
60     errs() << "Hard-float 'f' ABI can't be used for a target that "
61                 "doesn't support the F instruction set extension (ignoring "
62                           "target-abi)\n";
63     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
64   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
65              !Subtarget.hasStdExtD()) {
66     errs() << "Hard-float 'd' ABI can't be used for a target that "
67               "doesn't support the D instruction set extension (ignoring "
68               "target-abi)\n";
69     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
70   }
71 
72   switch (ABI) {
73   default:
74     report_fatal_error("Don't know how to lower this ABI");
75   case RISCVABI::ABI_ILP32:
76   case RISCVABI::ABI_ILP32F:
77   case RISCVABI::ABI_ILP32D:
78   case RISCVABI::ABI_LP64:
79   case RISCVABI::ABI_LP64F:
80   case RISCVABI::ABI_LP64D:
81     break;
82   }
83 
84   MVT XLenVT = Subtarget.getXLenVT();
85 
86   // Set up the register classes.
87   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
88 
89   if (Subtarget.hasStdExtZfh())
90     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
91   if (Subtarget.hasStdExtF())
92     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
93   if (Subtarget.hasStdExtD())
94     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
95 
96   static const MVT::SimpleValueType BoolVecVTs[] = {
97       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
98       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
99   static const MVT::SimpleValueType IntVecVTs[] = {
100       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
101       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
102       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
103       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
104       MVT::nxv4i64, MVT::nxv8i64};
105   static const MVT::SimpleValueType F16VecVTs[] = {
106       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
107       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
108   static const MVT::SimpleValueType F32VecVTs[] = {
109       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
110   static const MVT::SimpleValueType F64VecVTs[] = {
111       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
112 
113   if (Subtarget.hasVInstructions()) {
114     auto addRegClassForRVV = [this](MVT VT) {
115       unsigned Size = VT.getSizeInBits().getKnownMinValue();
116       assert(Size <= 512 && isPowerOf2_32(Size));
117       const TargetRegisterClass *RC;
118       if (Size <= 64)
119         RC = &RISCV::VRRegClass;
120       else if (Size == 128)
121         RC = &RISCV::VRM2RegClass;
122       else if (Size == 256)
123         RC = &RISCV::VRM4RegClass;
124       else
125         RC = &RISCV::VRM8RegClass;
126 
127       addRegisterClass(VT, RC);
128     };
129 
130     for (MVT VT : BoolVecVTs)
131       addRegClassForRVV(VT);
132     for (MVT VT : IntVecVTs) {
133       if (VT.getVectorElementType() == MVT::i64 &&
134           !Subtarget.hasVInstructionsI64())
135         continue;
136       addRegClassForRVV(VT);
137     }
138 
139     if (Subtarget.hasVInstructionsF16())
140       for (MVT VT : F16VecVTs)
141         addRegClassForRVV(VT);
142 
143     if (Subtarget.hasVInstructionsF32())
144       for (MVT VT : F32VecVTs)
145         addRegClassForRVV(VT);
146 
147     if (Subtarget.hasVInstructionsF64())
148       for (MVT VT : F64VecVTs)
149         addRegClassForRVV(VT);
150 
151     if (Subtarget.useRVVForFixedLengthVectors()) {
152       auto addRegClassForFixedVectors = [this](MVT VT) {
153         MVT ContainerVT = getContainerForFixedLengthVector(VT);
154         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
155         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
156         addRegisterClass(VT, TRI.getRegClass(RCID));
157       };
158       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
159         if (useRVVForFixedLengthVectorVT(VT))
160           addRegClassForFixedVectors(VT);
161 
162       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
163         if (useRVVForFixedLengthVectorVT(VT))
164           addRegClassForFixedVectors(VT);
165     }
166   }
167 
168   // Compute derived properties from the register classes.
169   computeRegisterProperties(STI.getRegisterInfo());
170 
171   setStackPointerRegisterToSaveRestore(RISCV::X2);
172 
173   setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, XLenVT,
174                    MVT::i1, Promote);
175 
176   // TODO: add all necessary setOperationAction calls.
177   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
178 
179   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
180   setOperationAction(ISD::BR_CC, XLenVT, Expand);
181   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
182   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
183 
184   setOperationAction({ISD::STACKSAVE, ISD::STACKRESTORE}, MVT::Other, Expand);
185 
186   setOperationAction(ISD::VASTART, MVT::Other, Custom);
187   setOperationAction({ISD::VAARG, ISD::VACOPY, ISD::VAEND}, MVT::Other, Expand);
188 
189   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
190   if (!Subtarget.hasStdExtZbb())
191     setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand);
192 
193   if (Subtarget.is64Bit()) {
194     setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL},
195                        MVT::i32, Custom);
196 
197     setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT},
198                        MVT::i32, Custom);
199   } else {
200     setLibcallName(
201         {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128},
202         nullptr);
203     setLibcallName(RTLIB::MULO_I64, nullptr);
204   }
205 
206   if (!Subtarget.hasStdExtM()) {
207     setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::SDIV, ISD::UDIV,
208                         ISD::SREM, ISD::UREM},
209                        XLenVT, Expand);
210   } else {
211     if (Subtarget.is64Bit()) {
212       setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom);
213 
214       setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM},
215                          {MVT::i8, MVT::i16, MVT::i32}, Custom);
216     } else {
217       setOperationAction(ISD::MUL, MVT::i64, Custom);
218     }
219   }
220 
221   setOperationAction(
222       {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT,
223       Expand);
224 
225   setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT,
226                      Custom);
227 
228   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
229       Subtarget.hasStdExtZbkb()) {
230     if (Subtarget.is64Bit())
231       setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom);
232   } else {
233     setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand);
234   }
235 
236   if (Subtarget.hasStdExtZbp()) {
237     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
238     // more combining.
239     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom);
240 
241     // BSWAP i8 doesn't exist.
242     setOperationAction(ISD::BITREVERSE, MVT::i8, Custom);
243 
244     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom);
245 
246     if (Subtarget.is64Bit())
247       setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom);
248   } else {
249     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
250     // pattern match it directly in isel.
251     setOperationAction(ISD::BSWAP, XLenVT,
252                        (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
253                            ? Legal
254                            : Expand);
255     // Zbkb can use rev8+brev8 to implement bitreverse.
256     setOperationAction(ISD::BITREVERSE, XLenVT,
257                        Subtarget.hasStdExtZbkb() ? Custom : Expand);
258   }
259 
260   if (Subtarget.hasStdExtZbb()) {
261     setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT,
262                        Legal);
263 
264     if (Subtarget.is64Bit())
265       setOperationAction(
266           {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF},
267           MVT::i32, Custom);
268   } else {
269     setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand);
270 
271     if (Subtarget.is64Bit())
272       setOperationAction(ISD::ABS, MVT::i32, Custom);
273   }
274 
275   if (Subtarget.hasStdExtZbt()) {
276     setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom);
277     setOperationAction(ISD::SELECT, XLenVT, Legal);
278 
279     if (Subtarget.is64Bit())
280       setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom);
281   } else {
282     setOperationAction(ISD::SELECT, XLenVT, Custom);
283   }
284 
285   static constexpr ISD::NodeType FPLegalNodeTypes[] = {
286       ISD::FMINNUM,        ISD::FMAXNUM,       ISD::LRINT,
287       ISD::LLRINT,         ISD::LROUND,        ISD::LLROUND,
288       ISD::STRICT_LRINT,   ISD::STRICT_LLRINT, ISD::STRICT_LROUND,
289       ISD::STRICT_LLROUND, ISD::STRICT_FMA,    ISD::STRICT_FADD,
290       ISD::STRICT_FSUB,    ISD::STRICT_FMUL,   ISD::STRICT_FDIV,
291       ISD::STRICT_FSQRT,   ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS};
292 
293   static const ISD::CondCode FPCCToExpand[] = {
294       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
295       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
296       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
297 
298   static const ISD::NodeType FPOpToExpand[] = {
299       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
300       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
301 
302   if (Subtarget.hasStdExtZfh())
303     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
304 
305   if (Subtarget.hasStdExtZfh()) {
306     for (auto NT : FPLegalNodeTypes)
307       setOperationAction(NT, MVT::f16, Legal);
308     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
309     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
310     for (auto CC : FPCCToExpand)
311       setCondCodeAction(CC, MVT::f16, Expand);
312     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
313     setOperationAction(ISD::SELECT, MVT::f16, Custom);
314     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
315 
316     setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT,
317                         ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC,
318                         ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN,
319                         ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG,
320                         ISD::FLOG2, ISD::FLOG10},
321                        MVT::f16, Promote);
322 
323     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
324     // complete support for all operations in LegalizeDAG.
325 
326     // We need to custom promote this.
327     if (Subtarget.is64Bit())
328       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
329   }
330 
331   if (Subtarget.hasStdExtF()) {
332     for (auto NT : FPLegalNodeTypes)
333       setOperationAction(NT, MVT::f32, Legal);
334     for (auto CC : FPCCToExpand)
335       setCondCodeAction(CC, MVT::f32, Expand);
336     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
337     setOperationAction(ISD::SELECT, MVT::f32, Custom);
338     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
339     for (auto Op : FPOpToExpand)
340       setOperationAction(Op, MVT::f32, Expand);
341     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
342     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
343   }
344 
345   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
346     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
347 
348   if (Subtarget.hasStdExtD()) {
349     for (auto NT : FPLegalNodeTypes)
350       setOperationAction(NT, MVT::f64, Legal);
351     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
352     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
353     for (auto CC : FPCCToExpand)
354       setCondCodeAction(CC, MVT::f64, Expand);
355     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
356     setOperationAction(ISD::SELECT, MVT::f64, Custom);
357     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
358     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
359     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
360     for (auto Op : FPOpToExpand)
361       setOperationAction(Op, MVT::f64, Expand);
362     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
363     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
364   }
365 
366   if (Subtarget.is64Bit())
367     setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT,
368                         ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT},
369                        MVT::i32, Custom);
370 
371   if (Subtarget.hasStdExtF()) {
372     setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT,
373                        Custom);
374 
375     setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT,
376                         ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP},
377                        XLenVT, Legal);
378 
379     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
380     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
381   }
382 
383   setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool,
384                       ISD::JumpTable},
385                      XLenVT, Custom);
386 
387   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
388 
389   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
390   // Unfortunately this can't be determined just from the ISA naming string.
391   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
392                      Subtarget.is64Bit() ? Legal : Custom);
393 
394   setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal);
395   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
396   if (Subtarget.is64Bit())
397     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
398 
399   if (Subtarget.hasStdExtA()) {
400     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
401     setMinCmpXchgSizeInBits(32);
402   } else {
403     setMaxAtomicSizeInBitsSupported(0);
404   }
405 
406   setBooleanContents(ZeroOrOneBooleanContent);
407 
408   if (Subtarget.hasVInstructions()) {
409     setBooleanVectorContents(ZeroOrOneBooleanContent);
410 
411     setOperationAction(ISD::VSCALE, XLenVT, Custom);
412 
413     // RVV intrinsics may have illegal operands.
414     // We also need to custom legalize vmv.x.s.
415     setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
416                        {MVT::i8, MVT::i16}, Custom);
417     if (Subtarget.is64Bit())
418       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
419     else
420       setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
421                          MVT::i64, Custom);
422 
423     setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID},
424                        MVT::Other, Custom);
425 
426     static const unsigned IntegerVPOps[] = {
427         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
428         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
429         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
430         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
431         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
432         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
433         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
434         ISD::VP_MERGE,       ISD::VP_SELECT,      ISD::VP_FPTOSI,
435         ISD::VP_FPTOUI,      ISD::VP_SETCC,       ISD::VP_SEXT,
436         ISD::VP_ZEXT,        ISD::VP_TRUNC};
437 
438     static const unsigned FloatingPointVPOps[] = {
439         ISD::VP_FADD,        ISD::VP_FSUB,
440         ISD::VP_FMUL,        ISD::VP_FDIV,
441         ISD::VP_FNEG,        ISD::VP_FMA,
442         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
443         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX,
444         ISD::VP_MERGE,       ISD::VP_SELECT,
445         ISD::VP_SITOFP,      ISD::VP_UITOFP,
446         ISD::VP_SETCC,       ISD::VP_FP_ROUND};
447 
448     if (!Subtarget.is64Bit()) {
449       // We must custom-lower certain vXi64 operations on RV32 due to the vector
450       // element type being illegal.
451       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
452                          MVT::i64, Custom);
453 
454       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
455                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
456                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
457                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
458                          MVT::i64, Custom);
459 
460       setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND,
461                           ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR,
462                           ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN,
463                           ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN},
464                          MVT::i64, Custom);
465     }
466 
467     for (MVT VT : BoolVecVTs) {
468       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
469 
470       // Mask VTs are custom-expanded into a series of standard nodes
471       setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS,
472                           ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
473                          VT, Custom);
474 
475       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
476                          Custom);
477 
478       setOperationAction(ISD::SELECT, VT, Custom);
479       setOperationAction(
480           {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT,
481           Expand);
482 
483       setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom);
484 
485       setOperationAction(
486           {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
487           Custom);
488 
489       setOperationAction(
490           {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
491           Custom);
492 
493       // RVV has native int->float & float->int conversions where the
494       // element type sizes are within one power-of-two of each other. Any
495       // wider distances between type sizes have to be lowered as sequences
496       // which progressively narrow the gap in stages.
497       setOperationAction(
498           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
499           VT, Custom);
500 
501       // Expand all extending loads to types larger than this, and truncating
502       // stores from types larger than this.
503       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
504         setTruncStoreAction(OtherVT, VT, Expand);
505         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
506                          VT, Expand);
507       }
508 
509       setOperationAction({ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNC}, VT,
510                          Custom);
511     }
512 
513     for (MVT VT : IntVecVTs) {
514       if (VT.getVectorElementType() == MVT::i64 &&
515           !Subtarget.hasVInstructionsI64())
516         continue;
517 
518       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
519       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
520 
521       // Vectors implement MULHS/MULHU.
522       setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand);
523 
524       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
525       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV())
526         setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand);
527 
528       setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT,
529                          Legal);
530 
531       setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand);
532 
533       setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT,
534                          Expand);
535 
536       setOperationAction(ISD::BSWAP, VT, Expand);
537 
538       // Custom-lower extensions and truncations from/to mask types.
539       setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND},
540                          VT, Custom);
541 
542       // RVV has native int->float & float->int conversions where the
543       // element type sizes are within one power-of-two of each other. Any
544       // wider distances between type sizes have to be lowered as sequences
545       // which progressively narrow the gap in stages.
546       setOperationAction(
547           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
548           VT, Custom);
549 
550       setOperationAction(
551           {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal);
552 
553       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
554       // nodes which truncate by one power of two at a time.
555       setOperationAction(ISD::TRUNCATE, VT, Custom);
556 
557       // Custom-lower insert/extract operations to simplify patterns.
558       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
559                          Custom);
560 
561       // Custom-lower reduction operations to set up the corresponding custom
562       // nodes' operands.
563       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
564                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
565                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
566                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
567                          VT, Custom);
568 
569       for (unsigned VPOpc : IntegerVPOps)
570         setOperationAction(VPOpc, VT, Custom);
571 
572       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
573 
574       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
575                          VT, Custom);
576 
577       setOperationAction(
578           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
579           Custom);
580 
581       setOperationAction(
582           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
583           VT, Custom);
584 
585       setOperationAction(ISD::SELECT, VT, Custom);
586       setOperationAction(ISD::SELECT_CC, VT, Expand);
587 
588       setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom);
589 
590       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
591         setTruncStoreAction(VT, OtherVT, Expand);
592         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
593                          VT, Expand);
594       }
595 
596       // Splice
597       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
598 
599       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
600       // type that can represent the value exactly.
601       if (VT.getVectorElementType() != MVT::i64) {
602         MVT FloatEltVT =
603             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
604         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
605         if (isTypeLegal(FloatVT)) {
606           setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
607                              Custom);
608         }
609       }
610     }
611 
612     // Expand various CCs to best match the RVV ISA, which natively supports UNE
613     // but no other unordered comparisons, and supports all ordered comparisons
614     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
615     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
616     // and we pattern-match those back to the "original", swapping operands once
617     // more. This way we catch both operations and both "vf" and "fv" forms with
618     // fewer patterns.
619     static const ISD::CondCode VFPCCToExpand[] = {
620         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
621         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
622         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
623     };
624 
625     // Sets common operation actions on RVV floating-point vector types.
626     const auto SetCommonVFPActions = [&](MVT VT) {
627       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
628       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
629       // sizes are within one power-of-two of each other. Therefore conversions
630       // between vXf16 and vXf64 must be lowered as sequences which convert via
631       // vXf32.
632       setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
633       // Custom-lower insert/extract operations to simplify patterns.
634       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
635                          Custom);
636       // Expand various condition codes (explained above).
637       for (auto CC : VFPCCToExpand)
638         setCondCodeAction(CC, VT, Expand);
639 
640       setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal);
641 
642       setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
643                          VT, Custom);
644 
645       setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
646                           ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
647                          VT, Custom);
648 
649       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
650 
651       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
652 
653       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
654                          VT, Custom);
655 
656       setOperationAction(
657           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
658           Custom);
659 
660       setOperationAction(ISD::SELECT, VT, Custom);
661       setOperationAction(ISD::SELECT_CC, VT, Expand);
662 
663       setOperationAction(
664           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
665           VT, Custom);
666 
667       setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom);
668 
669       for (unsigned VPOpc : FloatingPointVPOps)
670         setOperationAction(VPOpc, VT, Custom);
671     };
672 
673     // Sets common extload/truncstore actions on RVV floating-point vector
674     // types.
675     const auto SetCommonVFPExtLoadTruncStoreActions =
676         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
677           for (auto SmallVT : SmallerVTs) {
678             setTruncStoreAction(VT, SmallVT, Expand);
679             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
680           }
681         };
682 
683     if (Subtarget.hasVInstructionsF16())
684       for (MVT VT : F16VecVTs)
685         SetCommonVFPActions(VT);
686 
687     for (MVT VT : F32VecVTs) {
688       if (Subtarget.hasVInstructionsF32())
689         SetCommonVFPActions(VT);
690       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
691     }
692 
693     for (MVT VT : F64VecVTs) {
694       if (Subtarget.hasVInstructionsF64())
695         SetCommonVFPActions(VT);
696       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
697       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
698     }
699 
700     if (Subtarget.useRVVForFixedLengthVectors()) {
701       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
702         if (!useRVVForFixedLengthVectorVT(VT))
703           continue;
704 
705         // By default everything must be expanded.
706         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
707           setOperationAction(Op, VT, Expand);
708         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
709           setTruncStoreAction(VT, OtherVT, Expand);
710           setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD},
711                            OtherVT, VT, Expand);
712         }
713 
714         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
715         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
716                            Custom);
717 
718         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT,
719                            Custom);
720 
721         setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
722                            VT, Custom);
723 
724         setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
725 
726         setOperationAction(ISD::SETCC, VT, Custom);
727 
728         setOperationAction(ISD::SELECT, VT, Custom);
729 
730         setOperationAction(ISD::TRUNCATE, VT, Custom);
731 
732         setOperationAction(ISD::BITCAST, VT, Custom);
733 
734         setOperationAction(
735             {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
736             Custom);
737 
738         setOperationAction(
739             {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
740             Custom);
741 
742         setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT,
743                             ISD::FP_TO_UINT},
744                            VT, Custom);
745 
746         // Operations below are different for between masks and other vectors.
747         if (VT.getVectorElementType() == MVT::i1) {
748           setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND,
749                               ISD::OR, ISD::XOR},
750                              VT, Custom);
751 
752           setOperationAction(
753               {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNC},
754               VT, Custom);
755           continue;
756         }
757 
758         // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
759         // it before type legalization for i64 vectors on RV32. It will then be
760         // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
761         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
762         // improvements first.
763         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
764           setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
765           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
766         }
767 
768         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
769         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
770 
771         setOperationAction(
772             {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom);
773 
774         setOperationAction(
775             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
776             Custom);
777 
778         setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR,
779                             ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV,
780                             ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL},
781                            VT, Custom);
782 
783         setOperationAction(
784             {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom);
785 
786         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
787         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV())
788           setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom);
789 
790         setOperationAction(
791             {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT,
792             Custom);
793 
794         setOperationAction(ISD::VSELECT, VT, Custom);
795         setOperationAction(ISD::SELECT_CC, VT, Expand);
796 
797         setOperationAction(
798             {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom);
799 
800         // Custom-lower reduction operations to set up the corresponding custom
801         // nodes' operands.
802         setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX,
803                             ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX,
804                             ISD::VECREDUCE_UMIN},
805                            VT, Custom);
806 
807         for (unsigned VPOpc : IntegerVPOps)
808           setOperationAction(VPOpc, VT, Custom);
809 
810         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
811         // type that can represent the value exactly.
812         if (VT.getVectorElementType() != MVT::i64) {
813           MVT FloatEltVT =
814               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
815           EVT FloatVT =
816               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
817           if (isTypeLegal(FloatVT))
818             setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
819                                Custom);
820         }
821       }
822 
823       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
824         if (!useRVVForFixedLengthVectorVT(VT))
825           continue;
826 
827         // By default everything must be expanded.
828         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
829           setOperationAction(Op, VT, Expand);
830         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
831           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
832           setTruncStoreAction(VT, OtherVT, Expand);
833         }
834 
835         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
836         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
837                            Custom);
838 
839         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS,
840                             ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT,
841                             ISD::EXTRACT_VECTOR_ELT},
842                            VT, Custom);
843 
844         setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE,
845                             ISD::MGATHER, ISD::MSCATTER},
846                            VT, Custom);
847 
848         setOperationAction(
849             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
850             Custom);
851 
852         setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV,
853                             ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT,
854                             ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM},
855                            VT, Custom);
856 
857         setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
858 
859         setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
860                            VT, Custom);
861 
862         for (auto CC : VFPCCToExpand)
863           setCondCodeAction(CC, VT, Expand);
864 
865         setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom);
866         setOperationAction(ISD::SELECT_CC, VT, Expand);
867 
868         setOperationAction(ISD::BITCAST, VT, Custom);
869 
870         setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
871                             ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
872                            VT, Custom);
873 
874         for (unsigned VPOpc : FloatingPointVPOps)
875           setOperationAction(VPOpc, VT, Custom);
876       }
877 
878       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
879       setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64},
880                          Custom);
881       if (Subtarget.hasStdExtZfh())
882         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
883       if (Subtarget.hasStdExtF())
884         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
885       if (Subtarget.hasStdExtD())
886         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
887     }
888   }
889 
890   // Function alignments.
891   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
892   setMinFunctionAlignment(FunctionAlignment);
893   setPrefFunctionAlignment(FunctionAlignment);
894 
895   setMinimumJumpTableEntries(5);
896 
897   // Jumps are expensive, compared to logic
898   setJumpIsExpensive();
899 
900   setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND,
901                        ISD::OR, ISD::XOR});
902 
903   if (Subtarget.hasStdExtZbp())
904     setTargetDAGCombine({ISD::ROTL, ISD::ROTR});
905   if (Subtarget.hasStdExtZbkb())
906     setTargetDAGCombine(ISD::BITREVERSE);
907   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
908     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
909   if (Subtarget.hasStdExtF())
910     setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
911                          ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT});
912   if (Subtarget.hasVInstructions())
913     setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER,
914                          ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL,
915                          ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR});
916 
917   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
918   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
919 }
920 
921 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
922                                             LLVMContext &Context,
923                                             EVT VT) const {
924   if (!VT.isVector())
925     return getPointerTy(DL);
926   if (Subtarget.hasVInstructions() &&
927       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
928     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
929   return VT.changeVectorElementTypeToInteger();
930 }
931 
932 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
933   return Subtarget.getXLenVT();
934 }
935 
936 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
937                                              const CallInst &I,
938                                              MachineFunction &MF,
939                                              unsigned Intrinsic) const {
940   auto &DL = I.getModule()->getDataLayout();
941   switch (Intrinsic) {
942   default:
943     return false;
944   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
945   case Intrinsic::riscv_masked_atomicrmw_add_i32:
946   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
947   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
948   case Intrinsic::riscv_masked_atomicrmw_max_i32:
949   case Intrinsic::riscv_masked_atomicrmw_min_i32:
950   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
951   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
952   case Intrinsic::riscv_masked_cmpxchg_i32:
953     Info.opc = ISD::INTRINSIC_W_CHAIN;
954     Info.memVT = MVT::i32;
955     Info.ptrVal = I.getArgOperand(0);
956     Info.offset = 0;
957     Info.align = Align(4);
958     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
959                  MachineMemOperand::MOVolatile;
960     return true;
961   case Intrinsic::riscv_masked_strided_load:
962     Info.opc = ISD::INTRINSIC_W_CHAIN;
963     Info.ptrVal = I.getArgOperand(1);
964     Info.memVT = getValueType(DL, I.getType()->getScalarType());
965     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
966     Info.size = MemoryLocation::UnknownSize;
967     Info.flags |= MachineMemOperand::MOLoad;
968     return true;
969   case Intrinsic::riscv_masked_strided_store:
970     Info.opc = ISD::INTRINSIC_VOID;
971     Info.ptrVal = I.getArgOperand(1);
972     Info.memVT =
973         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
974     Info.align = Align(
975         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
976         8);
977     Info.size = MemoryLocation::UnknownSize;
978     Info.flags |= MachineMemOperand::MOStore;
979     return true;
980   case Intrinsic::riscv_seg2_load:
981   case Intrinsic::riscv_seg3_load:
982   case Intrinsic::riscv_seg4_load:
983   case Intrinsic::riscv_seg5_load:
984   case Intrinsic::riscv_seg6_load:
985   case Intrinsic::riscv_seg7_load:
986   case Intrinsic::riscv_seg8_load:
987     Info.opc = ISD::INTRINSIC_W_CHAIN;
988     Info.ptrVal = I.getArgOperand(0);
989     Info.memVT =
990         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
991     Info.align =
992         Align(DL.getTypeSizeInBits(
993                   I.getType()->getStructElementType(0)->getScalarType()) /
994               8);
995     Info.size = MemoryLocation::UnknownSize;
996     Info.flags |= MachineMemOperand::MOLoad;
997     return true;
998   }
999 }
1000 
1001 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1002                                                 const AddrMode &AM, Type *Ty,
1003                                                 unsigned AS,
1004                                                 Instruction *I) const {
1005   // No global is ever allowed as a base.
1006   if (AM.BaseGV)
1007     return false;
1008 
1009   // Require a 12-bit signed offset.
1010   if (!isInt<12>(AM.BaseOffs))
1011     return false;
1012 
1013   switch (AM.Scale) {
1014   case 0: // "r+i" or just "i", depending on HasBaseReg.
1015     break;
1016   case 1:
1017     if (!AM.HasBaseReg) // allow "r+i".
1018       break;
1019     return false; // disallow "r+r" or "r+r+i".
1020   default:
1021     return false;
1022   }
1023 
1024   return true;
1025 }
1026 
1027 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1028   return isInt<12>(Imm);
1029 }
1030 
1031 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1032   return isInt<12>(Imm);
1033 }
1034 
1035 // On RV32, 64-bit integers are split into their high and low parts and held
1036 // in two different registers, so the trunc is free since the low register can
1037 // just be used.
1038 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1039   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1040     return false;
1041   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1042   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1043   return (SrcBits == 64 && DestBits == 32);
1044 }
1045 
1046 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1047   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1048       !SrcVT.isInteger() || !DstVT.isInteger())
1049     return false;
1050   unsigned SrcBits = SrcVT.getSizeInBits();
1051   unsigned DestBits = DstVT.getSizeInBits();
1052   return (SrcBits == 64 && DestBits == 32);
1053 }
1054 
1055 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1056   // Zexts are free if they can be combined with a load.
1057   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1058   // poorly with type legalization of compares preferring sext.
1059   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1060     EVT MemVT = LD->getMemoryVT();
1061     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1062         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1063          LD->getExtensionType() == ISD::ZEXTLOAD))
1064       return true;
1065   }
1066 
1067   return TargetLowering::isZExtFree(Val, VT2);
1068 }
1069 
1070 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1071   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1072 }
1073 
1074 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const {
1075   return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
1076 }
1077 
1078 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1079   return Subtarget.hasStdExtZbb();
1080 }
1081 
1082 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1083   return Subtarget.hasStdExtZbb();
1084 }
1085 
1086 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1087   EVT VT = Y.getValueType();
1088 
1089   // FIXME: Support vectors once we have tests.
1090   if (VT.isVector())
1091     return false;
1092 
1093   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1094           Subtarget.hasStdExtZbkb()) &&
1095          !isa<ConstantSDNode>(Y);
1096 }
1097 
1098 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
1099   // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1100   auto *C = dyn_cast<ConstantSDNode>(Y);
1101   return C && C->getAPIntValue().ule(10);
1102 }
1103 
1104 /// Check if sinking \p I's operands to I's basic block is profitable, because
1105 /// the operands can be folded into a target instruction, e.g.
1106 /// splats of scalars can fold into vector instructions.
1107 bool RISCVTargetLowering::shouldSinkOperands(
1108     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1109   using namespace llvm::PatternMatch;
1110 
1111   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1112     return false;
1113 
1114   auto IsSinker = [&](Instruction *I, int Operand) {
1115     switch (I->getOpcode()) {
1116     case Instruction::Add:
1117     case Instruction::Sub:
1118     case Instruction::Mul:
1119     case Instruction::And:
1120     case Instruction::Or:
1121     case Instruction::Xor:
1122     case Instruction::FAdd:
1123     case Instruction::FSub:
1124     case Instruction::FMul:
1125     case Instruction::FDiv:
1126     case Instruction::ICmp:
1127     case Instruction::FCmp:
1128       return true;
1129     case Instruction::Shl:
1130     case Instruction::LShr:
1131     case Instruction::AShr:
1132     case Instruction::UDiv:
1133     case Instruction::SDiv:
1134     case Instruction::URem:
1135     case Instruction::SRem:
1136       return Operand == 1;
1137     case Instruction::Call:
1138       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1139         switch (II->getIntrinsicID()) {
1140         case Intrinsic::fma:
1141         case Intrinsic::vp_fma:
1142           return Operand == 0 || Operand == 1;
1143         // FIXME: Our patterns can only match vx/vf instructions when the splat
1144         // it on the RHS, because TableGen doesn't recognize our VP operations
1145         // as commutative.
1146         case Intrinsic::vp_add:
1147         case Intrinsic::vp_mul:
1148         case Intrinsic::vp_and:
1149         case Intrinsic::vp_or:
1150         case Intrinsic::vp_xor:
1151         case Intrinsic::vp_fadd:
1152         case Intrinsic::vp_fmul:
1153         case Intrinsic::vp_shl:
1154         case Intrinsic::vp_lshr:
1155         case Intrinsic::vp_ashr:
1156         case Intrinsic::vp_udiv:
1157         case Intrinsic::vp_sdiv:
1158         case Intrinsic::vp_urem:
1159         case Intrinsic::vp_srem:
1160           return Operand == 1;
1161         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1162         // explicit patterns for both LHS and RHS (as 'vr' versions).
1163         case Intrinsic::vp_sub:
1164         case Intrinsic::vp_fsub:
1165         case Intrinsic::vp_fdiv:
1166           return Operand == 0 || Operand == 1;
1167         default:
1168           return false;
1169         }
1170       }
1171       return false;
1172     default:
1173       return false;
1174     }
1175   };
1176 
1177   for (auto OpIdx : enumerate(I->operands())) {
1178     if (!IsSinker(I, OpIdx.index()))
1179       continue;
1180 
1181     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1182     // Make sure we are not already sinking this operand
1183     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1184       continue;
1185 
1186     // We are looking for a splat that can be sunk.
1187     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1188                              m_Undef(), m_ZeroMask())))
1189       continue;
1190 
1191     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1192     // and vector registers
1193     for (Use &U : Op->uses()) {
1194       Instruction *Insn = cast<Instruction>(U.getUser());
1195       if (!IsSinker(Insn, U.getOperandNo()))
1196         return false;
1197     }
1198 
1199     Ops.push_back(&Op->getOperandUse(0));
1200     Ops.push_back(&OpIdx.value());
1201   }
1202   return true;
1203 }
1204 
1205 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1206                                        bool ForCodeSize) const {
1207   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1208   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1209     return false;
1210   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1211     return false;
1212   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1213     return false;
1214   return Imm.isZero();
1215 }
1216 
1217 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1218   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1219          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1220          (VT == MVT::f64 && Subtarget.hasStdExtD());
1221 }
1222 
1223 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1224                                                       CallingConv::ID CC,
1225                                                       EVT VT) const {
1226   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1227   // We might still end up using a GPR but that will be decided based on ABI.
1228   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1229   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1230     return MVT::f32;
1231 
1232   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1233 }
1234 
1235 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1236                                                            CallingConv::ID CC,
1237                                                            EVT VT) const {
1238   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1239   // We might still end up using a GPR but that will be decided based on ABI.
1240   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1241   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1242     return 1;
1243 
1244   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1245 }
1246 
1247 // Changes the condition code and swaps operands if necessary, so the SetCC
1248 // operation matches one of the comparisons supported directly by branches
1249 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1250 // with 1/-1.
1251 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1252                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1253   // Convert X > -1 to X >= 0.
1254   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1255     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1256     CC = ISD::SETGE;
1257     return;
1258   }
1259   // Convert X < 1 to 0 >= X.
1260   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1261     RHS = LHS;
1262     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1263     CC = ISD::SETGE;
1264     return;
1265   }
1266 
1267   switch (CC) {
1268   default:
1269     break;
1270   case ISD::SETGT:
1271   case ISD::SETLE:
1272   case ISD::SETUGT:
1273   case ISD::SETULE:
1274     CC = ISD::getSetCCSwappedOperands(CC);
1275     std::swap(LHS, RHS);
1276     break;
1277   }
1278 }
1279 
1280 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1281   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1282   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1283   if (VT.getVectorElementType() == MVT::i1)
1284     KnownSize *= 8;
1285 
1286   switch (KnownSize) {
1287   default:
1288     llvm_unreachable("Invalid LMUL.");
1289   case 8:
1290     return RISCVII::VLMUL::LMUL_F8;
1291   case 16:
1292     return RISCVII::VLMUL::LMUL_F4;
1293   case 32:
1294     return RISCVII::VLMUL::LMUL_F2;
1295   case 64:
1296     return RISCVII::VLMUL::LMUL_1;
1297   case 128:
1298     return RISCVII::VLMUL::LMUL_2;
1299   case 256:
1300     return RISCVII::VLMUL::LMUL_4;
1301   case 512:
1302     return RISCVII::VLMUL::LMUL_8;
1303   }
1304 }
1305 
1306 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1307   switch (LMul) {
1308   default:
1309     llvm_unreachable("Invalid LMUL.");
1310   case RISCVII::VLMUL::LMUL_F8:
1311   case RISCVII::VLMUL::LMUL_F4:
1312   case RISCVII::VLMUL::LMUL_F2:
1313   case RISCVII::VLMUL::LMUL_1:
1314     return RISCV::VRRegClassID;
1315   case RISCVII::VLMUL::LMUL_2:
1316     return RISCV::VRM2RegClassID;
1317   case RISCVII::VLMUL::LMUL_4:
1318     return RISCV::VRM4RegClassID;
1319   case RISCVII::VLMUL::LMUL_8:
1320     return RISCV::VRM8RegClassID;
1321   }
1322 }
1323 
1324 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1325   RISCVII::VLMUL LMUL = getLMUL(VT);
1326   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1327       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1328       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1329       LMUL == RISCVII::VLMUL::LMUL_1) {
1330     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1331                   "Unexpected subreg numbering");
1332     return RISCV::sub_vrm1_0 + Index;
1333   }
1334   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1335     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1336                   "Unexpected subreg numbering");
1337     return RISCV::sub_vrm2_0 + Index;
1338   }
1339   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1340     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1341                   "Unexpected subreg numbering");
1342     return RISCV::sub_vrm4_0 + Index;
1343   }
1344   llvm_unreachable("Invalid vector type.");
1345 }
1346 
1347 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1348   if (VT.getVectorElementType() == MVT::i1)
1349     return RISCV::VRRegClassID;
1350   return getRegClassIDForLMUL(getLMUL(VT));
1351 }
1352 
1353 // Attempt to decompose a subvector insert/extract between VecVT and
1354 // SubVecVT via subregister indices. Returns the subregister index that
1355 // can perform the subvector insert/extract with the given element index, as
1356 // well as the index corresponding to any leftover subvectors that must be
1357 // further inserted/extracted within the register class for SubVecVT.
1358 std::pair<unsigned, unsigned>
1359 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1360     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1361     const RISCVRegisterInfo *TRI) {
1362   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1363                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1364                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1365                 "Register classes not ordered");
1366   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1367   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1368   // Try to compose a subregister index that takes us from the incoming
1369   // LMUL>1 register class down to the outgoing one. At each step we half
1370   // the LMUL:
1371   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1372   // Note that this is not guaranteed to find a subregister index, such as
1373   // when we are extracting from one VR type to another.
1374   unsigned SubRegIdx = RISCV::NoSubRegister;
1375   for (const unsigned RCID :
1376        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1377     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1378       VecVT = VecVT.getHalfNumVectorElementsVT();
1379       bool IsHi =
1380           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1381       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1382                                             getSubregIndexByMVT(VecVT, IsHi));
1383       if (IsHi)
1384         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1385     }
1386   return {SubRegIdx, InsertExtractIdx};
1387 }
1388 
1389 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1390 // stores for those types.
1391 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1392   return !Subtarget.useRVVForFixedLengthVectors() ||
1393          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1394 }
1395 
1396 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1397   if (ScalarTy->isPointerTy())
1398     return true;
1399 
1400   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1401       ScalarTy->isIntegerTy(32))
1402     return true;
1403 
1404   if (ScalarTy->isIntegerTy(64))
1405     return Subtarget.hasVInstructionsI64();
1406 
1407   if (ScalarTy->isHalfTy())
1408     return Subtarget.hasVInstructionsF16();
1409   if (ScalarTy->isFloatTy())
1410     return Subtarget.hasVInstructionsF32();
1411   if (ScalarTy->isDoubleTy())
1412     return Subtarget.hasVInstructionsF64();
1413 
1414   return false;
1415 }
1416 
1417 static SDValue getVLOperand(SDValue Op) {
1418   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1419           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1420          "Unexpected opcode");
1421   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1422   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1423   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1424       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1425   if (!II)
1426     return SDValue();
1427   return Op.getOperand(II->VLOperand + 1 + HasChain);
1428 }
1429 
1430 static bool useRVVForFixedLengthVectorVT(MVT VT,
1431                                          const RISCVSubtarget &Subtarget) {
1432   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1433   if (!Subtarget.useRVVForFixedLengthVectors())
1434     return false;
1435 
1436   // We only support a set of vector types with a consistent maximum fixed size
1437   // across all supported vector element types to avoid legalization issues.
1438   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1439   // fixed-length vector type we support is 1024 bytes.
1440   if (VT.getFixedSizeInBits() > 1024 * 8)
1441     return false;
1442 
1443   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1444 
1445   MVT EltVT = VT.getVectorElementType();
1446 
1447   // Don't use RVV for vectors we cannot scalarize if required.
1448   switch (EltVT.SimpleTy) {
1449   // i1 is supported but has different rules.
1450   default:
1451     return false;
1452   case MVT::i1:
1453     // Masks can only use a single register.
1454     if (VT.getVectorNumElements() > MinVLen)
1455       return false;
1456     MinVLen /= 8;
1457     break;
1458   case MVT::i8:
1459   case MVT::i16:
1460   case MVT::i32:
1461     break;
1462   case MVT::i64:
1463     if (!Subtarget.hasVInstructionsI64())
1464       return false;
1465     break;
1466   case MVT::f16:
1467     if (!Subtarget.hasVInstructionsF16())
1468       return false;
1469     break;
1470   case MVT::f32:
1471     if (!Subtarget.hasVInstructionsF32())
1472       return false;
1473     break;
1474   case MVT::f64:
1475     if (!Subtarget.hasVInstructionsF64())
1476       return false;
1477     break;
1478   }
1479 
1480   // Reject elements larger than ELEN.
1481   if (EltVT.getSizeInBits() > Subtarget.getELEN())
1482     return false;
1483 
1484   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1485   // Don't use RVV for types that don't fit.
1486   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1487     return false;
1488 
1489   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1490   // the base fixed length RVV support in place.
1491   if (!VT.isPow2VectorType())
1492     return false;
1493 
1494   return true;
1495 }
1496 
1497 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1498   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1499 }
1500 
1501 // Return the largest legal scalable vector type that matches VT's element type.
1502 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1503                                             const RISCVSubtarget &Subtarget) {
1504   // This may be called before legal types are setup.
1505   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1506           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1507          "Expected legal fixed length vector!");
1508 
1509   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1510   unsigned MaxELen = Subtarget.getELEN();
1511 
1512   MVT EltVT = VT.getVectorElementType();
1513   switch (EltVT.SimpleTy) {
1514   default:
1515     llvm_unreachable("unexpected element type for RVV container");
1516   case MVT::i1:
1517   case MVT::i8:
1518   case MVT::i16:
1519   case MVT::i32:
1520   case MVT::i64:
1521   case MVT::f16:
1522   case MVT::f32:
1523   case MVT::f64: {
1524     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1525     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1526     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1527     unsigned NumElts =
1528         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1529     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1530     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1531     return MVT::getScalableVectorVT(EltVT, NumElts);
1532   }
1533   }
1534 }
1535 
1536 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1537                                             const RISCVSubtarget &Subtarget) {
1538   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1539                                           Subtarget);
1540 }
1541 
1542 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1543   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1544 }
1545 
1546 // Grow V to consume an entire RVV register.
1547 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1548                                        const RISCVSubtarget &Subtarget) {
1549   assert(VT.isScalableVector() &&
1550          "Expected to convert into a scalable vector!");
1551   assert(V.getValueType().isFixedLengthVector() &&
1552          "Expected a fixed length vector operand!");
1553   SDLoc DL(V);
1554   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1555   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1556 }
1557 
1558 // Shrink V so it's just big enough to maintain a VT's worth of data.
1559 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1560                                          const RISCVSubtarget &Subtarget) {
1561   assert(VT.isFixedLengthVector() &&
1562          "Expected to convert into a fixed length vector!");
1563   assert(V.getValueType().isScalableVector() &&
1564          "Expected a scalable vector operand!");
1565   SDLoc DL(V);
1566   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1567   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1568 }
1569 
1570 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1571 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1572 // the vector type that it is contained in.
1573 static std::pair<SDValue, SDValue>
1574 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1575                 const RISCVSubtarget &Subtarget) {
1576   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1577   MVT XLenVT = Subtarget.getXLenVT();
1578   SDValue VL = VecVT.isFixedLengthVector()
1579                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1580                    : DAG.getRegister(RISCV::X0, XLenVT);
1581   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1582   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1583   return {Mask, VL};
1584 }
1585 
1586 // As above but assuming the given type is a scalable vector type.
1587 static std::pair<SDValue, SDValue>
1588 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1589                         const RISCVSubtarget &Subtarget) {
1590   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1591   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1592 }
1593 
1594 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1595 // of either is (currently) supported. This can get us into an infinite loop
1596 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1597 // as a ..., etc.
1598 // Until either (or both) of these can reliably lower any node, reporting that
1599 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1600 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1601 // which is not desirable.
1602 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1603     EVT VT, unsigned DefinedValues) const {
1604   return false;
1605 }
1606 
1607 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1608                                   const RISCVSubtarget &Subtarget) {
1609   // RISCV FP-to-int conversions saturate to the destination register size, but
1610   // don't produce 0 for nan. We can use a conversion instruction and fix the
1611   // nan case with a compare and a select.
1612   SDValue Src = Op.getOperand(0);
1613 
1614   EVT DstVT = Op.getValueType();
1615   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1616 
1617   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1618   unsigned Opc;
1619   if (SatVT == DstVT)
1620     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1621   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1622     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1623   else
1624     return SDValue();
1625   // FIXME: Support other SatVTs by clamping before or after the conversion.
1626 
1627   SDLoc DL(Op);
1628   SDValue FpToInt = DAG.getNode(
1629       Opc, DL, DstVT, Src,
1630       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1631 
1632   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1633   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1634 }
1635 
1636 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1637 // and back. Taking care to avoid converting values that are nan or already
1638 // correct.
1639 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1640 // have FRM dependencies modeled yet.
1641 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1642   MVT VT = Op.getSimpleValueType();
1643   assert(VT.isVector() && "Unexpected type");
1644 
1645   SDLoc DL(Op);
1646 
1647   // Freeze the source since we are increasing the number of uses.
1648   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1649 
1650   // Truncate to integer and convert back to FP.
1651   MVT IntVT = VT.changeVectorElementTypeToInteger();
1652   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1653   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1654 
1655   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1656 
1657   if (Op.getOpcode() == ISD::FCEIL) {
1658     // If the truncated value is the greater than or equal to the original
1659     // value, we've computed the ceil. Otherwise, we went the wrong way and
1660     // need to increase by 1.
1661     // FIXME: This should use a masked operation. Handle here or in isel?
1662     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1663                                  DAG.getConstantFP(1.0, DL, VT));
1664     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1665     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1666   } else if (Op.getOpcode() == ISD::FFLOOR) {
1667     // If the truncated value is the less than or equal to the original value,
1668     // we've computed the floor. Otherwise, we went the wrong way and need to
1669     // decrease by 1.
1670     // FIXME: This should use a masked operation. Handle here or in isel?
1671     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1672                                  DAG.getConstantFP(1.0, DL, VT));
1673     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1674     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1675   }
1676 
1677   // Restore the original sign so that -0.0 is preserved.
1678   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1679 
1680   // Determine the largest integer that can be represented exactly. This and
1681   // values larger than it don't have any fractional bits so don't need to
1682   // be converted.
1683   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1684   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1685   APFloat MaxVal = APFloat(FltSem);
1686   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1687                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1688   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1689 
1690   // If abs(Src) was larger than MaxVal or nan, keep it.
1691   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1692   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1693   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1694 }
1695 
1696 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1697 // This mode isn't supported in vector hardware on RISCV. But as long as we
1698 // aren't compiling with trapping math, we can emulate this with
1699 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1700 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1701 // dependencies modeled yet.
1702 // FIXME: Use masked operations to avoid final merge.
1703 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1704   MVT VT = Op.getSimpleValueType();
1705   assert(VT.isVector() && "Unexpected type");
1706 
1707   SDLoc DL(Op);
1708 
1709   // Freeze the source since we are increasing the number of uses.
1710   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1711 
1712   // We do the conversion on the absolute value and fix the sign at the end.
1713   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1714 
1715   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1716   bool Ignored;
1717   APFloat Point5Pred = APFloat(0.5f);
1718   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1719   Point5Pred.next(/*nextDown*/ true);
1720 
1721   // Add the adjustment.
1722   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1723                                DAG.getConstantFP(Point5Pred, DL, VT));
1724 
1725   // Truncate to integer and convert back to fp.
1726   MVT IntVT = VT.changeVectorElementTypeToInteger();
1727   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1728   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1729 
1730   // Restore the original sign.
1731   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1732 
1733   // Determine the largest integer that can be represented exactly. This and
1734   // values larger than it don't have any fractional bits so don't need to
1735   // be converted.
1736   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1737   APFloat MaxVal = APFloat(FltSem);
1738   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1739                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1740   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1741 
1742   // If abs(Src) was larger than MaxVal or nan, keep it.
1743   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1744   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1745   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1746 }
1747 
1748 struct VIDSequence {
1749   int64_t StepNumerator;
1750   unsigned StepDenominator;
1751   int64_t Addend;
1752 };
1753 
1754 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1755 // to the (non-zero) step S and start value X. This can be then lowered as the
1756 // RVV sequence (VID * S) + X, for example.
1757 // The step S is represented as an integer numerator divided by a positive
1758 // denominator. Note that the implementation currently only identifies
1759 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1760 // cannot detect 2/3, for example.
1761 // Note that this method will also match potentially unappealing index
1762 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1763 // determine whether this is worth generating code for.
1764 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1765   unsigned NumElts = Op.getNumOperands();
1766   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1767   if (!Op.getValueType().isInteger())
1768     return None;
1769 
1770   Optional<unsigned> SeqStepDenom;
1771   Optional<int64_t> SeqStepNum, SeqAddend;
1772   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1773   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1774   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1775     // Assume undef elements match the sequence; we just have to be careful
1776     // when interpolating across them.
1777     if (Op.getOperand(Idx).isUndef())
1778       continue;
1779     // The BUILD_VECTOR must be all constants.
1780     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1781       return None;
1782 
1783     uint64_t Val = Op.getConstantOperandVal(Idx) &
1784                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1785 
1786     if (PrevElt) {
1787       // Calculate the step since the last non-undef element, and ensure
1788       // it's consistent across the entire sequence.
1789       unsigned IdxDiff = Idx - PrevElt->second;
1790       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1791 
1792       // A zero-value value difference means that we're somewhere in the middle
1793       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1794       // step change before evaluating the sequence.
1795       if (ValDiff == 0)
1796         continue;
1797 
1798       int64_t Remainder = ValDiff % IdxDiff;
1799       // Normalize the step if it's greater than 1.
1800       if (Remainder != ValDiff) {
1801         // The difference must cleanly divide the element span.
1802         if (Remainder != 0)
1803           return None;
1804         ValDiff /= IdxDiff;
1805         IdxDiff = 1;
1806       }
1807 
1808       if (!SeqStepNum)
1809         SeqStepNum = ValDiff;
1810       else if (ValDiff != SeqStepNum)
1811         return None;
1812 
1813       if (!SeqStepDenom)
1814         SeqStepDenom = IdxDiff;
1815       else if (IdxDiff != *SeqStepDenom)
1816         return None;
1817     }
1818 
1819     // Record this non-undef element for later.
1820     if (!PrevElt || PrevElt->first != Val)
1821       PrevElt = std::make_pair(Val, Idx);
1822   }
1823 
1824   // We need to have logged a step for this to count as a legal index sequence.
1825   if (!SeqStepNum || !SeqStepDenom)
1826     return None;
1827 
1828   // Loop back through the sequence and validate elements we might have skipped
1829   // while waiting for a valid step. While doing this, log any sequence addend.
1830   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1831     if (Op.getOperand(Idx).isUndef())
1832       continue;
1833     uint64_t Val = Op.getConstantOperandVal(Idx) &
1834                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1835     uint64_t ExpectedVal =
1836         (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1837     int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1838     if (!SeqAddend)
1839       SeqAddend = Addend;
1840     else if (Addend != SeqAddend)
1841       return None;
1842   }
1843 
1844   assert(SeqAddend && "Must have an addend if we have a step");
1845 
1846   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1847 }
1848 
1849 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1850 // and lower it as a VRGATHER_VX_VL from the source vector.
1851 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
1852                                   SelectionDAG &DAG,
1853                                   const RISCVSubtarget &Subtarget) {
1854   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1855     return SDValue();
1856   SDValue Vec = SplatVal.getOperand(0);
1857   // Only perform this optimization on vectors of the same size for simplicity.
1858   if (Vec.getValueType() != VT)
1859     return SDValue();
1860   SDValue Idx = SplatVal.getOperand(1);
1861   // The index must be a legal type.
1862   if (Idx.getValueType() != Subtarget.getXLenVT())
1863     return SDValue();
1864 
1865   MVT ContainerVT = VT;
1866   if (VT.isFixedLengthVector()) {
1867     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1868     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
1869   }
1870 
1871   SDValue Mask, VL;
1872   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1873 
1874   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
1875                                Idx, Mask, VL);
1876 
1877   if (!VT.isFixedLengthVector())
1878     return Gather;
1879 
1880   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
1881 }
1882 
1883 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1884                                  const RISCVSubtarget &Subtarget) {
1885   MVT VT = Op.getSimpleValueType();
1886   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1887 
1888   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1889 
1890   SDLoc DL(Op);
1891   SDValue Mask, VL;
1892   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1893 
1894   MVT XLenVT = Subtarget.getXLenVT();
1895   unsigned NumElts = Op.getNumOperands();
1896 
1897   if (VT.getVectorElementType() == MVT::i1) {
1898     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1899       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1900       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1901     }
1902 
1903     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1904       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1905       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1906     }
1907 
1908     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1909     // scalar integer chunks whose bit-width depends on the number of mask
1910     // bits and XLEN.
1911     // First, determine the most appropriate scalar integer type to use. This
1912     // is at most XLenVT, but may be shrunk to a smaller vector element type
1913     // according to the size of the final vector - use i8 chunks rather than
1914     // XLenVT if we're producing a v8i1. This results in more consistent
1915     // codegen across RV32 and RV64.
1916     unsigned NumViaIntegerBits =
1917         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1918     NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN());
1919     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1920       // If we have to use more than one INSERT_VECTOR_ELT then this
1921       // optimization is likely to increase code size; avoid peforming it in
1922       // such a case. We can use a load from a constant pool in this case.
1923       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1924         return SDValue();
1925       // Now we can create our integer vector type. Note that it may be larger
1926       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1927       MVT IntegerViaVecVT =
1928           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1929                            divideCeil(NumElts, NumViaIntegerBits));
1930 
1931       uint64_t Bits = 0;
1932       unsigned BitPos = 0, IntegerEltIdx = 0;
1933       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1934 
1935       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1936         // Once we accumulate enough bits to fill our scalar type, insert into
1937         // our vector and clear our accumulated data.
1938         if (I != 0 && I % NumViaIntegerBits == 0) {
1939           if (NumViaIntegerBits <= 32)
1940             Bits = SignExtend64(Bits, 32);
1941           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1942           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1943                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1944           Bits = 0;
1945           BitPos = 0;
1946           IntegerEltIdx++;
1947         }
1948         SDValue V = Op.getOperand(I);
1949         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1950         Bits |= ((uint64_t)BitValue << BitPos);
1951       }
1952 
1953       // Insert the (remaining) scalar value into position in our integer
1954       // vector type.
1955       if (NumViaIntegerBits <= 32)
1956         Bits = SignExtend64(Bits, 32);
1957       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1958       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
1959                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1960 
1961       if (NumElts < NumViaIntegerBits) {
1962         // If we're producing a smaller vector than our minimum legal integer
1963         // type, bitcast to the equivalent (known-legal) mask type, and extract
1964         // our final mask.
1965         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
1966         Vec = DAG.getBitcast(MVT::v8i1, Vec);
1967         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
1968                           DAG.getConstant(0, DL, XLenVT));
1969       } else {
1970         // Else we must have produced an integer type with the same size as the
1971         // mask type; bitcast for the final result.
1972         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
1973         Vec = DAG.getBitcast(VT, Vec);
1974       }
1975 
1976       return Vec;
1977     }
1978 
1979     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
1980     // vector type, we have a legal equivalently-sized i8 type, so we can use
1981     // that.
1982     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
1983     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
1984 
1985     SDValue WideVec;
1986     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1987       // For a splat, perform a scalar truncate before creating the wider
1988       // vector.
1989       assert(Splat.getValueType() == XLenVT &&
1990              "Unexpected type for i1 splat value");
1991       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
1992                           DAG.getConstant(1, DL, XLenVT));
1993       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
1994     } else {
1995       SmallVector<SDValue, 8> Ops(Op->op_values());
1996       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
1997       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
1998       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
1999     }
2000 
2001     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2002   }
2003 
2004   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2005     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2006       return Gather;
2007     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2008                                         : RISCVISD::VMV_V_X_VL;
2009     Splat =
2010         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2011     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2012   }
2013 
2014   // Try and match index sequences, which we can lower to the vid instruction
2015   // with optional modifications. An all-undef vector is matched by
2016   // getSplatValue, above.
2017   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2018     int64_t StepNumerator = SimpleVID->StepNumerator;
2019     unsigned StepDenominator = SimpleVID->StepDenominator;
2020     int64_t Addend = SimpleVID->Addend;
2021 
2022     assert(StepNumerator != 0 && "Invalid step");
2023     bool Negate = false;
2024     int64_t SplatStepVal = StepNumerator;
2025     unsigned StepOpcode = ISD::MUL;
2026     if (StepNumerator != 1) {
2027       if (isPowerOf2_64(std::abs(StepNumerator))) {
2028         Negate = StepNumerator < 0;
2029         StepOpcode = ISD::SHL;
2030         SplatStepVal = Log2_64(std::abs(StepNumerator));
2031       }
2032     }
2033 
2034     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2035     // threshold since it's the immediate value many RVV instructions accept.
2036     // There is no vmul.vi instruction so ensure multiply constant can fit in
2037     // a single addi instruction.
2038     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2039          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2040         isPowerOf2_32(StepDenominator) &&
2041         (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) {
2042       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2043       // Convert right out of the scalable type so we can use standard ISD
2044       // nodes for the rest of the computation. If we used scalable types with
2045       // these, we'd lose the fixed-length vector info and generate worse
2046       // vsetvli code.
2047       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2048       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2049           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2050         SDValue SplatStep = DAG.getSplatBuildVector(
2051             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2052         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2053       }
2054       if (StepDenominator != 1) {
2055         SDValue SplatStep = DAG.getSplatBuildVector(
2056             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2057         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2058       }
2059       if (Addend != 0 || Negate) {
2060         SDValue SplatAddend = DAG.getSplatBuildVector(
2061             VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2062         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2063       }
2064       return VID;
2065     }
2066   }
2067 
2068   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2069   // when re-interpreted as a vector with a larger element type. For example,
2070   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2071   // could be instead splat as
2072   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2073   // TODO: This optimization could also work on non-constant splats, but it
2074   // would require bit-manipulation instructions to construct the splat value.
2075   SmallVector<SDValue> Sequence;
2076   unsigned EltBitSize = VT.getScalarSizeInBits();
2077   const auto *BV = cast<BuildVectorSDNode>(Op);
2078   if (VT.isInteger() && EltBitSize < 64 &&
2079       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2080       BV->getRepeatedSequence(Sequence) &&
2081       (Sequence.size() * EltBitSize) <= 64) {
2082     unsigned SeqLen = Sequence.size();
2083     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2084     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2085     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2086             ViaIntVT == MVT::i64) &&
2087            "Unexpected sequence type");
2088 
2089     unsigned EltIdx = 0;
2090     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2091     uint64_t SplatValue = 0;
2092     // Construct the amalgamated value which can be splatted as this larger
2093     // vector type.
2094     for (const auto &SeqV : Sequence) {
2095       if (!SeqV.isUndef())
2096         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2097                        << (EltIdx * EltBitSize));
2098       EltIdx++;
2099     }
2100 
2101     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2102     // achieve better constant materializion.
2103     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2104       SplatValue = SignExtend64(SplatValue, 32);
2105 
2106     // Since we can't introduce illegal i64 types at this stage, we can only
2107     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2108     // way we can use RVV instructions to splat.
2109     assert((ViaIntVT.bitsLE(XLenVT) ||
2110             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2111            "Unexpected bitcast sequence");
2112     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2113       SDValue ViaVL =
2114           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2115       MVT ViaContainerVT =
2116           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2117       SDValue Splat =
2118           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2119                       DAG.getUNDEF(ViaContainerVT),
2120                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2121       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2122       return DAG.getBitcast(VT, Splat);
2123     }
2124   }
2125 
2126   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2127   // which constitute a large proportion of the elements. In such cases we can
2128   // splat a vector with the dominant element and make up the shortfall with
2129   // INSERT_VECTOR_ELTs.
2130   // Note that this includes vectors of 2 elements by association. The
2131   // upper-most element is the "dominant" one, allowing us to use a splat to
2132   // "insert" the upper element, and an insert of the lower element at position
2133   // 0, which improves codegen.
2134   SDValue DominantValue;
2135   unsigned MostCommonCount = 0;
2136   DenseMap<SDValue, unsigned> ValueCounts;
2137   unsigned NumUndefElts =
2138       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2139 
2140   // Track the number of scalar loads we know we'd be inserting, estimated as
2141   // any non-zero floating-point constant. Other kinds of element are either
2142   // already in registers or are materialized on demand. The threshold at which
2143   // a vector load is more desirable than several scalar materializion and
2144   // vector-insertion instructions is not known.
2145   unsigned NumScalarLoads = 0;
2146 
2147   for (SDValue V : Op->op_values()) {
2148     if (V.isUndef())
2149       continue;
2150 
2151     ValueCounts.insert(std::make_pair(V, 0));
2152     unsigned &Count = ValueCounts[V];
2153 
2154     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2155       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2156 
2157     // Is this value dominant? In case of a tie, prefer the highest element as
2158     // it's cheaper to insert near the beginning of a vector than it is at the
2159     // end.
2160     if (++Count >= MostCommonCount) {
2161       DominantValue = V;
2162       MostCommonCount = Count;
2163     }
2164   }
2165 
2166   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2167   unsigned NumDefElts = NumElts - NumUndefElts;
2168   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2169 
2170   // Don't perform this optimization when optimizing for size, since
2171   // materializing elements and inserting them tends to cause code bloat.
2172   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2173       ((MostCommonCount > DominantValueCountThreshold) ||
2174        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2175     // Start by splatting the most common element.
2176     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2177 
2178     DenseSet<SDValue> Processed{DominantValue};
2179     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2180     for (const auto &OpIdx : enumerate(Op->ops())) {
2181       const SDValue &V = OpIdx.value();
2182       if (V.isUndef() || !Processed.insert(V).second)
2183         continue;
2184       if (ValueCounts[V] == 1) {
2185         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2186                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2187       } else {
2188         // Blend in all instances of this value using a VSELECT, using a
2189         // mask where each bit signals whether that element is the one
2190         // we're after.
2191         SmallVector<SDValue> Ops;
2192         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2193           return DAG.getConstant(V == V1, DL, XLenVT);
2194         });
2195         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2196                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2197                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2198       }
2199     }
2200 
2201     return Vec;
2202   }
2203 
2204   return SDValue();
2205 }
2206 
2207 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2208                                    SDValue Lo, SDValue Hi, SDValue VL,
2209                                    SelectionDAG &DAG) {
2210   if (!Passthru)
2211     Passthru = DAG.getUNDEF(VT);
2212   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2213     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2214     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2215     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2216     // node in order to try and match RVV vector/scalar instructions.
2217     if ((LoC >> 31) == HiC)
2218       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2219 
2220     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2221     // vmv.v.x whose EEW = 32 to lower it.
2222     auto *Const = dyn_cast<ConstantSDNode>(VL);
2223     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2224       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2225       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2226       // access the subtarget here now.
2227       auto InterVec = DAG.getNode(
2228           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2229                                   DAG.getRegister(RISCV::X0, MVT::i32));
2230       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2231     }
2232   }
2233 
2234   // Fall back to a stack store and stride x0 vector load.
2235   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2236                      Hi, VL);
2237 }
2238 
2239 // Called by type legalization to handle splat of i64 on RV32.
2240 // FIXME: We can optimize this when the type has sign or zero bits in one
2241 // of the halves.
2242 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2243                                    SDValue Scalar, SDValue VL,
2244                                    SelectionDAG &DAG) {
2245   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2246   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2247                            DAG.getConstant(0, DL, MVT::i32));
2248   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2249                            DAG.getConstant(1, DL, MVT::i32));
2250   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2251 }
2252 
2253 // This function lowers a splat of a scalar operand Splat with the vector
2254 // length VL. It ensures the final sequence is type legal, which is useful when
2255 // lowering a splat after type legalization.
2256 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2257                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2258                                 const RISCVSubtarget &Subtarget) {
2259   bool HasPassthru = Passthru && !Passthru.isUndef();
2260   if (!HasPassthru && !Passthru)
2261     Passthru = DAG.getUNDEF(VT);
2262   if (VT.isFloatingPoint()) {
2263     // If VL is 1, we could use vfmv.s.f.
2264     if (isOneConstant(VL))
2265       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2266     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2267   }
2268 
2269   MVT XLenVT = Subtarget.getXLenVT();
2270 
2271   // Simplest case is that the operand needs to be promoted to XLenVT.
2272   if (Scalar.getValueType().bitsLE(XLenVT)) {
2273     // If the operand is a constant, sign extend to increase our chances
2274     // of being able to use a .vi instruction. ANY_EXTEND would become a
2275     // a zero extend and the simm5 check in isel would fail.
2276     // FIXME: Should we ignore the upper bits in isel instead?
2277     unsigned ExtOpc =
2278         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2279     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2280     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2281     // If VL is 1 and the scalar value won't benefit from immediate, we could
2282     // use vmv.s.x.
2283     if (isOneConstant(VL) &&
2284         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2285       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2286     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2287   }
2288 
2289   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2290          "Unexpected scalar for splat lowering!");
2291 
2292   if (isOneConstant(VL) && isNullConstant(Scalar))
2293     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2294                        DAG.getConstant(0, DL, XLenVT), VL);
2295 
2296   // Otherwise use the more complicated splatting algorithm.
2297   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2298 }
2299 
2300 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2301                                 const RISCVSubtarget &Subtarget) {
2302   // We need to be able to widen elements to the next larger integer type.
2303   if (VT.getScalarSizeInBits() >= Subtarget.getELEN())
2304     return false;
2305 
2306   int Size = Mask.size();
2307   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2308 
2309   int Srcs[] = {-1, -1};
2310   for (int i = 0; i != Size; ++i) {
2311     // Ignore undef elements.
2312     if (Mask[i] < 0)
2313       continue;
2314 
2315     // Is this an even or odd element.
2316     int Pol = i % 2;
2317 
2318     // Ensure we consistently use the same source for this element polarity.
2319     int Src = Mask[i] / Size;
2320     if (Srcs[Pol] < 0)
2321       Srcs[Pol] = Src;
2322     if (Srcs[Pol] != Src)
2323       return false;
2324 
2325     // Make sure the element within the source is appropriate for this element
2326     // in the destination.
2327     int Elt = Mask[i] % Size;
2328     if (Elt != i / 2)
2329       return false;
2330   }
2331 
2332   // We need to find a source for each polarity and they can't be the same.
2333   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2334     return false;
2335 
2336   // Swap the sources if the second source was in the even polarity.
2337   SwapSources = Srcs[0] > Srcs[1];
2338 
2339   return true;
2340 }
2341 
2342 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2343 /// and then extract the original number of elements from the rotated result.
2344 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2345 /// returned rotation amount is for a rotate right, where elements move from
2346 /// higher elements to lower elements. \p LoSrc indicates the first source
2347 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2348 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2349 /// 0 or 1 if a rotation is found.
2350 ///
2351 /// NOTE: We talk about rotate to the right which matches how bit shift and
2352 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2353 /// and the table below write vectors with the lowest elements on the left.
2354 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2355   int Size = Mask.size();
2356 
2357   // We need to detect various ways of spelling a rotation:
2358   //   [11, 12, 13, 14, 15,  0,  1,  2]
2359   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2360   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2361   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2362   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2363   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2364   int Rotation = 0;
2365   LoSrc = -1;
2366   HiSrc = -1;
2367   for (int i = 0; i != Size; ++i) {
2368     int M = Mask[i];
2369     if (M < 0)
2370       continue;
2371 
2372     // Determine where a rotate vector would have started.
2373     int StartIdx = i - (M % Size);
2374     // The identity rotation isn't interesting, stop.
2375     if (StartIdx == 0)
2376       return -1;
2377 
2378     // If we found the tail of a vector the rotation must be the missing
2379     // front. If we found the head of a vector, it must be how much of the
2380     // head.
2381     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2382 
2383     if (Rotation == 0)
2384       Rotation = CandidateRotation;
2385     else if (Rotation != CandidateRotation)
2386       // The rotations don't match, so we can't match this mask.
2387       return -1;
2388 
2389     // Compute which value this mask is pointing at.
2390     int MaskSrc = M < Size ? 0 : 1;
2391 
2392     // Compute which of the two target values this index should be assigned to.
2393     // This reflects whether the high elements are remaining or the low elemnts
2394     // are remaining.
2395     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2396 
2397     // Either set up this value if we've not encountered it before, or check
2398     // that it remains consistent.
2399     if (TargetSrc < 0)
2400       TargetSrc = MaskSrc;
2401     else if (TargetSrc != MaskSrc)
2402       // This may be a rotation, but it pulls from the inputs in some
2403       // unsupported interleaving.
2404       return -1;
2405   }
2406 
2407   // Check that we successfully analyzed the mask, and normalize the results.
2408   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2409   assert((LoSrc >= 0 || HiSrc >= 0) &&
2410          "Failed to find a rotated input vector!");
2411 
2412   return Rotation;
2413 }
2414 
2415 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2416                                    const RISCVSubtarget &Subtarget) {
2417   SDValue V1 = Op.getOperand(0);
2418   SDValue V2 = Op.getOperand(1);
2419   SDLoc DL(Op);
2420   MVT XLenVT = Subtarget.getXLenVT();
2421   MVT VT = Op.getSimpleValueType();
2422   unsigned NumElts = VT.getVectorNumElements();
2423   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2424 
2425   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2426 
2427   SDValue TrueMask, VL;
2428   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2429 
2430   if (SVN->isSplat()) {
2431     const int Lane = SVN->getSplatIndex();
2432     if (Lane >= 0) {
2433       MVT SVT = VT.getVectorElementType();
2434 
2435       // Turn splatted vector load into a strided load with an X0 stride.
2436       SDValue V = V1;
2437       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2438       // with undef.
2439       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2440       int Offset = Lane;
2441       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2442         int OpElements =
2443             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2444         V = V.getOperand(Offset / OpElements);
2445         Offset %= OpElements;
2446       }
2447 
2448       // We need to ensure the load isn't atomic or volatile.
2449       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2450         auto *Ld = cast<LoadSDNode>(V);
2451         Offset *= SVT.getStoreSize();
2452         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2453                                                    TypeSize::Fixed(Offset), DL);
2454 
2455         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2456         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2457           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2458           SDValue IntID =
2459               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2460           SDValue Ops[] = {Ld->getChain(),
2461                            IntID,
2462                            DAG.getUNDEF(ContainerVT),
2463                            NewAddr,
2464                            DAG.getRegister(RISCV::X0, XLenVT),
2465                            VL};
2466           SDValue NewLoad = DAG.getMemIntrinsicNode(
2467               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2468               DAG.getMachineFunction().getMachineMemOperand(
2469                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2470           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2471           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2472         }
2473 
2474         // Otherwise use a scalar load and splat. This will give the best
2475         // opportunity to fold a splat into the operation. ISel can turn it into
2476         // the x0 strided load if we aren't able to fold away the select.
2477         if (SVT.isFloatingPoint())
2478           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2479                           Ld->getPointerInfo().getWithOffset(Offset),
2480                           Ld->getOriginalAlign(),
2481                           Ld->getMemOperand()->getFlags());
2482         else
2483           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2484                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2485                              Ld->getOriginalAlign(),
2486                              Ld->getMemOperand()->getFlags());
2487         DAG.makeEquivalentMemoryOrdering(Ld, V);
2488 
2489         unsigned Opc =
2490             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2491         SDValue Splat =
2492             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2493         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2494       }
2495 
2496       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2497       assert(Lane < (int)NumElts && "Unexpected lane!");
2498       SDValue Gather =
2499           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2500                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2501       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2502     }
2503   }
2504 
2505   ArrayRef<int> Mask = SVN->getMask();
2506 
2507   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2508   // be undef which can be handled with a single SLIDEDOWN/UP.
2509   int LoSrc, HiSrc;
2510   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2511   if (Rotation > 0) {
2512     SDValue LoV, HiV;
2513     if (LoSrc >= 0) {
2514       LoV = LoSrc == 0 ? V1 : V2;
2515       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2516     }
2517     if (HiSrc >= 0) {
2518       HiV = HiSrc == 0 ? V1 : V2;
2519       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2520     }
2521 
2522     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2523     // to slide LoV up by (NumElts - Rotation).
2524     unsigned InvRotate = NumElts - Rotation;
2525 
2526     SDValue Res = DAG.getUNDEF(ContainerVT);
2527     if (HiV) {
2528       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2529       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2530       // causes multiple vsetvlis in some test cases such as lowering
2531       // reduce.mul
2532       SDValue DownVL = VL;
2533       if (LoV)
2534         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2535       Res =
2536           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2537                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2538     }
2539     if (LoV)
2540       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2541                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2542 
2543     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2544   }
2545 
2546   // Detect an interleave shuffle and lower to
2547   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2548   bool SwapSources;
2549   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2550     // Swap sources if needed.
2551     if (SwapSources)
2552       std::swap(V1, V2);
2553 
2554     // Extract the lower half of the vectors.
2555     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2556     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2557                      DAG.getConstant(0, DL, XLenVT));
2558     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2559                      DAG.getConstant(0, DL, XLenVT));
2560 
2561     // Double the element width and halve the number of elements in an int type.
2562     unsigned EltBits = VT.getScalarSizeInBits();
2563     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2564     MVT WideIntVT =
2565         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2566     // Convert this to a scalable vector. We need to base this on the
2567     // destination size to ensure there's always a type with a smaller LMUL.
2568     MVT WideIntContainerVT =
2569         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2570 
2571     // Convert sources to scalable vectors with the same element count as the
2572     // larger type.
2573     MVT HalfContainerVT = MVT::getVectorVT(
2574         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2575     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2576     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2577 
2578     // Cast sources to integer.
2579     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2580     MVT IntHalfVT =
2581         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2582     V1 = DAG.getBitcast(IntHalfVT, V1);
2583     V2 = DAG.getBitcast(IntHalfVT, V2);
2584 
2585     // Freeze V2 since we use it twice and we need to be sure that the add and
2586     // multiply see the same value.
2587     V2 = DAG.getFreeze(V2);
2588 
2589     // Recreate TrueMask using the widened type's element count.
2590     MVT MaskVT =
2591         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2592     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2593 
2594     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2595     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2596                               V2, TrueMask, VL);
2597     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2598     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2599                                      DAG.getUNDEF(IntHalfVT),
2600                                      DAG.getAllOnesConstant(DL, XLenVT));
2601     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2602                                    V2, Multiplier, TrueMask, VL);
2603     // Add the new copies to our previous addition giving us 2^eltbits copies of
2604     // V2. This is equivalent to shifting V2 left by eltbits. This should
2605     // combine with the vwmulu.vv above to form vwmaccu.vv.
2606     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2607                       TrueMask, VL);
2608     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2609     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2610     // vector VT.
2611     ContainerVT =
2612         MVT::getVectorVT(VT.getVectorElementType(),
2613                          WideIntContainerVT.getVectorElementCount() * 2);
2614     Add = DAG.getBitcast(ContainerVT, Add);
2615     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2616   }
2617 
2618   // Detect shuffles which can be re-expressed as vector selects; these are
2619   // shuffles in which each element in the destination is taken from an element
2620   // at the corresponding index in either source vectors.
2621   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2622     int MaskIndex = MaskIdx.value();
2623     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2624   });
2625 
2626   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2627 
2628   SmallVector<SDValue> MaskVals;
2629   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2630   // merged with a second vrgather.
2631   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2632 
2633   // By default we preserve the original operand order, and use a mask to
2634   // select LHS as true and RHS as false. However, since RVV vector selects may
2635   // feature splats but only on the LHS, we may choose to invert our mask and
2636   // instead select between RHS and LHS.
2637   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2638   bool InvertMask = IsSelect == SwapOps;
2639 
2640   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2641   // half.
2642   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2643 
2644   // Now construct the mask that will be used by the vselect or blended
2645   // vrgather operation. For vrgathers, construct the appropriate indices into
2646   // each vector.
2647   for (int MaskIndex : Mask) {
2648     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2649     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2650     if (!IsSelect) {
2651       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2652       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2653                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2654                                      : DAG.getUNDEF(XLenVT));
2655       GatherIndicesRHS.push_back(
2656           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2657                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2658       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2659         ++LHSIndexCounts[MaskIndex];
2660       if (!IsLHSOrUndefIndex)
2661         ++RHSIndexCounts[MaskIndex - NumElts];
2662     }
2663   }
2664 
2665   if (SwapOps) {
2666     std::swap(V1, V2);
2667     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2668   }
2669 
2670   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2671   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2672   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2673 
2674   if (IsSelect)
2675     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2676 
2677   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2678     // On such a large vector we're unable to use i8 as the index type.
2679     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2680     // may involve vector splitting if we're already at LMUL=8, or our
2681     // user-supplied maximum fixed-length LMUL.
2682     return SDValue();
2683   }
2684 
2685   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2686   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2687   MVT IndexVT = VT.changeTypeToInteger();
2688   // Since we can't introduce illegal index types at this stage, use i16 and
2689   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2690   // than XLenVT.
2691   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2692     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2693     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2694   }
2695 
2696   MVT IndexContainerVT =
2697       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2698 
2699   SDValue Gather;
2700   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2701   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2702   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2703     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2704                               Subtarget);
2705   } else {
2706     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2707     // If only one index is used, we can use a "splat" vrgather.
2708     // TODO: We can splat the most-common index and fix-up any stragglers, if
2709     // that's beneficial.
2710     if (LHSIndexCounts.size() == 1) {
2711       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2712       Gather =
2713           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2714                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2715     } else {
2716       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2717       LHSIndices =
2718           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2719 
2720       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2721                            TrueMask, VL);
2722     }
2723   }
2724 
2725   // If a second vector operand is used by this shuffle, blend it in with an
2726   // additional vrgather.
2727   if (!V2.isUndef()) {
2728     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2729     // If only one index is used, we can use a "splat" vrgather.
2730     // TODO: We can splat the most-common index and fix-up any stragglers, if
2731     // that's beneficial.
2732     if (RHSIndexCounts.size() == 1) {
2733       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2734       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2735                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2736     } else {
2737       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2738       RHSIndices =
2739           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2740       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2741                        VL);
2742     }
2743 
2744     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2745     SelectMask =
2746         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2747 
2748     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2749                          Gather, VL);
2750   }
2751 
2752   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2753 }
2754 
2755 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2756   // Support splats for any type. These should type legalize well.
2757   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2758     return true;
2759 
2760   // Only support legal VTs for other shuffles for now.
2761   if (!isTypeLegal(VT))
2762     return false;
2763 
2764   MVT SVT = VT.getSimpleVT();
2765 
2766   bool SwapSources;
2767   int LoSrc, HiSrc;
2768   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2769          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2770 }
2771 
2772 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2773                                      SDLoc DL, SelectionDAG &DAG,
2774                                      const RISCVSubtarget &Subtarget) {
2775   if (VT.isScalableVector())
2776     return DAG.getFPExtendOrRound(Op, DL, VT);
2777   assert(VT.isFixedLengthVector() &&
2778          "Unexpected value type for RVV FP extend/round lowering");
2779   SDValue Mask, VL;
2780   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2781   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2782                         ? RISCVISD::FP_EXTEND_VL
2783                         : RISCVISD::FP_ROUND_VL;
2784   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2785 }
2786 
2787 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2788 // the exponent.
2789 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2790   MVT VT = Op.getSimpleValueType();
2791   unsigned EltSize = VT.getScalarSizeInBits();
2792   SDValue Src = Op.getOperand(0);
2793   SDLoc DL(Op);
2794 
2795   // We need a FP type that can represent the value.
2796   // TODO: Use f16 for i8 when possible?
2797   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2798   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2799 
2800   // Legal types should have been checked in the RISCVTargetLowering
2801   // constructor.
2802   // TODO: Splitting may make sense in some cases.
2803   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2804          "Expected legal float type!");
2805 
2806   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2807   // The trailing zero count is equal to log2 of this single bit value.
2808   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2809     SDValue Neg =
2810         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2811     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2812   }
2813 
2814   // We have a legal FP type, convert to it.
2815   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2816   // Bitcast to integer and shift the exponent to the LSB.
2817   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2818   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2819   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2820   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2821                               DAG.getConstant(ShiftAmt, DL, IntVT));
2822   // Truncate back to original type to allow vnsrl.
2823   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2824   // The exponent contains log2 of the value in biased form.
2825   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2826 
2827   // For trailing zeros, we just need to subtract the bias.
2828   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2829     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2830                        DAG.getConstant(ExponentBias, DL, VT));
2831 
2832   // For leading zeros, we need to remove the bias and convert from log2 to
2833   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2834   unsigned Adjust = ExponentBias + (EltSize - 1);
2835   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2836 }
2837 
2838 // While RVV has alignment restrictions, we should always be able to load as a
2839 // legal equivalently-sized byte-typed vector instead. This method is
2840 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2841 // the load is already correctly-aligned, it returns SDValue().
2842 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2843                                                     SelectionDAG &DAG) const {
2844   auto *Load = cast<LoadSDNode>(Op);
2845   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2846 
2847   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2848                                      Load->getMemoryVT(),
2849                                      *Load->getMemOperand()))
2850     return SDValue();
2851 
2852   SDLoc DL(Op);
2853   MVT VT = Op.getSimpleValueType();
2854   unsigned EltSizeBits = VT.getScalarSizeInBits();
2855   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2856          "Unexpected unaligned RVV load type");
2857   MVT NewVT =
2858       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2859   assert(NewVT.isValid() &&
2860          "Expecting equally-sized RVV vector types to be legal");
2861   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2862                           Load->getPointerInfo(), Load->getOriginalAlign(),
2863                           Load->getMemOperand()->getFlags());
2864   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2865 }
2866 
2867 // While RVV has alignment restrictions, we should always be able to store as a
2868 // legal equivalently-sized byte-typed vector instead. This method is
2869 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2870 // returns SDValue() if the store is already correctly aligned.
2871 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2872                                                      SelectionDAG &DAG) const {
2873   auto *Store = cast<StoreSDNode>(Op);
2874   assert(Store && Store->getValue().getValueType().isVector() &&
2875          "Expected vector store");
2876 
2877   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2878                                      Store->getMemoryVT(),
2879                                      *Store->getMemOperand()))
2880     return SDValue();
2881 
2882   SDLoc DL(Op);
2883   SDValue StoredVal = Store->getValue();
2884   MVT VT = StoredVal.getSimpleValueType();
2885   unsigned EltSizeBits = VT.getScalarSizeInBits();
2886   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2887          "Unexpected unaligned RVV store type");
2888   MVT NewVT =
2889       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2890   assert(NewVT.isValid() &&
2891          "Expecting equally-sized RVV vector types to be legal");
2892   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2893   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2894                       Store->getPointerInfo(), Store->getOriginalAlign(),
2895                       Store->getMemOperand()->getFlags());
2896 }
2897 
2898 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2899                                             SelectionDAG &DAG) const {
2900   switch (Op.getOpcode()) {
2901   default:
2902     report_fatal_error("unimplemented operand");
2903   case ISD::GlobalAddress:
2904     return lowerGlobalAddress(Op, DAG);
2905   case ISD::BlockAddress:
2906     return lowerBlockAddress(Op, DAG);
2907   case ISD::ConstantPool:
2908     return lowerConstantPool(Op, DAG);
2909   case ISD::JumpTable:
2910     return lowerJumpTable(Op, DAG);
2911   case ISD::GlobalTLSAddress:
2912     return lowerGlobalTLSAddress(Op, DAG);
2913   case ISD::SELECT:
2914     return lowerSELECT(Op, DAG);
2915   case ISD::BRCOND:
2916     return lowerBRCOND(Op, DAG);
2917   case ISD::VASTART:
2918     return lowerVASTART(Op, DAG);
2919   case ISD::FRAMEADDR:
2920     return lowerFRAMEADDR(Op, DAG);
2921   case ISD::RETURNADDR:
2922     return lowerRETURNADDR(Op, DAG);
2923   case ISD::SHL_PARTS:
2924     return lowerShiftLeftParts(Op, DAG);
2925   case ISD::SRA_PARTS:
2926     return lowerShiftRightParts(Op, DAG, true);
2927   case ISD::SRL_PARTS:
2928     return lowerShiftRightParts(Op, DAG, false);
2929   case ISD::BITCAST: {
2930     SDLoc DL(Op);
2931     EVT VT = Op.getValueType();
2932     SDValue Op0 = Op.getOperand(0);
2933     EVT Op0VT = Op0.getValueType();
2934     MVT XLenVT = Subtarget.getXLenVT();
2935     if (VT.isFixedLengthVector()) {
2936       // We can handle fixed length vector bitcasts with a simple replacement
2937       // in isel.
2938       if (Op0VT.isFixedLengthVector())
2939         return Op;
2940       // When bitcasting from scalar to fixed-length vector, insert the scalar
2941       // into a one-element vector of the result type, and perform a vector
2942       // bitcast.
2943       if (!Op0VT.isVector()) {
2944         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2945         if (!isTypeLegal(BVT))
2946           return SDValue();
2947         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2948                                               DAG.getUNDEF(BVT), Op0,
2949                                               DAG.getConstant(0, DL, XLenVT)));
2950       }
2951       return SDValue();
2952     }
2953     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2954     // thus: bitcast the vector to a one-element vector type whose element type
2955     // is the same as the result type, and extract the first element.
2956     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2957       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2958       if (!isTypeLegal(BVT))
2959         return SDValue();
2960       SDValue BVec = DAG.getBitcast(BVT, Op0);
2961       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2962                          DAG.getConstant(0, DL, XLenVT));
2963     }
2964     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2965       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2966       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2967       return FPConv;
2968     }
2969     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2970         Subtarget.hasStdExtF()) {
2971       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2972       SDValue FPConv =
2973           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2974       return FPConv;
2975     }
2976     return SDValue();
2977   }
2978   case ISD::INTRINSIC_WO_CHAIN:
2979     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2980   case ISD::INTRINSIC_W_CHAIN:
2981     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2982   case ISD::INTRINSIC_VOID:
2983     return LowerINTRINSIC_VOID(Op, DAG);
2984   case ISD::BSWAP:
2985   case ISD::BITREVERSE: {
2986     MVT VT = Op.getSimpleValueType();
2987     SDLoc DL(Op);
2988     if (Subtarget.hasStdExtZbp()) {
2989       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2990       // Start with the maximum immediate value which is the bitwidth - 1.
2991       unsigned Imm = VT.getSizeInBits() - 1;
2992       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2993       if (Op.getOpcode() == ISD::BSWAP)
2994         Imm &= ~0x7U;
2995       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2996                          DAG.getConstant(Imm, DL, VT));
2997     }
2998     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
2999     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3000     // Expand bitreverse to a bswap(rev8) followed by brev8.
3001     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3002     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3003     // as brev8 by an isel pattern.
3004     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3005                        DAG.getConstant(7, DL, VT));
3006   }
3007   case ISD::FSHL:
3008   case ISD::FSHR: {
3009     MVT VT = Op.getSimpleValueType();
3010     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3011     SDLoc DL(Op);
3012     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3013     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3014     // accidentally setting the extra bit.
3015     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3016     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3017                                 DAG.getConstant(ShAmtWidth, DL, VT));
3018     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3019     // instruction use different orders. fshl will return its first operand for
3020     // shift of zero, fshr will return its second operand. fsl and fsr both
3021     // return rs1 so the ISD nodes need to have different operand orders.
3022     // Shift amount is in rs2.
3023     SDValue Op0 = Op.getOperand(0);
3024     SDValue Op1 = Op.getOperand(1);
3025     unsigned Opc = RISCVISD::FSL;
3026     if (Op.getOpcode() == ISD::FSHR) {
3027       std::swap(Op0, Op1);
3028       Opc = RISCVISD::FSR;
3029     }
3030     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3031   }
3032   case ISD::TRUNCATE:
3033     // Only custom-lower vector truncates
3034     if (!Op.getSimpleValueType().isVector())
3035       return Op;
3036     return lowerVectorTruncLike(Op, DAG);
3037   case ISD::ANY_EXTEND:
3038   case ISD::ZERO_EXTEND:
3039     if (Op.getOperand(0).getValueType().isVector() &&
3040         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3041       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3042     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3043   case ISD::SIGN_EXTEND:
3044     if (Op.getOperand(0).getValueType().isVector() &&
3045         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3046       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3047     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3048   case ISD::SPLAT_VECTOR_PARTS:
3049     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3050   case ISD::INSERT_VECTOR_ELT:
3051     return lowerINSERT_VECTOR_ELT(Op, DAG);
3052   case ISD::EXTRACT_VECTOR_ELT:
3053     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3054   case ISD::VSCALE: {
3055     MVT VT = Op.getSimpleValueType();
3056     SDLoc DL(Op);
3057     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3058     // We define our scalable vector types for lmul=1 to use a 64 bit known
3059     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3060     // vscale as VLENB / 8.
3061     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3062     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3063       report_fatal_error("Support for VLEN==32 is incomplete.");
3064     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3065       // We assume VLENB is a multiple of 8. We manually choose the best shift
3066       // here because SimplifyDemandedBits isn't always able to simplify it.
3067       uint64_t Val = Op.getConstantOperandVal(0);
3068       if (isPowerOf2_64(Val)) {
3069         uint64_t Log2 = Log2_64(Val);
3070         if (Log2 < 3)
3071           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3072                              DAG.getConstant(3 - Log2, DL, VT));
3073         if (Log2 > 3)
3074           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3075                              DAG.getConstant(Log2 - 3, DL, VT));
3076         return VLENB;
3077       }
3078       // If the multiplier is a multiple of 8, scale it down to avoid needing
3079       // to shift the VLENB value.
3080       if ((Val % 8) == 0)
3081         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3082                            DAG.getConstant(Val / 8, DL, VT));
3083     }
3084 
3085     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3086                                  DAG.getConstant(3, DL, VT));
3087     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3088   }
3089   case ISD::FPOWI: {
3090     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3091     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3092     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3093         Op.getOperand(1).getValueType() == MVT::i32) {
3094       SDLoc DL(Op);
3095       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3096       SDValue Powi =
3097           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3098       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3099                          DAG.getIntPtrConstant(0, DL));
3100     }
3101     return SDValue();
3102   }
3103   case ISD::FP_EXTEND: {
3104     // RVV can only do fp_extend to types double the size as the source. We
3105     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3106     // via f32.
3107     SDLoc DL(Op);
3108     MVT VT = Op.getSimpleValueType();
3109     SDValue Src = Op.getOperand(0);
3110     MVT SrcVT = Src.getSimpleValueType();
3111 
3112     // Prepare any fixed-length vector operands.
3113     MVT ContainerVT = VT;
3114     if (SrcVT.isFixedLengthVector()) {
3115       ContainerVT = getContainerForFixedLengthVector(VT);
3116       MVT SrcContainerVT =
3117           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3118       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3119     }
3120 
3121     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3122         SrcVT.getVectorElementType() != MVT::f16) {
3123       // For scalable vectors, we only need to close the gap between
3124       // vXf16->vXf64.
3125       if (!VT.isFixedLengthVector())
3126         return Op;
3127       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3128       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3129       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3130     }
3131 
3132     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3133     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3134     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3135         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3136 
3137     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3138                                            DL, DAG, Subtarget);
3139     if (VT.isFixedLengthVector())
3140       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3141     return Extend;
3142   }
3143   case ISD::FP_ROUND:
3144     if (!Op.getValueType().isVector())
3145       return Op;
3146     return lowerVectorFPRoundLike(Op, DAG);
3147   case ISD::FP_TO_SINT:
3148   case ISD::FP_TO_UINT:
3149   case ISD::SINT_TO_FP:
3150   case ISD::UINT_TO_FP: {
3151     // RVV can only do fp<->int conversions to types half/double the size as
3152     // the source. We custom-lower any conversions that do two hops into
3153     // sequences.
3154     MVT VT = Op.getSimpleValueType();
3155     if (!VT.isVector())
3156       return Op;
3157     SDLoc DL(Op);
3158     SDValue Src = Op.getOperand(0);
3159     MVT EltVT = VT.getVectorElementType();
3160     MVT SrcVT = Src.getSimpleValueType();
3161     MVT SrcEltVT = SrcVT.getVectorElementType();
3162     unsigned EltSize = EltVT.getSizeInBits();
3163     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3164     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3165            "Unexpected vector element types");
3166 
3167     bool IsInt2FP = SrcEltVT.isInteger();
3168     // Widening conversions
3169     if (EltSize > (2 * SrcEltSize)) {
3170       if (IsInt2FP) {
3171         // Do a regular integer sign/zero extension then convert to float.
3172         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize),
3173                                       VT.getVectorElementCount());
3174         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3175                                  ? ISD::ZERO_EXTEND
3176                                  : ISD::SIGN_EXTEND;
3177         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3178         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3179       }
3180       // FP2Int
3181       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3182       // Do one doubling fp_extend then complete the operation by converting
3183       // to int.
3184       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3185       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3186       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3187     }
3188 
3189     // Narrowing conversions
3190     if (SrcEltSize > (2 * EltSize)) {
3191       if (IsInt2FP) {
3192         // One narrowing int_to_fp, then an fp_round.
3193         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3194         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3195         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3196         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3197       }
3198       // FP2Int
3199       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3200       // representable by the integer, the result is poison.
3201       MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
3202                                     VT.getVectorElementCount());
3203       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3204       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3205     }
3206 
3207     // Scalable vectors can exit here. Patterns will handle equally-sized
3208     // conversions halving/doubling ones.
3209     if (!VT.isFixedLengthVector())
3210       return Op;
3211 
3212     // For fixed-length vectors we lower to a custom "VL" node.
3213     unsigned RVVOpc = 0;
3214     switch (Op.getOpcode()) {
3215     default:
3216       llvm_unreachable("Impossible opcode");
3217     case ISD::FP_TO_SINT:
3218       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3219       break;
3220     case ISD::FP_TO_UINT:
3221       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3222       break;
3223     case ISD::SINT_TO_FP:
3224       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3225       break;
3226     case ISD::UINT_TO_FP:
3227       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3228       break;
3229     }
3230 
3231     MVT ContainerVT, SrcContainerVT;
3232     // Derive the reference container type from the larger vector type.
3233     if (SrcEltSize > EltSize) {
3234       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3235       ContainerVT =
3236           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3237     } else {
3238       ContainerVT = getContainerForFixedLengthVector(VT);
3239       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3240     }
3241 
3242     SDValue Mask, VL;
3243     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3244 
3245     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3246     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3247     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3248   }
3249   case ISD::FP_TO_SINT_SAT:
3250   case ISD::FP_TO_UINT_SAT:
3251     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3252   case ISD::FTRUNC:
3253   case ISD::FCEIL:
3254   case ISD::FFLOOR:
3255     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3256   case ISD::FROUND:
3257     return lowerFROUND(Op, DAG);
3258   case ISD::VECREDUCE_ADD:
3259   case ISD::VECREDUCE_UMAX:
3260   case ISD::VECREDUCE_SMAX:
3261   case ISD::VECREDUCE_UMIN:
3262   case ISD::VECREDUCE_SMIN:
3263     return lowerVECREDUCE(Op, DAG);
3264   case ISD::VECREDUCE_AND:
3265   case ISD::VECREDUCE_OR:
3266   case ISD::VECREDUCE_XOR:
3267     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3268       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3269     return lowerVECREDUCE(Op, DAG);
3270   case ISD::VECREDUCE_FADD:
3271   case ISD::VECREDUCE_SEQ_FADD:
3272   case ISD::VECREDUCE_FMIN:
3273   case ISD::VECREDUCE_FMAX:
3274     return lowerFPVECREDUCE(Op, DAG);
3275   case ISD::VP_REDUCE_ADD:
3276   case ISD::VP_REDUCE_UMAX:
3277   case ISD::VP_REDUCE_SMAX:
3278   case ISD::VP_REDUCE_UMIN:
3279   case ISD::VP_REDUCE_SMIN:
3280   case ISD::VP_REDUCE_FADD:
3281   case ISD::VP_REDUCE_SEQ_FADD:
3282   case ISD::VP_REDUCE_FMIN:
3283   case ISD::VP_REDUCE_FMAX:
3284     return lowerVPREDUCE(Op, DAG);
3285   case ISD::VP_REDUCE_AND:
3286   case ISD::VP_REDUCE_OR:
3287   case ISD::VP_REDUCE_XOR:
3288     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3289       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3290     return lowerVPREDUCE(Op, DAG);
3291   case ISD::INSERT_SUBVECTOR:
3292     return lowerINSERT_SUBVECTOR(Op, DAG);
3293   case ISD::EXTRACT_SUBVECTOR:
3294     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3295   case ISD::STEP_VECTOR:
3296     return lowerSTEP_VECTOR(Op, DAG);
3297   case ISD::VECTOR_REVERSE:
3298     return lowerVECTOR_REVERSE(Op, DAG);
3299   case ISD::VECTOR_SPLICE:
3300     return lowerVECTOR_SPLICE(Op, DAG);
3301   case ISD::BUILD_VECTOR:
3302     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3303   case ISD::SPLAT_VECTOR:
3304     if (Op.getValueType().getVectorElementType() == MVT::i1)
3305       return lowerVectorMaskSplat(Op, DAG);
3306     return SDValue();
3307   case ISD::VECTOR_SHUFFLE:
3308     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3309   case ISD::CONCAT_VECTORS: {
3310     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3311     // better than going through the stack, as the default expansion does.
3312     SDLoc DL(Op);
3313     MVT VT = Op.getSimpleValueType();
3314     unsigned NumOpElts =
3315         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3316     SDValue Vec = DAG.getUNDEF(VT);
3317     for (const auto &OpIdx : enumerate(Op->ops())) {
3318       SDValue SubVec = OpIdx.value();
3319       // Don't insert undef subvectors.
3320       if (SubVec.isUndef())
3321         continue;
3322       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3323                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3324     }
3325     return Vec;
3326   }
3327   case ISD::LOAD:
3328     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3329       return V;
3330     if (Op.getValueType().isFixedLengthVector())
3331       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3332     return Op;
3333   case ISD::STORE:
3334     if (auto V = expandUnalignedRVVStore(Op, DAG))
3335       return V;
3336     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3337       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3338     return Op;
3339   case ISD::MLOAD:
3340   case ISD::VP_LOAD:
3341     return lowerMaskedLoad(Op, DAG);
3342   case ISD::MSTORE:
3343   case ISD::VP_STORE:
3344     return lowerMaskedStore(Op, DAG);
3345   case ISD::SETCC:
3346     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3347   case ISD::ADD:
3348     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3349   case ISD::SUB:
3350     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3351   case ISD::MUL:
3352     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3353   case ISD::MULHS:
3354     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3355   case ISD::MULHU:
3356     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3357   case ISD::AND:
3358     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3359                                               RISCVISD::AND_VL);
3360   case ISD::OR:
3361     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3362                                               RISCVISD::OR_VL);
3363   case ISD::XOR:
3364     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3365                                               RISCVISD::XOR_VL);
3366   case ISD::SDIV:
3367     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3368   case ISD::SREM:
3369     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3370   case ISD::UDIV:
3371     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3372   case ISD::UREM:
3373     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3374   case ISD::SHL:
3375   case ISD::SRA:
3376   case ISD::SRL:
3377     if (Op.getSimpleValueType().isFixedLengthVector())
3378       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3379     // This can be called for an i32 shift amount that needs to be promoted.
3380     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3381            "Unexpected custom legalisation");
3382     return SDValue();
3383   case ISD::SADDSAT:
3384     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3385   case ISD::UADDSAT:
3386     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3387   case ISD::SSUBSAT:
3388     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3389   case ISD::USUBSAT:
3390     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3391   case ISD::FADD:
3392     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3393   case ISD::FSUB:
3394     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3395   case ISD::FMUL:
3396     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3397   case ISD::FDIV:
3398     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3399   case ISD::FNEG:
3400     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3401   case ISD::FABS:
3402     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3403   case ISD::FSQRT:
3404     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3405   case ISD::FMA:
3406     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3407   case ISD::SMIN:
3408     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3409   case ISD::SMAX:
3410     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3411   case ISD::UMIN:
3412     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3413   case ISD::UMAX:
3414     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3415   case ISD::FMINNUM:
3416     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3417   case ISD::FMAXNUM:
3418     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3419   case ISD::ABS:
3420     return lowerABS(Op, DAG);
3421   case ISD::CTLZ_ZERO_UNDEF:
3422   case ISD::CTTZ_ZERO_UNDEF:
3423     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3424   case ISD::VSELECT:
3425     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3426   case ISD::FCOPYSIGN:
3427     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3428   case ISD::MGATHER:
3429   case ISD::VP_GATHER:
3430     return lowerMaskedGather(Op, DAG);
3431   case ISD::MSCATTER:
3432   case ISD::VP_SCATTER:
3433     return lowerMaskedScatter(Op, DAG);
3434   case ISD::FLT_ROUNDS_:
3435     return lowerGET_ROUNDING(Op, DAG);
3436   case ISD::SET_ROUNDING:
3437     return lowerSET_ROUNDING(Op, DAG);
3438   case ISD::VP_SELECT:
3439     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3440   case ISD::VP_MERGE:
3441     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3442   case ISD::VP_ADD:
3443     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3444   case ISD::VP_SUB:
3445     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3446   case ISD::VP_MUL:
3447     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3448   case ISD::VP_SDIV:
3449     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3450   case ISD::VP_UDIV:
3451     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3452   case ISD::VP_SREM:
3453     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3454   case ISD::VP_UREM:
3455     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3456   case ISD::VP_AND:
3457     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3458   case ISD::VP_OR:
3459     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3460   case ISD::VP_XOR:
3461     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3462   case ISD::VP_ASHR:
3463     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3464   case ISD::VP_LSHR:
3465     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3466   case ISD::VP_SHL:
3467     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3468   case ISD::VP_FADD:
3469     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3470   case ISD::VP_FSUB:
3471     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3472   case ISD::VP_FMUL:
3473     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3474   case ISD::VP_FDIV:
3475     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3476   case ISD::VP_FNEG:
3477     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3478   case ISD::VP_FMA:
3479     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3480   case ISD::VP_SEXT:
3481   case ISD::VP_ZEXT:
3482     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3483       return lowerVPExtMaskOp(Op, DAG);
3484     return lowerVPOp(Op, DAG,
3485                      Op.getOpcode() == ISD::VP_SEXT ? RISCVISD::VSEXT_VL
3486                                                     : RISCVISD::VZEXT_VL);
3487   case ISD::VP_TRUNC:
3488     return lowerVectorTruncLike(Op, DAG);
3489   case ISD::VP_FP_ROUND:
3490     return lowerVectorFPRoundLike(Op, DAG);
3491   case ISD::VP_FPTOSI:
3492     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL);
3493   case ISD::VP_FPTOUI:
3494     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL);
3495   case ISD::VP_SITOFP:
3496     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
3497   case ISD::VP_UITOFP:
3498     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL);
3499   case ISD::VP_SETCC:
3500     return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL);
3501   }
3502 }
3503 
3504 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3505                              SelectionDAG &DAG, unsigned Flags) {
3506   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3507 }
3508 
3509 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3510                              SelectionDAG &DAG, unsigned Flags) {
3511   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3512                                    Flags);
3513 }
3514 
3515 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3516                              SelectionDAG &DAG, unsigned Flags) {
3517   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3518                                    N->getOffset(), Flags);
3519 }
3520 
3521 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3522                              SelectionDAG &DAG, unsigned Flags) {
3523   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3524 }
3525 
3526 template <class NodeTy>
3527 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3528                                      bool IsLocal) const {
3529   SDLoc DL(N);
3530   EVT Ty = getPointerTy(DAG.getDataLayout());
3531 
3532   if (isPositionIndependent()) {
3533     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3534     if (IsLocal)
3535       // Use PC-relative addressing to access the symbol. This generates the
3536       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3537       // %pcrel_lo(auipc)).
3538       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3539 
3540     // Use PC-relative addressing to access the GOT for this symbol, then load
3541     // the address from the GOT. This generates the pattern (PseudoLA sym),
3542     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3543     SDValue Load =
3544         SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3545     MachineFunction &MF = DAG.getMachineFunction();
3546     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3547         MachinePointerInfo::getGOT(MF),
3548         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3549             MachineMemOperand::MOInvariant,
3550         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3551     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3552     return Load;
3553   }
3554 
3555   switch (getTargetMachine().getCodeModel()) {
3556   default:
3557     report_fatal_error("Unsupported code model for lowering");
3558   case CodeModel::Small: {
3559     // Generate a sequence for accessing addresses within the first 2 GiB of
3560     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3561     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3562     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3563     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3564     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3565   }
3566   case CodeModel::Medium: {
3567     // Generate a sequence for accessing addresses within any 2GiB range within
3568     // the address space. This generates the pattern (PseudoLLA sym), which
3569     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3570     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3571     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3572   }
3573   }
3574 }
3575 
3576 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>(
3577     GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3578 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>(
3579     BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3580 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>(
3581     ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3582 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>(
3583     JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3584 
3585 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3586                                                 SelectionDAG &DAG) const {
3587   SDLoc DL(Op);
3588   EVT Ty = Op.getValueType();
3589   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3590   int64_t Offset = N->getOffset();
3591   MVT XLenVT = Subtarget.getXLenVT();
3592 
3593   const GlobalValue *GV = N->getGlobal();
3594   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3595   SDValue Addr = getAddr(N, DAG, IsLocal);
3596 
3597   // In order to maximise the opportunity for common subexpression elimination,
3598   // emit a separate ADD node for the global address offset instead of folding
3599   // it in the global address node. Later peephole optimisations may choose to
3600   // fold it back in when profitable.
3601   if (Offset != 0)
3602     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3603                        DAG.getConstant(Offset, DL, XLenVT));
3604   return Addr;
3605 }
3606 
3607 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3608                                                SelectionDAG &DAG) const {
3609   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3610 
3611   return getAddr(N, DAG);
3612 }
3613 
3614 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3615                                                SelectionDAG &DAG) const {
3616   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3617 
3618   return getAddr(N, DAG);
3619 }
3620 
3621 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3622                                             SelectionDAG &DAG) const {
3623   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3624 
3625   return getAddr(N, DAG);
3626 }
3627 
3628 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3629                                               SelectionDAG &DAG,
3630                                               bool UseGOT) const {
3631   SDLoc DL(N);
3632   EVT Ty = getPointerTy(DAG.getDataLayout());
3633   const GlobalValue *GV = N->getGlobal();
3634   MVT XLenVT = Subtarget.getXLenVT();
3635 
3636   if (UseGOT) {
3637     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3638     // load the address from the GOT and add the thread pointer. This generates
3639     // the pattern (PseudoLA_TLS_IE sym), which expands to
3640     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3641     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3642     SDValue Load =
3643         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3644     MachineFunction &MF = DAG.getMachineFunction();
3645     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3646         MachinePointerInfo::getGOT(MF),
3647         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3648             MachineMemOperand::MOInvariant,
3649         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3650     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3651 
3652     // Add the thread pointer.
3653     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3654     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3655   }
3656 
3657   // Generate a sequence for accessing the address relative to the thread
3658   // pointer, with the appropriate adjustment for the thread pointer offset.
3659   // This generates the pattern
3660   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3661   SDValue AddrHi =
3662       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3663   SDValue AddrAdd =
3664       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3665   SDValue AddrLo =
3666       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3667 
3668   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3669   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3670   SDValue MNAdd = SDValue(
3671       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3672       0);
3673   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3674 }
3675 
3676 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3677                                                SelectionDAG &DAG) const {
3678   SDLoc DL(N);
3679   EVT Ty = getPointerTy(DAG.getDataLayout());
3680   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3681   const GlobalValue *GV = N->getGlobal();
3682 
3683   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3684   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3685   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3686   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3687   SDValue Load =
3688       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3689 
3690   // Prepare argument list to generate call.
3691   ArgListTy Args;
3692   ArgListEntry Entry;
3693   Entry.Node = Load;
3694   Entry.Ty = CallTy;
3695   Args.push_back(Entry);
3696 
3697   // Setup call to __tls_get_addr.
3698   TargetLowering::CallLoweringInfo CLI(DAG);
3699   CLI.setDebugLoc(DL)
3700       .setChain(DAG.getEntryNode())
3701       .setLibCallee(CallingConv::C, CallTy,
3702                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3703                     std::move(Args));
3704 
3705   return LowerCallTo(CLI).first;
3706 }
3707 
3708 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3709                                                    SelectionDAG &DAG) const {
3710   SDLoc DL(Op);
3711   EVT Ty = Op.getValueType();
3712   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3713   int64_t Offset = N->getOffset();
3714   MVT XLenVT = Subtarget.getXLenVT();
3715 
3716   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3717 
3718   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3719       CallingConv::GHC)
3720     report_fatal_error("In GHC calling convention TLS is not supported");
3721 
3722   SDValue Addr;
3723   switch (Model) {
3724   case TLSModel::LocalExec:
3725     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3726     break;
3727   case TLSModel::InitialExec:
3728     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3729     break;
3730   case TLSModel::LocalDynamic:
3731   case TLSModel::GeneralDynamic:
3732     Addr = getDynamicTLSAddr(N, DAG);
3733     break;
3734   }
3735 
3736   // In order to maximise the opportunity for common subexpression elimination,
3737   // emit a separate ADD node for the global address offset instead of folding
3738   // it in the global address node. Later peephole optimisations may choose to
3739   // fold it back in when profitable.
3740   if (Offset != 0)
3741     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3742                        DAG.getConstant(Offset, DL, XLenVT));
3743   return Addr;
3744 }
3745 
3746 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3747   SDValue CondV = Op.getOperand(0);
3748   SDValue TrueV = Op.getOperand(1);
3749   SDValue FalseV = Op.getOperand(2);
3750   SDLoc DL(Op);
3751   MVT VT = Op.getSimpleValueType();
3752   MVT XLenVT = Subtarget.getXLenVT();
3753 
3754   // Lower vector SELECTs to VSELECTs by splatting the condition.
3755   if (VT.isVector()) {
3756     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3757     SDValue CondSplat = VT.isScalableVector()
3758                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3759                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3760     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3761   }
3762 
3763   // If the result type is XLenVT and CondV is the output of a SETCC node
3764   // which also operated on XLenVT inputs, then merge the SETCC node into the
3765   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3766   // compare+branch instructions. i.e.:
3767   // (select (setcc lhs, rhs, cc), truev, falsev)
3768   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3769   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3770       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3771     SDValue LHS = CondV.getOperand(0);
3772     SDValue RHS = CondV.getOperand(1);
3773     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3774     ISD::CondCode CCVal = CC->get();
3775 
3776     // Special case for a select of 2 constants that have a diffence of 1.
3777     // Normally this is done by DAGCombine, but if the select is introduced by
3778     // type legalization or op legalization, we miss it. Restricting to SETLT
3779     // case for now because that is what signed saturating add/sub need.
3780     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3781     // but we would probably want to swap the true/false values if the condition
3782     // is SETGE/SETLE to avoid an XORI.
3783     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3784         CCVal == ISD::SETLT) {
3785       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3786       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3787       if (TrueVal - 1 == FalseVal)
3788         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3789       if (TrueVal + 1 == FalseVal)
3790         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3791     }
3792 
3793     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3794 
3795     SDValue TargetCC = DAG.getCondCode(CCVal);
3796     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3797     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3798   }
3799 
3800   // Otherwise:
3801   // (select condv, truev, falsev)
3802   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3803   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3804   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3805 
3806   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3807 
3808   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3809 }
3810 
3811 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3812   SDValue CondV = Op.getOperand(1);
3813   SDLoc DL(Op);
3814   MVT XLenVT = Subtarget.getXLenVT();
3815 
3816   if (CondV.getOpcode() == ISD::SETCC &&
3817       CondV.getOperand(0).getValueType() == XLenVT) {
3818     SDValue LHS = CondV.getOperand(0);
3819     SDValue RHS = CondV.getOperand(1);
3820     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3821 
3822     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3823 
3824     SDValue TargetCC = DAG.getCondCode(CCVal);
3825     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3826                        LHS, RHS, TargetCC, Op.getOperand(2));
3827   }
3828 
3829   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3830                      CondV, DAG.getConstant(0, DL, XLenVT),
3831                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3832 }
3833 
3834 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3835   MachineFunction &MF = DAG.getMachineFunction();
3836   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3837 
3838   SDLoc DL(Op);
3839   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3840                                  getPointerTy(MF.getDataLayout()));
3841 
3842   // vastart just stores the address of the VarArgsFrameIndex slot into the
3843   // memory location argument.
3844   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3845   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3846                       MachinePointerInfo(SV));
3847 }
3848 
3849 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3850                                             SelectionDAG &DAG) const {
3851   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3852   MachineFunction &MF = DAG.getMachineFunction();
3853   MachineFrameInfo &MFI = MF.getFrameInfo();
3854   MFI.setFrameAddressIsTaken(true);
3855   Register FrameReg = RI.getFrameRegister(MF);
3856   int XLenInBytes = Subtarget.getXLen() / 8;
3857 
3858   EVT VT = Op.getValueType();
3859   SDLoc DL(Op);
3860   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3861   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3862   while (Depth--) {
3863     int Offset = -(XLenInBytes * 2);
3864     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3865                               DAG.getIntPtrConstant(Offset, DL));
3866     FrameAddr =
3867         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3868   }
3869   return FrameAddr;
3870 }
3871 
3872 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3873                                              SelectionDAG &DAG) const {
3874   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3875   MachineFunction &MF = DAG.getMachineFunction();
3876   MachineFrameInfo &MFI = MF.getFrameInfo();
3877   MFI.setReturnAddressIsTaken(true);
3878   MVT XLenVT = Subtarget.getXLenVT();
3879   int XLenInBytes = Subtarget.getXLen() / 8;
3880 
3881   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3882     return SDValue();
3883 
3884   EVT VT = Op.getValueType();
3885   SDLoc DL(Op);
3886   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3887   if (Depth) {
3888     int Off = -XLenInBytes;
3889     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3890     SDValue Offset = DAG.getConstant(Off, DL, VT);
3891     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3892                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3893                        MachinePointerInfo());
3894   }
3895 
3896   // Return the value of the return address register, marking it an implicit
3897   // live-in.
3898   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3899   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3900 }
3901 
3902 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3903                                                  SelectionDAG &DAG) const {
3904   SDLoc DL(Op);
3905   SDValue Lo = Op.getOperand(0);
3906   SDValue Hi = Op.getOperand(1);
3907   SDValue Shamt = Op.getOperand(2);
3908   EVT VT = Lo.getValueType();
3909 
3910   // if Shamt-XLEN < 0: // Shamt < XLEN
3911   //   Lo = Lo << Shamt
3912   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
3913   // else:
3914   //   Lo = 0
3915   //   Hi = Lo << (Shamt-XLEN)
3916 
3917   SDValue Zero = DAG.getConstant(0, DL, VT);
3918   SDValue One = DAG.getConstant(1, DL, VT);
3919   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3920   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3921   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3922   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
3923 
3924   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3925   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3926   SDValue ShiftRightLo =
3927       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3928   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3929   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3930   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3931 
3932   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3933 
3934   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3935   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3936 
3937   SDValue Parts[2] = {Lo, Hi};
3938   return DAG.getMergeValues(Parts, DL);
3939 }
3940 
3941 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3942                                                   bool IsSRA) const {
3943   SDLoc DL(Op);
3944   SDValue Lo = Op.getOperand(0);
3945   SDValue Hi = Op.getOperand(1);
3946   SDValue Shamt = Op.getOperand(2);
3947   EVT VT = Lo.getValueType();
3948 
3949   // SRA expansion:
3950   //   if Shamt-XLEN < 0: // Shamt < XLEN
3951   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
3952   //     Hi = Hi >>s Shamt
3953   //   else:
3954   //     Lo = Hi >>s (Shamt-XLEN);
3955   //     Hi = Hi >>s (XLEN-1)
3956   //
3957   // SRL expansion:
3958   //   if Shamt-XLEN < 0: // Shamt < XLEN
3959   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
3960   //     Hi = Hi >>u Shamt
3961   //   else:
3962   //     Lo = Hi >>u (Shamt-XLEN);
3963   //     Hi = 0;
3964 
3965   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3966 
3967   SDValue Zero = DAG.getConstant(0, DL, VT);
3968   SDValue One = DAG.getConstant(1, DL, VT);
3969   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3970   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3971   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3972   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
3973 
3974   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3975   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3976   SDValue ShiftLeftHi =
3977       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3978   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3979   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3980   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3981   SDValue HiFalse =
3982       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3983 
3984   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3985 
3986   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3987   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3988 
3989   SDValue Parts[2] = {Lo, Hi};
3990   return DAG.getMergeValues(Parts, DL);
3991 }
3992 
3993 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3994 // legal equivalently-sized i8 type, so we can use that as a go-between.
3995 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3996                                                   SelectionDAG &DAG) const {
3997   SDLoc DL(Op);
3998   MVT VT = Op.getSimpleValueType();
3999   SDValue SplatVal = Op.getOperand(0);
4000   // All-zeros or all-ones splats are handled specially.
4001   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4002     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4003     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4004   }
4005   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4006     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4007     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4008   }
4009   MVT XLenVT = Subtarget.getXLenVT();
4010   assert(SplatVal.getValueType() == XLenVT &&
4011          "Unexpected type for i1 splat value");
4012   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4013   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4014                          DAG.getConstant(1, DL, XLenVT));
4015   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4016   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4017   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4018 }
4019 
4020 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4021 // illegal (currently only vXi64 RV32).
4022 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4023 // them to VMV_V_X_VL.
4024 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4025                                                      SelectionDAG &DAG) const {
4026   SDLoc DL(Op);
4027   MVT VecVT = Op.getSimpleValueType();
4028   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4029          "Unexpected SPLAT_VECTOR_PARTS lowering");
4030 
4031   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4032   SDValue Lo = Op.getOperand(0);
4033   SDValue Hi = Op.getOperand(1);
4034 
4035   if (VecVT.isFixedLengthVector()) {
4036     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4037     SDLoc DL(Op);
4038     SDValue Mask, VL;
4039     std::tie(Mask, VL) =
4040         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4041 
4042     SDValue Res =
4043         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4044     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4045   }
4046 
4047   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4048     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4049     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4050     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4051     // node in order to try and match RVV vector/scalar instructions.
4052     if ((LoC >> 31) == HiC)
4053       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4054                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4055   }
4056 
4057   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4058   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4059       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4060       Hi.getConstantOperandVal(1) == 31)
4061     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4062                        DAG.getRegister(RISCV::X0, MVT::i32));
4063 
4064   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4065   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4066                      DAG.getUNDEF(VecVT), Lo, Hi,
4067                      DAG.getRegister(RISCV::X0, MVT::i32));
4068 }
4069 
4070 // Custom-lower extensions from mask vectors by using a vselect either with 1
4071 // for zero/any-extension or -1 for sign-extension:
4072 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4073 // Note that any-extension is lowered identically to zero-extension.
4074 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4075                                                 int64_t ExtTrueVal) const {
4076   SDLoc DL(Op);
4077   MVT VecVT = Op.getSimpleValueType();
4078   SDValue Src = Op.getOperand(0);
4079   // Only custom-lower extensions from mask types
4080   assert(Src.getValueType().isVector() &&
4081          Src.getValueType().getVectorElementType() == MVT::i1);
4082 
4083   if (VecVT.isScalableVector()) {
4084     SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
4085     SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
4086     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4087   }
4088 
4089   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4090   MVT I1ContainerVT =
4091       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4092 
4093   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4094 
4095   SDValue Mask, VL;
4096   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4097 
4098   MVT XLenVT = Subtarget.getXLenVT();
4099   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4100   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4101 
4102   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4103                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4104   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4105                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4106   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4107                                SplatTrueVal, SplatZero, VL);
4108 
4109   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4110 }
4111 
4112 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4113     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4114   MVT ExtVT = Op.getSimpleValueType();
4115   // Only custom-lower extensions from fixed-length vector types.
4116   if (!ExtVT.isFixedLengthVector())
4117     return Op;
4118   MVT VT = Op.getOperand(0).getSimpleValueType();
4119   // Grab the canonical container type for the extended type. Infer the smaller
4120   // type from that to ensure the same number of vector elements, as we know
4121   // the LMUL will be sufficient to hold the smaller type.
4122   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4123   // Get the extended container type manually to ensure the same number of
4124   // vector elements between source and dest.
4125   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4126                                      ContainerExtVT.getVectorElementCount());
4127 
4128   SDValue Op1 =
4129       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4130 
4131   SDLoc DL(Op);
4132   SDValue Mask, VL;
4133   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4134 
4135   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4136 
4137   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4138 }
4139 
4140 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4141 // setcc operation:
4142 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4143 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op,
4144                                                       SelectionDAG &DAG) const {
4145   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNC;
4146   SDLoc DL(Op);
4147   EVT MaskVT = Op.getValueType();
4148   // Only expect to custom-lower truncations to mask types
4149   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4150          "Unexpected type for vector mask lowering");
4151   SDValue Src = Op.getOperand(0);
4152   MVT VecVT = Src.getSimpleValueType();
4153   SDValue Mask, VL;
4154   if (IsVPTrunc) {
4155     Mask = Op.getOperand(1);
4156     VL = Op.getOperand(2);
4157   }
4158   // If this is a fixed vector, we need to convert it to a scalable vector.
4159   MVT ContainerVT = VecVT;
4160 
4161   if (VecVT.isFixedLengthVector()) {
4162     ContainerVT = getContainerForFixedLengthVector(VecVT);
4163     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4164     if (IsVPTrunc) {
4165       MVT MaskContainerVT =
4166           getContainerForFixedLengthVector(Mask.getSimpleValueType());
4167       Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget);
4168     }
4169   }
4170 
4171   if (!IsVPTrunc) {
4172     std::tie(Mask, VL) =
4173         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4174   }
4175 
4176   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4177   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4178 
4179   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4180                          DAG.getUNDEF(ContainerVT), SplatOne, VL);
4181   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4182                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4183 
4184   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4185   SDValue Trunc =
4186       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4187   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4188                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4189   if (MaskVT.isFixedLengthVector())
4190     Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4191   return Trunc;
4192 }
4193 
4194 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op,
4195                                                   SelectionDAG &DAG) const {
4196   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNC;
4197   SDLoc DL(Op);
4198 
4199   MVT VT = Op.getSimpleValueType();
4200   // Only custom-lower vector truncates
4201   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4202 
4203   // Truncates to mask types are handled differently
4204   if (VT.getVectorElementType() == MVT::i1)
4205     return lowerVectorMaskTruncLike(Op, DAG);
4206 
4207   // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
4208   // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
4209   // truncate by one power of two at a time.
4210   MVT DstEltVT = VT.getVectorElementType();
4211 
4212   SDValue Src = Op.getOperand(0);
4213   MVT SrcVT = Src.getSimpleValueType();
4214   MVT SrcEltVT = SrcVT.getVectorElementType();
4215 
4216   assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) &&
4217          isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
4218          "Unexpected vector truncate lowering");
4219 
4220   MVT ContainerVT = SrcVT;
4221   SDValue Mask, VL;
4222   if (IsVPTrunc) {
4223     Mask = Op.getOperand(1);
4224     VL = Op.getOperand(2);
4225   }
4226   if (SrcVT.isFixedLengthVector()) {
4227     ContainerVT = getContainerForFixedLengthVector(SrcVT);
4228     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4229     if (IsVPTrunc) {
4230       MVT MaskVT =
4231           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4232       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4233     }
4234   }
4235 
4236   SDValue Result = Src;
4237   if (!IsVPTrunc) {
4238     std::tie(Mask, VL) =
4239         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4240   }
4241 
4242   LLVMContext &Context = *DAG.getContext();
4243   const ElementCount Count = ContainerVT.getVectorElementCount();
4244   do {
4245     SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
4246     EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
4247     Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
4248                          Mask, VL);
4249   } while (SrcEltVT != DstEltVT);
4250 
4251   if (SrcVT.isFixedLengthVector())
4252     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4253 
4254   return Result;
4255 }
4256 
4257 SDValue RISCVTargetLowering::lowerVectorFPRoundLike(SDValue Op,
4258                                                     SelectionDAG &DAG) const {
4259   bool IsVPFPTrunc = Op.getOpcode() == ISD::VP_FP_ROUND;
4260   // RVV can only do truncate fp to types half the size as the source. We
4261   // custom-lower f64->f16 rounds via RVV's round-to-odd float
4262   // conversion instruction.
4263   SDLoc DL(Op);
4264   MVT VT = Op.getSimpleValueType();
4265 
4266   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4267 
4268   SDValue Src = Op.getOperand(0);
4269   MVT SrcVT = Src.getSimpleValueType();
4270 
4271   bool IsDirectConv = VT.getVectorElementType() != MVT::f16 ||
4272                       SrcVT.getVectorElementType() != MVT::f64;
4273 
4274   // For FP_ROUND of scalable vectors, leave it to the pattern.
4275   if (!VT.isFixedLengthVector() && !IsVPFPTrunc && IsDirectConv)
4276     return Op;
4277 
4278   // Prepare any fixed-length vector operands.
4279   MVT ContainerVT = VT;
4280   SDValue Mask, VL;
4281   if (IsVPFPTrunc) {
4282     Mask = Op.getOperand(1);
4283     VL = Op.getOperand(2);
4284   }
4285   if (VT.isFixedLengthVector()) {
4286     MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
4287     ContainerVT =
4288         SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
4289     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
4290     if (IsVPFPTrunc) {
4291       MVT MaskVT =
4292           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4293       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4294     }
4295   }
4296 
4297   if (!IsVPFPTrunc)
4298     std::tie(Mask, VL) =
4299         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4300 
4301   if (IsDirectConv) {
4302     Src = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, ContainerVT, Src, Mask, VL);
4303     if (VT.isFixedLengthVector())
4304       Src = convertFromScalableVector(VT, Src, DAG, Subtarget);
4305     return Src;
4306   }
4307 
4308   MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
4309   SDValue IntermediateRound =
4310       DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
4311   SDValue Round = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, ContainerVT,
4312                               IntermediateRound, Mask, VL);
4313   if (VT.isFixedLengthVector())
4314     return convertFromScalableVector(VT, Round, DAG, Subtarget);
4315   return Round;
4316 }
4317 
4318 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4319 // first position of a vector, and that vector is slid up to the insert index.
4320 // By limiting the active vector length to index+1 and merging with the
4321 // original vector (with an undisturbed tail policy for elements >= VL), we
4322 // achieve the desired result of leaving all elements untouched except the one
4323 // at VL-1, which is replaced with the desired value.
4324 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4325                                                     SelectionDAG &DAG) const {
4326   SDLoc DL(Op);
4327   MVT VecVT = Op.getSimpleValueType();
4328   SDValue Vec = Op.getOperand(0);
4329   SDValue Val = Op.getOperand(1);
4330   SDValue Idx = Op.getOperand(2);
4331 
4332   if (VecVT.getVectorElementType() == MVT::i1) {
4333     // FIXME: For now we just promote to an i8 vector and insert into that,
4334     // but this is probably not optimal.
4335     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4336     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4337     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4338     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4339   }
4340 
4341   MVT ContainerVT = VecVT;
4342   // If the operand is a fixed-length vector, convert to a scalable one.
4343   if (VecVT.isFixedLengthVector()) {
4344     ContainerVT = getContainerForFixedLengthVector(VecVT);
4345     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4346   }
4347 
4348   MVT XLenVT = Subtarget.getXLenVT();
4349 
4350   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4351   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4352   // Even i64-element vectors on RV32 can be lowered without scalar
4353   // legalization if the most-significant 32 bits of the value are not affected
4354   // by the sign-extension of the lower 32 bits.
4355   // TODO: We could also catch sign extensions of a 32-bit value.
4356   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4357     const auto *CVal = cast<ConstantSDNode>(Val);
4358     if (isInt<32>(CVal->getSExtValue())) {
4359       IsLegalInsert = true;
4360       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4361     }
4362   }
4363 
4364   SDValue Mask, VL;
4365   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4366 
4367   SDValue ValInVec;
4368 
4369   if (IsLegalInsert) {
4370     unsigned Opc =
4371         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4372     if (isNullConstant(Idx)) {
4373       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4374       if (!VecVT.isFixedLengthVector())
4375         return Vec;
4376       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4377     }
4378     ValInVec =
4379         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4380   } else {
4381     // On RV32, i64-element vectors must be specially handled to place the
4382     // value at element 0, by using two vslide1up instructions in sequence on
4383     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4384     // this.
4385     SDValue One = DAG.getConstant(1, DL, XLenVT);
4386     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4387     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4388     MVT I32ContainerVT =
4389         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4390     SDValue I32Mask =
4391         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4392     // Limit the active VL to two.
4393     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4394     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4395     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4396     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4397                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4398     // First slide in the hi value, then the lo in underneath it.
4399     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4400                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4401                            I32Mask, InsertI64VL);
4402     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4403                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4404                            I32Mask, InsertI64VL);
4405     // Bitcast back to the right container type.
4406     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4407   }
4408 
4409   // Now that the value is in a vector, slide it into position.
4410   SDValue InsertVL =
4411       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4412   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4413                                 ValInVec, Idx, Mask, InsertVL);
4414   if (!VecVT.isFixedLengthVector())
4415     return Slideup;
4416   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4417 }
4418 
4419 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4420 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4421 // types this is done using VMV_X_S to allow us to glean information about the
4422 // sign bits of the result.
4423 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4424                                                      SelectionDAG &DAG) const {
4425   SDLoc DL(Op);
4426   SDValue Idx = Op.getOperand(1);
4427   SDValue Vec = Op.getOperand(0);
4428   EVT EltVT = Op.getValueType();
4429   MVT VecVT = Vec.getSimpleValueType();
4430   MVT XLenVT = Subtarget.getXLenVT();
4431 
4432   if (VecVT.getVectorElementType() == MVT::i1) {
4433     if (VecVT.isFixedLengthVector()) {
4434       unsigned NumElts = VecVT.getVectorNumElements();
4435       if (NumElts >= 8) {
4436         MVT WideEltVT;
4437         unsigned WidenVecLen;
4438         SDValue ExtractElementIdx;
4439         SDValue ExtractBitIdx;
4440         unsigned MaxEEW = Subtarget.getELEN();
4441         MVT LargestEltVT = MVT::getIntegerVT(
4442             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4443         if (NumElts <= LargestEltVT.getSizeInBits()) {
4444           assert(isPowerOf2_32(NumElts) &&
4445                  "the number of elements should be power of 2");
4446           WideEltVT = MVT::getIntegerVT(NumElts);
4447           WidenVecLen = 1;
4448           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4449           ExtractBitIdx = Idx;
4450         } else {
4451           WideEltVT = LargestEltVT;
4452           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4453           // extract element index = index / element width
4454           ExtractElementIdx = DAG.getNode(
4455               ISD::SRL, DL, XLenVT, Idx,
4456               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4457           // mask bit index = index % element width
4458           ExtractBitIdx = DAG.getNode(
4459               ISD::AND, DL, XLenVT, Idx,
4460               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4461         }
4462         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4463         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4464         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4465                                          Vec, ExtractElementIdx);
4466         // Extract the bit from GPR.
4467         SDValue ShiftRight =
4468             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4469         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4470                            DAG.getConstant(1, DL, XLenVT));
4471       }
4472     }
4473     // Otherwise, promote to an i8 vector and extract from that.
4474     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4475     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4476     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4477   }
4478 
4479   // If this is a fixed vector, we need to convert it to a scalable vector.
4480   MVT ContainerVT = VecVT;
4481   if (VecVT.isFixedLengthVector()) {
4482     ContainerVT = getContainerForFixedLengthVector(VecVT);
4483     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4484   }
4485 
4486   // If the index is 0, the vector is already in the right position.
4487   if (!isNullConstant(Idx)) {
4488     // Use a VL of 1 to avoid processing more elements than we need.
4489     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4490     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4491     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4492     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4493                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4494   }
4495 
4496   if (!EltVT.isInteger()) {
4497     // Floating-point extracts are handled in TableGen.
4498     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4499                        DAG.getConstant(0, DL, XLenVT));
4500   }
4501 
4502   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4503   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4504 }
4505 
4506 // Some RVV intrinsics may claim that they want an integer operand to be
4507 // promoted or expanded.
4508 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4509                                            const RISCVSubtarget &Subtarget) {
4510   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4511           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4512          "Unexpected opcode");
4513 
4514   if (!Subtarget.hasVInstructions())
4515     return SDValue();
4516 
4517   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4518   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4519   SDLoc DL(Op);
4520 
4521   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4522       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4523   if (!II || !II->hasScalarOperand())
4524     return SDValue();
4525 
4526   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4527   assert(SplatOp < Op.getNumOperands());
4528 
4529   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4530   SDValue &ScalarOp = Operands[SplatOp];
4531   MVT OpVT = ScalarOp.getSimpleValueType();
4532   MVT XLenVT = Subtarget.getXLenVT();
4533 
4534   // If this isn't a scalar, or its type is XLenVT we're done.
4535   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4536     return SDValue();
4537 
4538   // Simplest case is that the operand needs to be promoted to XLenVT.
4539   if (OpVT.bitsLT(XLenVT)) {
4540     // If the operand is a constant, sign extend to increase our chances
4541     // of being able to use a .vi instruction. ANY_EXTEND would become a
4542     // a zero extend and the simm5 check in isel would fail.
4543     // FIXME: Should we ignore the upper bits in isel instead?
4544     unsigned ExtOpc =
4545         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4546     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4547     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4548   }
4549 
4550   // Use the previous operand to get the vXi64 VT. The result might be a mask
4551   // VT for compares. Using the previous operand assumes that the previous
4552   // operand will never have a smaller element size than a scalar operand and
4553   // that a widening operation never uses SEW=64.
4554   // NOTE: If this fails the below assert, we can probably just find the
4555   // element count from any operand or result and use it to construct the VT.
4556   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4557   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4558 
4559   // The more complex case is when the scalar is larger than XLenVT.
4560   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4561          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4562 
4563   // If this is a sign-extended 32-bit value, we can truncate it and rely on the
4564   // instruction to sign-extend since SEW>XLEN.
4565   if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
4566     ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
4567     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4568   }
4569 
4570   switch (IntNo) {
4571   case Intrinsic::riscv_vslide1up:
4572   case Intrinsic::riscv_vslide1down:
4573   case Intrinsic::riscv_vslide1up_mask:
4574   case Intrinsic::riscv_vslide1down_mask: {
4575     // We need to special case these when the scalar is larger than XLen.
4576     unsigned NumOps = Op.getNumOperands();
4577     bool IsMasked = NumOps == 7;
4578 
4579     // Convert the vector source to the equivalent nxvXi32 vector.
4580     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4581     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4582 
4583     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4584                                    DAG.getConstant(0, DL, XLenVT));
4585     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4586                                    DAG.getConstant(1, DL, XLenVT));
4587 
4588     // Double the VL since we halved SEW.
4589     SDValue AVL = getVLOperand(Op);
4590     SDValue I32VL;
4591 
4592     // Optimize for constant AVL
4593     if (isa<ConstantSDNode>(AVL)) {
4594       unsigned EltSize = VT.getScalarSizeInBits();
4595       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4596 
4597       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4598       unsigned MaxVLMAX =
4599           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4600 
4601       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4602       unsigned MinVLMAX =
4603           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4604 
4605       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4606       if (AVLInt <= MinVLMAX) {
4607         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4608       } else if (AVLInt >= 2 * MaxVLMAX) {
4609         // Just set vl to VLMAX in this situation
4610         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4611         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4612         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4613         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4614         SDValue SETVLMAX = DAG.getTargetConstant(
4615             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4616         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4617                             LMUL);
4618       } else {
4619         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4620         // is related to the hardware implementation.
4621         // So let the following code handle
4622       }
4623     }
4624     if (!I32VL) {
4625       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4626       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4627       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4628       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4629       SDValue SETVL =
4630           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4631       // Using vsetvli instruction to get actually used length which related to
4632       // the hardware implementation
4633       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4634                                SEW, LMUL);
4635       I32VL =
4636           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4637     }
4638 
4639     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4640     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, I32VL);
4641 
4642     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4643     // instructions.
4644     SDValue Passthru;
4645     if (IsMasked)
4646       Passthru = DAG.getUNDEF(I32VT);
4647     else
4648       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4649 
4650     if (IntNo == Intrinsic::riscv_vslide1up ||
4651         IntNo == Intrinsic::riscv_vslide1up_mask) {
4652       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4653                         ScalarHi, I32Mask, I32VL);
4654       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4655                         ScalarLo, I32Mask, I32VL);
4656     } else {
4657       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4658                         ScalarLo, I32Mask, I32VL);
4659       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4660                         ScalarHi, I32Mask, I32VL);
4661     }
4662 
4663     // Convert back to nxvXi64.
4664     Vec = DAG.getBitcast(VT, Vec);
4665 
4666     if (!IsMasked)
4667       return Vec;
4668     // Apply mask after the operation.
4669     SDValue Mask = Operands[NumOps - 3];
4670     SDValue MaskedOff = Operands[1];
4671     // Assume Policy operand is the last operand.
4672     uint64_t Policy =
4673         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4674     // We don't need to select maskedoff if it's undef.
4675     if (MaskedOff.isUndef())
4676       return Vec;
4677     // TAMU
4678     if (Policy == RISCVII::TAIL_AGNOSTIC)
4679       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4680                          AVL);
4681     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4682     // It's fine because vmerge does not care mask policy.
4683     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4684                        AVL);
4685   }
4686   }
4687 
4688   // We need to convert the scalar to a splat vector.
4689   SDValue VL = getVLOperand(Op);
4690   assert(VL.getValueType() == XLenVT);
4691   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4692   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4693 }
4694 
4695 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4696                                                      SelectionDAG &DAG) const {
4697   unsigned IntNo = Op.getConstantOperandVal(0);
4698   SDLoc DL(Op);
4699   MVT XLenVT = Subtarget.getXLenVT();
4700 
4701   switch (IntNo) {
4702   default:
4703     break; // Don't custom lower most intrinsics.
4704   case Intrinsic::thread_pointer: {
4705     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4706     return DAG.getRegister(RISCV::X4, PtrVT);
4707   }
4708   case Intrinsic::riscv_orc_b:
4709   case Intrinsic::riscv_brev8: {
4710     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4711     unsigned Opc =
4712         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4713     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4714                        DAG.getConstant(7, DL, XLenVT));
4715   }
4716   case Intrinsic::riscv_grev:
4717   case Intrinsic::riscv_gorc: {
4718     unsigned Opc =
4719         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4720     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4721   }
4722   case Intrinsic::riscv_zip:
4723   case Intrinsic::riscv_unzip: {
4724     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4725     // For i32 the immediate is 15. For i64 the immediate is 31.
4726     unsigned Opc =
4727         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4728     unsigned BitWidth = Op.getValueSizeInBits();
4729     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4730     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4731                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4732   }
4733   case Intrinsic::riscv_shfl:
4734   case Intrinsic::riscv_unshfl: {
4735     unsigned Opc =
4736         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4737     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4738   }
4739   case Intrinsic::riscv_bcompress:
4740   case Intrinsic::riscv_bdecompress: {
4741     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4742                                                        : RISCVISD::BDECOMPRESS;
4743     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4744   }
4745   case Intrinsic::riscv_bfp:
4746     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4747                        Op.getOperand(2));
4748   case Intrinsic::riscv_fsl:
4749     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4750                        Op.getOperand(2), Op.getOperand(3));
4751   case Intrinsic::riscv_fsr:
4752     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4753                        Op.getOperand(2), Op.getOperand(3));
4754   case Intrinsic::riscv_vmv_x_s:
4755     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4756     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4757                        Op.getOperand(1));
4758   case Intrinsic::riscv_vmv_v_x:
4759     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4760                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4761                             Subtarget);
4762   case Intrinsic::riscv_vfmv_v_f:
4763     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4764                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4765   case Intrinsic::riscv_vmv_s_x: {
4766     SDValue Scalar = Op.getOperand(2);
4767 
4768     if (Scalar.getValueType().bitsLE(XLenVT)) {
4769       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4770       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4771                          Op.getOperand(1), Scalar, Op.getOperand(3));
4772     }
4773 
4774     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4775 
4776     // This is an i64 value that lives in two scalar registers. We have to
4777     // insert this in a convoluted way. First we build vXi64 splat containing
4778     // the two values that we assemble using some bit math. Next we'll use
4779     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4780     // to merge element 0 from our splat into the source vector.
4781     // FIXME: This is probably not the best way to do this, but it is
4782     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4783     // point.
4784     //   sw lo, (a0)
4785     //   sw hi, 4(a0)
4786     //   vlse vX, (a0)
4787     //
4788     //   vid.v      vVid
4789     //   vmseq.vx   mMask, vVid, 0
4790     //   vmerge.vvm vDest, vSrc, vVal, mMask
4791     MVT VT = Op.getSimpleValueType();
4792     SDValue Vec = Op.getOperand(1);
4793     SDValue VL = getVLOperand(Op);
4794 
4795     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4796     if (Op.getOperand(1).isUndef())
4797       return SplattedVal;
4798     SDValue SplattedIdx =
4799         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4800                     DAG.getConstant(0, DL, MVT::i32), VL);
4801 
4802     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4803     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4804     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4805     SDValue SelectCond =
4806         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4807                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4808     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4809                        Vec, VL);
4810   }
4811   }
4812 
4813   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4814 }
4815 
4816 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4817                                                     SelectionDAG &DAG) const {
4818   unsigned IntNo = Op.getConstantOperandVal(1);
4819   switch (IntNo) {
4820   default:
4821     break;
4822   case Intrinsic::riscv_masked_strided_load: {
4823     SDLoc DL(Op);
4824     MVT XLenVT = Subtarget.getXLenVT();
4825 
4826     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4827     // the selection of the masked intrinsics doesn't do this for us.
4828     SDValue Mask = Op.getOperand(5);
4829     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4830 
4831     MVT VT = Op->getSimpleValueType(0);
4832     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4833 
4834     SDValue PassThru = Op.getOperand(2);
4835     if (!IsUnmasked) {
4836       MVT MaskVT =
4837           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4838       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4839       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4840     }
4841 
4842     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4843 
4844     SDValue IntID = DAG.getTargetConstant(
4845         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4846         XLenVT);
4847 
4848     auto *Load = cast<MemIntrinsicSDNode>(Op);
4849     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4850     if (IsUnmasked)
4851       Ops.push_back(DAG.getUNDEF(ContainerVT));
4852     else
4853       Ops.push_back(PassThru);
4854     Ops.push_back(Op.getOperand(3)); // Ptr
4855     Ops.push_back(Op.getOperand(4)); // Stride
4856     if (!IsUnmasked)
4857       Ops.push_back(Mask);
4858     Ops.push_back(VL);
4859     if (!IsUnmasked) {
4860       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4861       Ops.push_back(Policy);
4862     }
4863 
4864     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4865     SDValue Result =
4866         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4867                                 Load->getMemoryVT(), Load->getMemOperand());
4868     SDValue Chain = Result.getValue(1);
4869     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4870     return DAG.getMergeValues({Result, Chain}, DL);
4871   }
4872   case Intrinsic::riscv_seg2_load:
4873   case Intrinsic::riscv_seg3_load:
4874   case Intrinsic::riscv_seg4_load:
4875   case Intrinsic::riscv_seg5_load:
4876   case Intrinsic::riscv_seg6_load:
4877   case Intrinsic::riscv_seg7_load:
4878   case Intrinsic::riscv_seg8_load: {
4879     SDLoc DL(Op);
4880     static const Intrinsic::ID VlsegInts[7] = {
4881         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
4882         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
4883         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
4884         Intrinsic::riscv_vlseg8};
4885     unsigned NF = Op->getNumValues() - 1;
4886     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
4887     MVT XLenVT = Subtarget.getXLenVT();
4888     MVT VT = Op->getSimpleValueType(0);
4889     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4890 
4891     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4892     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
4893     auto *Load = cast<MemIntrinsicSDNode>(Op);
4894     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
4895     ContainerVTs.push_back(MVT::Other);
4896     SDVTList VTs = DAG.getVTList(ContainerVTs);
4897     SDValue Result =
4898         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs,
4899                                 {Load->getChain(), IntID, Op.getOperand(2), VL},
4900                                 Load->getMemoryVT(), Load->getMemOperand());
4901     SmallVector<SDValue, 9> Results;
4902     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
4903       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
4904                                                   DAG, Subtarget));
4905     Results.push_back(Result.getValue(NF));
4906     return DAG.getMergeValues(Results, DL);
4907   }
4908   }
4909 
4910   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4911 }
4912 
4913 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4914                                                  SelectionDAG &DAG) const {
4915   unsigned IntNo = Op.getConstantOperandVal(1);
4916   switch (IntNo) {
4917   default:
4918     break;
4919   case Intrinsic::riscv_masked_strided_store: {
4920     SDLoc DL(Op);
4921     MVT XLenVT = Subtarget.getXLenVT();
4922 
4923     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4924     // the selection of the masked intrinsics doesn't do this for us.
4925     SDValue Mask = Op.getOperand(5);
4926     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4927 
4928     SDValue Val = Op.getOperand(2);
4929     MVT VT = Val.getSimpleValueType();
4930     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4931 
4932     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4933     if (!IsUnmasked) {
4934       MVT MaskVT =
4935           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4936       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4937     }
4938 
4939     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4940 
4941     SDValue IntID = DAG.getTargetConstant(
4942         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4943         XLenVT);
4944 
4945     auto *Store = cast<MemIntrinsicSDNode>(Op);
4946     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4947     Ops.push_back(Val);
4948     Ops.push_back(Op.getOperand(3)); // Ptr
4949     Ops.push_back(Op.getOperand(4)); // Stride
4950     if (!IsUnmasked)
4951       Ops.push_back(Mask);
4952     Ops.push_back(VL);
4953 
4954     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4955                                    Ops, Store->getMemoryVT(),
4956                                    Store->getMemOperand());
4957   }
4958   }
4959 
4960   return SDValue();
4961 }
4962 
4963 static MVT getLMUL1VT(MVT VT) {
4964   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4965          "Unexpected vector MVT");
4966   return MVT::getScalableVectorVT(
4967       VT.getVectorElementType(),
4968       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4969 }
4970 
4971 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4972   switch (ISDOpcode) {
4973   default:
4974     llvm_unreachable("Unhandled reduction");
4975   case ISD::VECREDUCE_ADD:
4976     return RISCVISD::VECREDUCE_ADD_VL;
4977   case ISD::VECREDUCE_UMAX:
4978     return RISCVISD::VECREDUCE_UMAX_VL;
4979   case ISD::VECREDUCE_SMAX:
4980     return RISCVISD::VECREDUCE_SMAX_VL;
4981   case ISD::VECREDUCE_UMIN:
4982     return RISCVISD::VECREDUCE_UMIN_VL;
4983   case ISD::VECREDUCE_SMIN:
4984     return RISCVISD::VECREDUCE_SMIN_VL;
4985   case ISD::VECREDUCE_AND:
4986     return RISCVISD::VECREDUCE_AND_VL;
4987   case ISD::VECREDUCE_OR:
4988     return RISCVISD::VECREDUCE_OR_VL;
4989   case ISD::VECREDUCE_XOR:
4990     return RISCVISD::VECREDUCE_XOR_VL;
4991   }
4992 }
4993 
4994 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4995                                                          SelectionDAG &DAG,
4996                                                          bool IsVP) const {
4997   SDLoc DL(Op);
4998   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4999   MVT VecVT = Vec.getSimpleValueType();
5000   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5001           Op.getOpcode() == ISD::VECREDUCE_OR ||
5002           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5003           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5004           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5005           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5006          "Unexpected reduction lowering");
5007 
5008   MVT XLenVT = Subtarget.getXLenVT();
5009   assert(Op.getValueType() == XLenVT &&
5010          "Expected reduction output to be legalized to XLenVT");
5011 
5012   MVT ContainerVT = VecVT;
5013   if (VecVT.isFixedLengthVector()) {
5014     ContainerVT = getContainerForFixedLengthVector(VecVT);
5015     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5016   }
5017 
5018   SDValue Mask, VL;
5019   if (IsVP) {
5020     Mask = Op.getOperand(2);
5021     VL = Op.getOperand(3);
5022   } else {
5023     std::tie(Mask, VL) =
5024         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5025   }
5026 
5027   unsigned BaseOpc;
5028   ISD::CondCode CC;
5029   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5030 
5031   switch (Op.getOpcode()) {
5032   default:
5033     llvm_unreachable("Unhandled reduction");
5034   case ISD::VECREDUCE_AND:
5035   case ISD::VP_REDUCE_AND: {
5036     // vcpop ~x == 0
5037     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5038     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5039     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5040     CC = ISD::SETEQ;
5041     BaseOpc = ISD::AND;
5042     break;
5043   }
5044   case ISD::VECREDUCE_OR:
5045   case ISD::VP_REDUCE_OR:
5046     // vcpop x != 0
5047     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5048     CC = ISD::SETNE;
5049     BaseOpc = ISD::OR;
5050     break;
5051   case ISD::VECREDUCE_XOR:
5052   case ISD::VP_REDUCE_XOR: {
5053     // ((vcpop x) & 1) != 0
5054     SDValue One = DAG.getConstant(1, DL, XLenVT);
5055     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5056     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5057     CC = ISD::SETNE;
5058     BaseOpc = ISD::XOR;
5059     break;
5060   }
5061   }
5062 
5063   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5064 
5065   if (!IsVP)
5066     return SetCC;
5067 
5068   // Now include the start value in the operation.
5069   // Note that we must return the start value when no elements are operated
5070   // upon. The vcpop instructions we've emitted in each case above will return
5071   // 0 for an inactive vector, and so we've already received the neutral value:
5072   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5073   // can simply include the start value.
5074   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5075 }
5076 
5077 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5078                                             SelectionDAG &DAG) const {
5079   SDLoc DL(Op);
5080   SDValue Vec = Op.getOperand(0);
5081   EVT VecEVT = Vec.getValueType();
5082 
5083   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5084 
5085   // Due to ordering in legalize types we may have a vector type that needs to
5086   // be split. Do that manually so we can get down to a legal type.
5087   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5088          TargetLowering::TypeSplitVector) {
5089     SDValue Lo, Hi;
5090     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5091     VecEVT = Lo.getValueType();
5092     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5093   }
5094 
5095   // TODO: The type may need to be widened rather than split. Or widened before
5096   // it can be split.
5097   if (!isTypeLegal(VecEVT))
5098     return SDValue();
5099 
5100   MVT VecVT = VecEVT.getSimpleVT();
5101   MVT VecEltVT = VecVT.getVectorElementType();
5102   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5103 
5104   MVT ContainerVT = VecVT;
5105   if (VecVT.isFixedLengthVector()) {
5106     ContainerVT = getContainerForFixedLengthVector(VecVT);
5107     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5108   }
5109 
5110   MVT M1VT = getLMUL1VT(ContainerVT);
5111   MVT XLenVT = Subtarget.getXLenVT();
5112 
5113   SDValue Mask, VL;
5114   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5115 
5116   SDValue NeutralElem =
5117       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5118   SDValue IdentitySplat =
5119       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5120                        M1VT, DL, DAG, Subtarget);
5121   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5122                                   IdentitySplat, Mask, VL);
5123   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5124                              DAG.getConstant(0, DL, XLenVT));
5125   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5126 }
5127 
5128 // Given a reduction op, this function returns the matching reduction opcode,
5129 // the vector SDValue and the scalar SDValue required to lower this to a
5130 // RISCVISD node.
5131 static std::tuple<unsigned, SDValue, SDValue>
5132 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5133   SDLoc DL(Op);
5134   auto Flags = Op->getFlags();
5135   unsigned Opcode = Op.getOpcode();
5136   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5137   switch (Opcode) {
5138   default:
5139     llvm_unreachable("Unhandled reduction");
5140   case ISD::VECREDUCE_FADD: {
5141     // Use positive zero if we can. It is cheaper to materialize.
5142     SDValue Zero =
5143         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5144     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5145   }
5146   case ISD::VECREDUCE_SEQ_FADD:
5147     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5148                            Op.getOperand(0));
5149   case ISD::VECREDUCE_FMIN:
5150     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5151                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5152   case ISD::VECREDUCE_FMAX:
5153     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5154                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5155   }
5156 }
5157 
5158 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5159                                               SelectionDAG &DAG) const {
5160   SDLoc DL(Op);
5161   MVT VecEltVT = Op.getSimpleValueType();
5162 
5163   unsigned RVVOpcode;
5164   SDValue VectorVal, ScalarVal;
5165   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5166       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5167   MVT VecVT = VectorVal.getSimpleValueType();
5168 
5169   MVT ContainerVT = VecVT;
5170   if (VecVT.isFixedLengthVector()) {
5171     ContainerVT = getContainerForFixedLengthVector(VecVT);
5172     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5173   }
5174 
5175   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5176   MVT XLenVT = Subtarget.getXLenVT();
5177 
5178   SDValue Mask, VL;
5179   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5180 
5181   SDValue ScalarSplat =
5182       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5183                        M1VT, DL, DAG, Subtarget);
5184   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5185                                   VectorVal, ScalarSplat, Mask, VL);
5186   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5187                      DAG.getConstant(0, DL, XLenVT));
5188 }
5189 
5190 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5191   switch (ISDOpcode) {
5192   default:
5193     llvm_unreachable("Unhandled reduction");
5194   case ISD::VP_REDUCE_ADD:
5195     return RISCVISD::VECREDUCE_ADD_VL;
5196   case ISD::VP_REDUCE_UMAX:
5197     return RISCVISD::VECREDUCE_UMAX_VL;
5198   case ISD::VP_REDUCE_SMAX:
5199     return RISCVISD::VECREDUCE_SMAX_VL;
5200   case ISD::VP_REDUCE_UMIN:
5201     return RISCVISD::VECREDUCE_UMIN_VL;
5202   case ISD::VP_REDUCE_SMIN:
5203     return RISCVISD::VECREDUCE_SMIN_VL;
5204   case ISD::VP_REDUCE_AND:
5205     return RISCVISD::VECREDUCE_AND_VL;
5206   case ISD::VP_REDUCE_OR:
5207     return RISCVISD::VECREDUCE_OR_VL;
5208   case ISD::VP_REDUCE_XOR:
5209     return RISCVISD::VECREDUCE_XOR_VL;
5210   case ISD::VP_REDUCE_FADD:
5211     return RISCVISD::VECREDUCE_FADD_VL;
5212   case ISD::VP_REDUCE_SEQ_FADD:
5213     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5214   case ISD::VP_REDUCE_FMAX:
5215     return RISCVISD::VECREDUCE_FMAX_VL;
5216   case ISD::VP_REDUCE_FMIN:
5217     return RISCVISD::VECREDUCE_FMIN_VL;
5218   }
5219 }
5220 
5221 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5222                                            SelectionDAG &DAG) const {
5223   SDLoc DL(Op);
5224   SDValue Vec = Op.getOperand(1);
5225   EVT VecEVT = Vec.getValueType();
5226 
5227   // TODO: The type may need to be widened rather than split. Or widened before
5228   // it can be split.
5229   if (!isTypeLegal(VecEVT))
5230     return SDValue();
5231 
5232   MVT VecVT = VecEVT.getSimpleVT();
5233   MVT VecEltVT = VecVT.getVectorElementType();
5234   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5235 
5236   MVT ContainerVT = VecVT;
5237   if (VecVT.isFixedLengthVector()) {
5238     ContainerVT = getContainerForFixedLengthVector(VecVT);
5239     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5240   }
5241 
5242   SDValue VL = Op.getOperand(3);
5243   SDValue Mask = Op.getOperand(2);
5244 
5245   MVT M1VT = getLMUL1VT(ContainerVT);
5246   MVT XLenVT = Subtarget.getXLenVT();
5247   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5248 
5249   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5250                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5251                                         DL, DAG, Subtarget);
5252   SDValue Reduction =
5253       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5254   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5255                              DAG.getConstant(0, DL, XLenVT));
5256   if (!VecVT.isInteger())
5257     return Elt0;
5258   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5259 }
5260 
5261 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5262                                                    SelectionDAG &DAG) const {
5263   SDValue Vec = Op.getOperand(0);
5264   SDValue SubVec = Op.getOperand(1);
5265   MVT VecVT = Vec.getSimpleValueType();
5266   MVT SubVecVT = SubVec.getSimpleValueType();
5267 
5268   SDLoc DL(Op);
5269   MVT XLenVT = Subtarget.getXLenVT();
5270   unsigned OrigIdx = Op.getConstantOperandVal(2);
5271   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5272 
5273   // We don't have the ability to slide mask vectors up indexed by their i1
5274   // elements; the smallest we can do is i8. Often we are able to bitcast to
5275   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5276   // into a scalable one, we might not necessarily have enough scalable
5277   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5278   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5279       (OrigIdx != 0 || !Vec.isUndef())) {
5280     if (VecVT.getVectorMinNumElements() >= 8 &&
5281         SubVecVT.getVectorMinNumElements() >= 8) {
5282       assert(OrigIdx % 8 == 0 && "Invalid index");
5283       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5284              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5285              "Unexpected mask vector lowering");
5286       OrigIdx /= 8;
5287       SubVecVT =
5288           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5289                            SubVecVT.isScalableVector());
5290       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5291                                VecVT.isScalableVector());
5292       Vec = DAG.getBitcast(VecVT, Vec);
5293       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5294     } else {
5295       // We can't slide this mask vector up indexed by its i1 elements.
5296       // This poses a problem when we wish to insert a scalable vector which
5297       // can't be re-expressed as a larger type. Just choose the slow path and
5298       // extend to a larger type, then truncate back down.
5299       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5300       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5301       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5302       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5303       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5304                         Op.getOperand(2));
5305       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5306       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5307     }
5308   }
5309 
5310   // If the subvector vector is a fixed-length type, we cannot use subregister
5311   // manipulation to simplify the codegen; we don't know which register of a
5312   // LMUL group contains the specific subvector as we only know the minimum
5313   // register size. Therefore we must slide the vector group up the full
5314   // amount.
5315   if (SubVecVT.isFixedLengthVector()) {
5316     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5317       return Op;
5318     MVT ContainerVT = VecVT;
5319     if (VecVT.isFixedLengthVector()) {
5320       ContainerVT = getContainerForFixedLengthVector(VecVT);
5321       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5322     }
5323     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5324                          DAG.getUNDEF(ContainerVT), SubVec,
5325                          DAG.getConstant(0, DL, XLenVT));
5326     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5327       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5328       return DAG.getBitcast(Op.getValueType(), SubVec);
5329     }
5330     SDValue Mask =
5331         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5332     // Set the vector length to only the number of elements we care about. Note
5333     // that for slideup this includes the offset.
5334     SDValue VL =
5335         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5336     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5337     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5338                                   SubVec, SlideupAmt, Mask, VL);
5339     if (VecVT.isFixedLengthVector())
5340       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5341     return DAG.getBitcast(Op.getValueType(), Slideup);
5342   }
5343 
5344   unsigned SubRegIdx, RemIdx;
5345   std::tie(SubRegIdx, RemIdx) =
5346       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5347           VecVT, SubVecVT, OrigIdx, TRI);
5348 
5349   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5350   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5351                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5352                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5353 
5354   // 1. If the Idx has been completely eliminated and this subvector's size is
5355   // a vector register or a multiple thereof, or the surrounding elements are
5356   // undef, then this is a subvector insert which naturally aligns to a vector
5357   // register. These can easily be handled using subregister manipulation.
5358   // 2. If the subvector is smaller than a vector register, then the insertion
5359   // must preserve the undisturbed elements of the register. We do this by
5360   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5361   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5362   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5363   // LMUL=1 type back into the larger vector (resolving to another subregister
5364   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5365   // to avoid allocating a large register group to hold our subvector.
5366   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5367     return Op;
5368 
5369   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5370   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5371   // (in our case undisturbed). This means we can set up a subvector insertion
5372   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5373   // size of the subvector.
5374   MVT InterSubVT = VecVT;
5375   SDValue AlignedExtract = Vec;
5376   unsigned AlignedIdx = OrigIdx - RemIdx;
5377   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5378     InterSubVT = getLMUL1VT(VecVT);
5379     // Extract a subvector equal to the nearest full vector register type. This
5380     // should resolve to a EXTRACT_SUBREG instruction.
5381     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5382                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5383   }
5384 
5385   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5386   // For scalable vectors this must be further multiplied by vscale.
5387   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5388 
5389   SDValue Mask, VL;
5390   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5391 
5392   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5393   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5394   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5395   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5396 
5397   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5398                        DAG.getUNDEF(InterSubVT), SubVec,
5399                        DAG.getConstant(0, DL, XLenVT));
5400 
5401   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5402                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5403 
5404   // If required, insert this subvector back into the correct vector register.
5405   // This should resolve to an INSERT_SUBREG instruction.
5406   if (VecVT.bitsGT(InterSubVT))
5407     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5408                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5409 
5410   // We might have bitcast from a mask type: cast back to the original type if
5411   // required.
5412   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5413 }
5414 
5415 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5416                                                     SelectionDAG &DAG) const {
5417   SDValue Vec = Op.getOperand(0);
5418   MVT SubVecVT = Op.getSimpleValueType();
5419   MVT VecVT = Vec.getSimpleValueType();
5420 
5421   SDLoc DL(Op);
5422   MVT XLenVT = Subtarget.getXLenVT();
5423   unsigned OrigIdx = Op.getConstantOperandVal(1);
5424   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5425 
5426   // We don't have the ability to slide mask vectors down indexed by their i1
5427   // elements; the smallest we can do is i8. Often we are able to bitcast to
5428   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5429   // from a scalable one, we might not necessarily have enough scalable
5430   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5431   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5432     if (VecVT.getVectorMinNumElements() >= 8 &&
5433         SubVecVT.getVectorMinNumElements() >= 8) {
5434       assert(OrigIdx % 8 == 0 && "Invalid index");
5435       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5436              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5437              "Unexpected mask vector lowering");
5438       OrigIdx /= 8;
5439       SubVecVT =
5440           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5441                            SubVecVT.isScalableVector());
5442       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5443                                VecVT.isScalableVector());
5444       Vec = DAG.getBitcast(VecVT, Vec);
5445     } else {
5446       // We can't slide this mask vector down, indexed by its i1 elements.
5447       // This poses a problem when we wish to extract a scalable vector which
5448       // can't be re-expressed as a larger type. Just choose the slow path and
5449       // extend to a larger type, then truncate back down.
5450       // TODO: We could probably improve this when extracting certain fixed
5451       // from fixed, where we can extract as i8 and shift the correct element
5452       // right to reach the desired subvector?
5453       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5454       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5455       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5456       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5457                         Op.getOperand(1));
5458       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5459       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5460     }
5461   }
5462 
5463   // If the subvector vector is a fixed-length type, we cannot use subregister
5464   // manipulation to simplify the codegen; we don't know which register of a
5465   // LMUL group contains the specific subvector as we only know the minimum
5466   // register size. Therefore we must slide the vector group down the full
5467   // amount.
5468   if (SubVecVT.isFixedLengthVector()) {
5469     // With an index of 0 this is a cast-like subvector, which can be performed
5470     // with subregister operations.
5471     if (OrigIdx == 0)
5472       return Op;
5473     MVT ContainerVT = VecVT;
5474     if (VecVT.isFixedLengthVector()) {
5475       ContainerVT = getContainerForFixedLengthVector(VecVT);
5476       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5477     }
5478     SDValue Mask =
5479         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5480     // Set the vector length to only the number of elements we care about. This
5481     // avoids sliding down elements we're going to discard straight away.
5482     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5483     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5484     SDValue Slidedown =
5485         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5486                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5487     // Now we can use a cast-like subvector extract to get the result.
5488     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5489                             DAG.getConstant(0, DL, XLenVT));
5490     return DAG.getBitcast(Op.getValueType(), Slidedown);
5491   }
5492 
5493   unsigned SubRegIdx, RemIdx;
5494   std::tie(SubRegIdx, RemIdx) =
5495       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5496           VecVT, SubVecVT, OrigIdx, TRI);
5497 
5498   // If the Idx has been completely eliminated then this is a subvector extract
5499   // which naturally aligns to a vector register. These can easily be handled
5500   // using subregister manipulation.
5501   if (RemIdx == 0)
5502     return Op;
5503 
5504   // Else we must shift our vector register directly to extract the subvector.
5505   // Do this using VSLIDEDOWN.
5506 
5507   // If the vector type is an LMUL-group type, extract a subvector equal to the
5508   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5509   // instruction.
5510   MVT InterSubVT = VecVT;
5511   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5512     InterSubVT = getLMUL1VT(VecVT);
5513     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5514                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5515   }
5516 
5517   // Slide this vector register down by the desired number of elements in order
5518   // to place the desired subvector starting at element 0.
5519   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5520   // For scalable vectors this must be further multiplied by vscale.
5521   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5522 
5523   SDValue Mask, VL;
5524   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5525   SDValue Slidedown =
5526       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5527                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5528 
5529   // Now the vector is in the right position, extract our final subvector. This
5530   // should resolve to a COPY.
5531   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5532                           DAG.getConstant(0, DL, XLenVT));
5533 
5534   // We might have bitcast from a mask type: cast back to the original type if
5535   // required.
5536   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5537 }
5538 
5539 // Lower step_vector to the vid instruction. Any non-identity step value must
5540 // be accounted for my manual expansion.
5541 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5542                                               SelectionDAG &DAG) const {
5543   SDLoc DL(Op);
5544   MVT VT = Op.getSimpleValueType();
5545   MVT XLenVT = Subtarget.getXLenVT();
5546   SDValue Mask, VL;
5547   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5548   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5549   uint64_t StepValImm = Op.getConstantOperandVal(0);
5550   if (StepValImm != 1) {
5551     if (isPowerOf2_64(StepValImm)) {
5552       SDValue StepVal =
5553           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5554                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5555       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5556     } else {
5557       SDValue StepVal = lowerScalarSplat(
5558           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5559           VL, VT, DL, DAG, Subtarget);
5560       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5561     }
5562   }
5563   return StepVec;
5564 }
5565 
5566 // Implement vector_reverse using vrgather.vv with indices determined by
5567 // subtracting the id of each element from (VLMAX-1). This will convert
5568 // the indices like so:
5569 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5570 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5571 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5572                                                  SelectionDAG &DAG) const {
5573   SDLoc DL(Op);
5574   MVT VecVT = Op.getSimpleValueType();
5575   unsigned EltSize = VecVT.getScalarSizeInBits();
5576   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5577 
5578   unsigned MaxVLMAX = 0;
5579   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5580   if (VectorBitsMax != 0)
5581     MaxVLMAX =
5582         RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5583 
5584   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5585   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5586 
5587   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5588   // to use vrgatherei16.vv.
5589   // TODO: It's also possible to use vrgatherei16.vv for other types to
5590   // decrease register width for the index calculation.
5591   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5592     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5593     // Reverse each half, then reassemble them in reverse order.
5594     // NOTE: It's also possible that after splitting that VLMAX no longer
5595     // requires vrgatherei16.vv.
5596     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5597       SDValue Lo, Hi;
5598       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5599       EVT LoVT, HiVT;
5600       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5601       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5602       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5603       // Reassemble the low and high pieces reversed.
5604       // FIXME: This is a CONCAT_VECTORS.
5605       SDValue Res =
5606           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5607                       DAG.getIntPtrConstant(0, DL));
5608       return DAG.getNode(
5609           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5610           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5611     }
5612 
5613     // Just promote the int type to i16 which will double the LMUL.
5614     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5615     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5616   }
5617 
5618   MVT XLenVT = Subtarget.getXLenVT();
5619   SDValue Mask, VL;
5620   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5621 
5622   // Calculate VLMAX-1 for the desired SEW.
5623   unsigned MinElts = VecVT.getVectorMinNumElements();
5624   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5625                               DAG.getConstant(MinElts, DL, XLenVT));
5626   SDValue VLMinus1 =
5627       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5628 
5629   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5630   bool IsRV32E64 =
5631       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5632   SDValue SplatVL;
5633   if (!IsRV32E64)
5634     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5635   else
5636     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5637                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5638 
5639   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5640   SDValue Indices =
5641       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5642 
5643   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5644 }
5645 
5646 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5647                                                 SelectionDAG &DAG) const {
5648   SDLoc DL(Op);
5649   SDValue V1 = Op.getOperand(0);
5650   SDValue V2 = Op.getOperand(1);
5651   MVT XLenVT = Subtarget.getXLenVT();
5652   MVT VecVT = Op.getSimpleValueType();
5653 
5654   unsigned MinElts = VecVT.getVectorMinNumElements();
5655   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5656                               DAG.getConstant(MinElts, DL, XLenVT));
5657 
5658   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5659   SDValue DownOffset, UpOffset;
5660   if (ImmValue >= 0) {
5661     // The operand is a TargetConstant, we need to rebuild it as a regular
5662     // constant.
5663     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5664     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5665   } else {
5666     // The operand is a TargetConstant, we need to rebuild it as a regular
5667     // constant rather than negating the original operand.
5668     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5669     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5670   }
5671 
5672   MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5673   SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax);
5674 
5675   SDValue SlideDown =
5676       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5677                   DownOffset, TrueMask, UpOffset);
5678   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5679                      TrueMask,
5680                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5681 }
5682 
5683 SDValue
5684 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5685                                                      SelectionDAG &DAG) const {
5686   SDLoc DL(Op);
5687   auto *Load = cast<LoadSDNode>(Op);
5688 
5689   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5690                                         Load->getMemoryVT(),
5691                                         *Load->getMemOperand()) &&
5692          "Expecting a correctly-aligned load");
5693 
5694   MVT VT = Op.getSimpleValueType();
5695   MVT XLenVT = Subtarget.getXLenVT();
5696   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5697 
5698   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5699 
5700   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5701   SDValue IntID = DAG.getTargetConstant(
5702       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5703   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5704   if (!IsMaskOp)
5705     Ops.push_back(DAG.getUNDEF(ContainerVT));
5706   Ops.push_back(Load->getBasePtr());
5707   Ops.push_back(VL);
5708   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5709   SDValue NewLoad =
5710       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5711                               Load->getMemoryVT(), Load->getMemOperand());
5712 
5713   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5714   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5715 }
5716 
5717 SDValue
5718 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5719                                                       SelectionDAG &DAG) const {
5720   SDLoc DL(Op);
5721   auto *Store = cast<StoreSDNode>(Op);
5722 
5723   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5724                                         Store->getMemoryVT(),
5725                                         *Store->getMemOperand()) &&
5726          "Expecting a correctly-aligned store");
5727 
5728   SDValue StoreVal = Store->getValue();
5729   MVT VT = StoreVal.getSimpleValueType();
5730   MVT XLenVT = Subtarget.getXLenVT();
5731 
5732   // If the size less than a byte, we need to pad with zeros to make a byte.
5733   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5734     VT = MVT::v8i1;
5735     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5736                            DAG.getConstant(0, DL, VT), StoreVal,
5737                            DAG.getIntPtrConstant(0, DL));
5738   }
5739 
5740   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5741 
5742   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5743 
5744   SDValue NewValue =
5745       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5746 
5747   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5748   SDValue IntID = DAG.getTargetConstant(
5749       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5750   return DAG.getMemIntrinsicNode(
5751       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5752       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5753       Store->getMemoryVT(), Store->getMemOperand());
5754 }
5755 
5756 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5757                                              SelectionDAG &DAG) const {
5758   SDLoc DL(Op);
5759   MVT VT = Op.getSimpleValueType();
5760 
5761   const auto *MemSD = cast<MemSDNode>(Op);
5762   EVT MemVT = MemSD->getMemoryVT();
5763   MachineMemOperand *MMO = MemSD->getMemOperand();
5764   SDValue Chain = MemSD->getChain();
5765   SDValue BasePtr = MemSD->getBasePtr();
5766 
5767   SDValue Mask, PassThru, VL;
5768   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5769     Mask = VPLoad->getMask();
5770     PassThru = DAG.getUNDEF(VT);
5771     VL = VPLoad->getVectorLength();
5772   } else {
5773     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5774     Mask = MLoad->getMask();
5775     PassThru = MLoad->getPassThru();
5776   }
5777 
5778   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5779 
5780   MVT XLenVT = Subtarget.getXLenVT();
5781 
5782   MVT ContainerVT = VT;
5783   if (VT.isFixedLengthVector()) {
5784     ContainerVT = getContainerForFixedLengthVector(VT);
5785     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5786     if (!IsUnmasked) {
5787       MVT MaskVT =
5788           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5789       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5790     }
5791   }
5792 
5793   if (!VL)
5794     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5795 
5796   unsigned IntID =
5797       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5798   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5799   if (IsUnmasked)
5800     Ops.push_back(DAG.getUNDEF(ContainerVT));
5801   else
5802     Ops.push_back(PassThru);
5803   Ops.push_back(BasePtr);
5804   if (!IsUnmasked)
5805     Ops.push_back(Mask);
5806   Ops.push_back(VL);
5807   if (!IsUnmasked)
5808     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5809 
5810   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5811 
5812   SDValue Result =
5813       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5814   Chain = Result.getValue(1);
5815 
5816   if (VT.isFixedLengthVector())
5817     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5818 
5819   return DAG.getMergeValues({Result, Chain}, DL);
5820 }
5821 
5822 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5823                                               SelectionDAG &DAG) const {
5824   SDLoc DL(Op);
5825 
5826   const auto *MemSD = cast<MemSDNode>(Op);
5827   EVT MemVT = MemSD->getMemoryVT();
5828   MachineMemOperand *MMO = MemSD->getMemOperand();
5829   SDValue Chain = MemSD->getChain();
5830   SDValue BasePtr = MemSD->getBasePtr();
5831   SDValue Val, Mask, VL;
5832 
5833   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5834     Val = VPStore->getValue();
5835     Mask = VPStore->getMask();
5836     VL = VPStore->getVectorLength();
5837   } else {
5838     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5839     Val = MStore->getValue();
5840     Mask = MStore->getMask();
5841   }
5842 
5843   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5844 
5845   MVT VT = Val.getSimpleValueType();
5846   MVT XLenVT = Subtarget.getXLenVT();
5847 
5848   MVT ContainerVT = VT;
5849   if (VT.isFixedLengthVector()) {
5850     ContainerVT = getContainerForFixedLengthVector(VT);
5851 
5852     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5853     if (!IsUnmasked) {
5854       MVT MaskVT =
5855           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5856       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5857     }
5858   }
5859 
5860   if (!VL)
5861     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5862 
5863   unsigned IntID =
5864       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5865   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5866   Ops.push_back(Val);
5867   Ops.push_back(BasePtr);
5868   if (!IsUnmasked)
5869     Ops.push_back(Mask);
5870   Ops.push_back(VL);
5871 
5872   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5873                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5874 }
5875 
5876 SDValue
5877 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5878                                                       SelectionDAG &DAG) const {
5879   MVT InVT = Op.getOperand(0).getSimpleValueType();
5880   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5881 
5882   MVT VT = Op.getSimpleValueType();
5883 
5884   SDValue Op1 =
5885       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5886   SDValue Op2 =
5887       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5888 
5889   SDLoc DL(Op);
5890   SDValue VL =
5891       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5892 
5893   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5894   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5895 
5896   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5897                             Op.getOperand(2), Mask, VL);
5898 
5899   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5900 }
5901 
5902 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5903     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5904   MVT VT = Op.getSimpleValueType();
5905 
5906   if (VT.getVectorElementType() == MVT::i1)
5907     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5908 
5909   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5910 }
5911 
5912 SDValue
5913 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5914                                                       SelectionDAG &DAG) const {
5915   unsigned Opc;
5916   switch (Op.getOpcode()) {
5917   default: llvm_unreachable("Unexpected opcode!");
5918   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5919   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5920   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5921   }
5922 
5923   return lowerToScalableOp(Op, DAG, Opc);
5924 }
5925 
5926 // Lower vector ABS to smax(X, sub(0, X)).
5927 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5928   SDLoc DL(Op);
5929   MVT VT = Op.getSimpleValueType();
5930   SDValue X = Op.getOperand(0);
5931 
5932   assert(VT.isFixedLengthVector() && "Unexpected type");
5933 
5934   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5935   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5936 
5937   SDValue Mask, VL;
5938   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5939 
5940   SDValue SplatZero = DAG.getNode(
5941       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
5942       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5943   SDValue NegX =
5944       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5945   SDValue Max =
5946       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5947 
5948   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5949 }
5950 
5951 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5952     SDValue Op, SelectionDAG &DAG) const {
5953   SDLoc DL(Op);
5954   MVT VT = Op.getSimpleValueType();
5955   SDValue Mag = Op.getOperand(0);
5956   SDValue Sign = Op.getOperand(1);
5957   assert(Mag.getValueType() == Sign.getValueType() &&
5958          "Can only handle COPYSIGN with matching types.");
5959 
5960   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5961   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5962   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5963 
5964   SDValue Mask, VL;
5965   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5966 
5967   SDValue CopySign =
5968       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5969 
5970   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5971 }
5972 
5973 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5974     SDValue Op, SelectionDAG &DAG) const {
5975   MVT VT = Op.getSimpleValueType();
5976   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5977 
5978   MVT I1ContainerVT =
5979       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5980 
5981   SDValue CC =
5982       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5983   SDValue Op1 =
5984       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5985   SDValue Op2 =
5986       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5987 
5988   SDLoc DL(Op);
5989   SDValue Mask, VL;
5990   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5991 
5992   SDValue Select =
5993       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5994 
5995   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5996 }
5997 
5998 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5999                                                unsigned NewOpc,
6000                                                bool HasMask) const {
6001   MVT VT = Op.getSimpleValueType();
6002   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6003 
6004   // Create list of operands by converting existing ones to scalable types.
6005   SmallVector<SDValue, 6> Ops;
6006   for (const SDValue &V : Op->op_values()) {
6007     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6008 
6009     // Pass through non-vector operands.
6010     if (!V.getValueType().isVector()) {
6011       Ops.push_back(V);
6012       continue;
6013     }
6014 
6015     // "cast" fixed length vector to a scalable vector.
6016     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6017            "Only fixed length vectors are supported!");
6018     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6019   }
6020 
6021   SDLoc DL(Op);
6022   SDValue Mask, VL;
6023   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6024   if (HasMask)
6025     Ops.push_back(Mask);
6026   Ops.push_back(VL);
6027 
6028   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6029   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6030 }
6031 
6032 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6033 // * Operands of each node are assumed to be in the same order.
6034 // * The EVL operand is promoted from i32 to i64 on RV64.
6035 // * Fixed-length vectors are converted to their scalable-vector container
6036 //   types.
6037 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6038                                        unsigned RISCVISDOpc) const {
6039   SDLoc DL(Op);
6040   MVT VT = Op.getSimpleValueType();
6041   SmallVector<SDValue, 4> Ops;
6042 
6043   for (const auto &OpIdx : enumerate(Op->ops())) {
6044     SDValue V = OpIdx.value();
6045     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6046     // Pass through operands which aren't fixed-length vectors.
6047     if (!V.getValueType().isFixedLengthVector()) {
6048       Ops.push_back(V);
6049       continue;
6050     }
6051     // "cast" fixed length vector to a scalable vector.
6052     MVT OpVT = V.getSimpleValueType();
6053     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6054     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6055            "Only fixed length vectors are supported!");
6056     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6057   }
6058 
6059   if (!VT.isFixedLengthVector())
6060     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
6061 
6062   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6063 
6064   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
6065 
6066   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6067 }
6068 
6069 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op,
6070                                               SelectionDAG &DAG) const {
6071   SDLoc DL(Op);
6072   MVT VT = Op.getSimpleValueType();
6073 
6074   SDValue Src = Op.getOperand(0);
6075   // NOTE: Mask is dropped.
6076   SDValue VL = Op.getOperand(2);
6077 
6078   MVT ContainerVT = VT;
6079   if (VT.isFixedLengthVector()) {
6080     ContainerVT = getContainerForFixedLengthVector(VT);
6081     MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6082     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6083   }
6084 
6085   MVT XLenVT = Subtarget.getXLenVT();
6086   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6087   SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6088                                   DAG.getUNDEF(ContainerVT), Zero, VL);
6089 
6090   SDValue SplatValue =
6091       DAG.getConstant(Op.getOpcode() == ISD::VP_ZEXT ? 1 : -1, DL, XLenVT);
6092   SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6093                               DAG.getUNDEF(ContainerVT), SplatValue, VL);
6094 
6095   SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src,
6096                                Splat, ZeroSplat, VL);
6097   if (!VT.isFixedLengthVector())
6098     return Result;
6099   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6100 }
6101 
6102 // Lower Floating-Point/Integer Type-Convert VP SDNodes
6103 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
6104                                                 unsigned RISCVISDOpc) const {
6105   SDLoc DL(Op);
6106 
6107   SDValue Src = Op.getOperand(0);
6108   SDValue Mask = Op.getOperand(1);
6109   SDValue VL = Op.getOperand(2);
6110 
6111   MVT DstVT = Op.getSimpleValueType();
6112   MVT SrcVT = Src.getSimpleValueType();
6113   if (DstVT.isFixedLengthVector()) {
6114     DstVT = getContainerForFixedLengthVector(DstVT);
6115     SrcVT = getContainerForFixedLengthVector(SrcVT);
6116     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6117     MVT MaskVT = MVT::getVectorVT(MVT::i1, DstVT.getVectorElementCount());
6118     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6119   }
6120 
6121   unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL ||
6122                              RISCVISDOpc == RISCVISD::FP_TO_SINT_VL)
6123                                 ? RISCVISD::VSEXT_VL
6124                                 : RISCVISD::VZEXT_VL;
6125 
6126   unsigned DstEltSize = DstVT.getScalarSizeInBits();
6127   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
6128 
6129   SDValue Result;
6130   if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
6131     if (SrcVT.isInteger()) {
6132       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6133 
6134       // Do we need to do any pre-widening before converting?
6135       if (SrcEltSize == 1) {
6136         MVT IntVT = DstVT.changeVectorElementTypeToInteger();
6137         MVT XLenVT = Subtarget.getXLenVT();
6138         SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6139         SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6140                                         DAG.getUNDEF(IntVT), Zero, VL);
6141         SDValue One = DAG.getConstant(
6142             RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
6143         SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6144                                        DAG.getUNDEF(IntVT), One, VL);
6145         Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
6146                           ZeroSplat, VL);
6147       } else if (DstEltSize > (2 * SrcEltSize)) {
6148         // Widen before converting.
6149         MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
6150                                      DstVT.getVectorElementCount());
6151         Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL);
6152       }
6153 
6154       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6155     } else {
6156       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6157              "Wrong input/output vector types");
6158 
6159       // Convert f16 to f32 then convert f32 to i64.
6160       if (DstEltSize > (2 * SrcEltSize)) {
6161         assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6162         MVT InterimFVT =
6163             MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6164         Src =
6165             DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL);
6166       }
6167 
6168       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6169     }
6170   } else { // Narrowing + Conversion
6171     if (SrcVT.isInteger()) {
6172       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6173       // First do a narrowing convert to an FP type half the size, then round
6174       // the FP type to a small FP type if needed.
6175 
6176       MVT InterimFVT = DstVT;
6177       if (SrcEltSize > (2 * DstEltSize)) {
6178         assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
6179         assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6180         InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6181       }
6182 
6183       Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL);
6184 
6185       if (InterimFVT != DstVT) {
6186         Src = Result;
6187         Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL);
6188       }
6189     } else {
6190       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6191              "Wrong input/output vector types");
6192       // First do a narrowing conversion to an integer half the size, then
6193       // truncate if needed.
6194 
6195       if (DstEltSize == 1) {
6196         // First convert to the same size integer, then convert to mask using
6197         // setcc.
6198         assert(SrcEltSize >= 16 && "Unexpected FP type!");
6199         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize),
6200                                           DstVT.getVectorElementCount());
6201         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6202 
6203         // Compare the integer result to 0. The integer should be 0 or 1/-1,
6204         // otherwise the conversion was undefined.
6205         MVT XLenVT = Subtarget.getXLenVT();
6206         SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
6207         SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT,
6208                                 DAG.getUNDEF(InterimIVT), SplatZero);
6209         Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero,
6210                              DAG.getCondCode(ISD::SETNE), Mask, VL);
6211       } else {
6212         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6213                                           DstVT.getVectorElementCount());
6214 
6215         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6216 
6217         while (InterimIVT != DstVT) {
6218           SrcEltSize /= 2;
6219           Src = Result;
6220           InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6221                                         DstVT.getVectorElementCount());
6222           Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
6223                                Src, Mask, VL);
6224         }
6225       }
6226     }
6227   }
6228 
6229   MVT VT = Op.getSimpleValueType();
6230   if (!VT.isFixedLengthVector())
6231     return Result;
6232   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6233 }
6234 
6235 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6236                                             unsigned MaskOpc,
6237                                             unsigned VecOpc) const {
6238   MVT VT = Op.getSimpleValueType();
6239   if (VT.getVectorElementType() != MVT::i1)
6240     return lowerVPOp(Op, DAG, VecOpc);
6241 
6242   // It is safe to drop mask parameter as masked-off elements are undef.
6243   SDValue Op1 = Op->getOperand(0);
6244   SDValue Op2 = Op->getOperand(1);
6245   SDValue VL = Op->getOperand(3);
6246 
6247   MVT ContainerVT = VT;
6248   const bool IsFixed = VT.isFixedLengthVector();
6249   if (IsFixed) {
6250     ContainerVT = getContainerForFixedLengthVector(VT);
6251     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6252     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6253   }
6254 
6255   SDLoc DL(Op);
6256   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6257   if (!IsFixed)
6258     return Val;
6259   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6260 }
6261 
6262 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6263 // matched to a RVV indexed load. The RVV indexed load instructions only
6264 // support the "unsigned unscaled" addressing mode; indices are implicitly
6265 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6266 // signed or scaled indexing is extended to the XLEN value type and scaled
6267 // accordingly.
6268 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6269                                                SelectionDAG &DAG) const {
6270   SDLoc DL(Op);
6271   MVT VT = Op.getSimpleValueType();
6272 
6273   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6274   EVT MemVT = MemSD->getMemoryVT();
6275   MachineMemOperand *MMO = MemSD->getMemOperand();
6276   SDValue Chain = MemSD->getChain();
6277   SDValue BasePtr = MemSD->getBasePtr();
6278 
6279   ISD::LoadExtType LoadExtType;
6280   SDValue Index, Mask, PassThru, VL;
6281 
6282   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6283     Index = VPGN->getIndex();
6284     Mask = VPGN->getMask();
6285     PassThru = DAG.getUNDEF(VT);
6286     VL = VPGN->getVectorLength();
6287     // VP doesn't support extending loads.
6288     LoadExtType = ISD::NON_EXTLOAD;
6289   } else {
6290     // Else it must be a MGATHER.
6291     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6292     Index = MGN->getIndex();
6293     Mask = MGN->getMask();
6294     PassThru = MGN->getPassThru();
6295     LoadExtType = MGN->getExtensionType();
6296   }
6297 
6298   MVT IndexVT = Index.getSimpleValueType();
6299   MVT XLenVT = Subtarget.getXLenVT();
6300 
6301   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6302          "Unexpected VTs!");
6303   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6304   // Targets have to explicitly opt-in for extending vector loads.
6305   assert(LoadExtType == ISD::NON_EXTLOAD &&
6306          "Unexpected extending MGATHER/VP_GATHER");
6307   (void)LoadExtType;
6308 
6309   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6310   // the selection of the masked intrinsics doesn't do this for us.
6311   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6312 
6313   MVT ContainerVT = VT;
6314   if (VT.isFixedLengthVector()) {
6315     // We need to use the larger of the result and index type to determine the
6316     // scalable type to use so we don't increase LMUL for any operand/result.
6317     if (VT.bitsGE(IndexVT)) {
6318       ContainerVT = getContainerForFixedLengthVector(VT);
6319       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6320                                  ContainerVT.getVectorElementCount());
6321     } else {
6322       IndexVT = getContainerForFixedLengthVector(IndexVT);
6323       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
6324                                      IndexVT.getVectorElementCount());
6325     }
6326 
6327     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6328 
6329     if (!IsUnmasked) {
6330       MVT MaskVT =
6331           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6332       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6333       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6334     }
6335   }
6336 
6337   if (!VL)
6338     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6339 
6340   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6341     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6342     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6343                                    VL);
6344     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6345                         TrueMask, VL);
6346   }
6347 
6348   unsigned IntID =
6349       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6350   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6351   if (IsUnmasked)
6352     Ops.push_back(DAG.getUNDEF(ContainerVT));
6353   else
6354     Ops.push_back(PassThru);
6355   Ops.push_back(BasePtr);
6356   Ops.push_back(Index);
6357   if (!IsUnmasked)
6358     Ops.push_back(Mask);
6359   Ops.push_back(VL);
6360   if (!IsUnmasked)
6361     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6362 
6363   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6364   SDValue Result =
6365       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6366   Chain = Result.getValue(1);
6367 
6368   if (VT.isFixedLengthVector())
6369     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6370 
6371   return DAG.getMergeValues({Result, Chain}, DL);
6372 }
6373 
6374 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6375 // matched to a RVV indexed store. The RVV indexed store instructions only
6376 // support the "unsigned unscaled" addressing mode; indices are implicitly
6377 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6378 // signed or scaled indexing is extended to the XLEN value type and scaled
6379 // accordingly.
6380 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6381                                                 SelectionDAG &DAG) const {
6382   SDLoc DL(Op);
6383   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6384   EVT MemVT = MemSD->getMemoryVT();
6385   MachineMemOperand *MMO = MemSD->getMemOperand();
6386   SDValue Chain = MemSD->getChain();
6387   SDValue BasePtr = MemSD->getBasePtr();
6388 
6389   bool IsTruncatingStore = false;
6390   SDValue Index, Mask, Val, VL;
6391 
6392   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6393     Index = VPSN->getIndex();
6394     Mask = VPSN->getMask();
6395     Val = VPSN->getValue();
6396     VL = VPSN->getVectorLength();
6397     // VP doesn't support truncating stores.
6398     IsTruncatingStore = false;
6399   } else {
6400     // Else it must be a MSCATTER.
6401     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6402     Index = MSN->getIndex();
6403     Mask = MSN->getMask();
6404     Val = MSN->getValue();
6405     IsTruncatingStore = MSN->isTruncatingStore();
6406   }
6407 
6408   MVT VT = Val.getSimpleValueType();
6409   MVT IndexVT = Index.getSimpleValueType();
6410   MVT XLenVT = Subtarget.getXLenVT();
6411 
6412   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6413          "Unexpected VTs!");
6414   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6415   // Targets have to explicitly opt-in for extending vector loads and
6416   // truncating vector stores.
6417   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6418   (void)IsTruncatingStore;
6419 
6420   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6421   // the selection of the masked intrinsics doesn't do this for us.
6422   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6423 
6424   MVT ContainerVT = VT;
6425   if (VT.isFixedLengthVector()) {
6426     // We need to use the larger of the value and index type to determine the
6427     // scalable type to use so we don't increase LMUL for any operand/result.
6428     if (VT.bitsGE(IndexVT)) {
6429       ContainerVT = getContainerForFixedLengthVector(VT);
6430       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6431                                  ContainerVT.getVectorElementCount());
6432     } else {
6433       IndexVT = getContainerForFixedLengthVector(IndexVT);
6434       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
6435                                      IndexVT.getVectorElementCount());
6436     }
6437 
6438     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6439     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6440 
6441     if (!IsUnmasked) {
6442       MVT MaskVT =
6443           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6444       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6445     }
6446   }
6447 
6448   if (!VL)
6449     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6450 
6451   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6452     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6453     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6454                                    VL);
6455     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6456                         TrueMask, VL);
6457   }
6458 
6459   unsigned IntID =
6460       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6461   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6462   Ops.push_back(Val);
6463   Ops.push_back(BasePtr);
6464   Ops.push_back(Index);
6465   if (!IsUnmasked)
6466     Ops.push_back(Mask);
6467   Ops.push_back(VL);
6468 
6469   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6470                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6471 }
6472 
6473 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6474                                                SelectionDAG &DAG) const {
6475   const MVT XLenVT = Subtarget.getXLenVT();
6476   SDLoc DL(Op);
6477   SDValue Chain = Op->getOperand(0);
6478   SDValue SysRegNo = DAG.getTargetConstant(
6479       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6480   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6481   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6482 
6483   // Encoding used for rounding mode in RISCV differs from that used in
6484   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6485   // table, which consists of a sequence of 4-bit fields, each representing
6486   // corresponding FLT_ROUNDS mode.
6487   static const int Table =
6488       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6489       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6490       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6491       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6492       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6493 
6494   SDValue Shift =
6495       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6496   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6497                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6498   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6499                                DAG.getConstant(7, DL, XLenVT));
6500 
6501   return DAG.getMergeValues({Masked, Chain}, DL);
6502 }
6503 
6504 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6505                                                SelectionDAG &DAG) const {
6506   const MVT XLenVT = Subtarget.getXLenVT();
6507   SDLoc DL(Op);
6508   SDValue Chain = Op->getOperand(0);
6509   SDValue RMValue = Op->getOperand(1);
6510   SDValue SysRegNo = DAG.getTargetConstant(
6511       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6512 
6513   // Encoding used for rounding mode in RISCV differs from that used in
6514   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6515   // a table, which consists of a sequence of 4-bit fields, each representing
6516   // corresponding RISCV mode.
6517   static const unsigned Table =
6518       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6519       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6520       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6521       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6522       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6523 
6524   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6525                               DAG.getConstant(2, DL, XLenVT));
6526   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6527                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6528   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6529                         DAG.getConstant(0x7, DL, XLenVT));
6530   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6531                      RMValue);
6532 }
6533 
6534 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6535   switch (IntNo) {
6536   default:
6537     llvm_unreachable("Unexpected Intrinsic");
6538   case Intrinsic::riscv_bcompress:
6539     return RISCVISD::BCOMPRESSW;
6540   case Intrinsic::riscv_bdecompress:
6541     return RISCVISD::BDECOMPRESSW;
6542   case Intrinsic::riscv_bfp:
6543     return RISCVISD::BFPW;
6544   case Intrinsic::riscv_fsl:
6545     return RISCVISD::FSLW;
6546   case Intrinsic::riscv_fsr:
6547     return RISCVISD::FSRW;
6548   }
6549 }
6550 
6551 // Converts the given intrinsic to a i64 operation with any extension.
6552 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6553                                          unsigned IntNo) {
6554   SDLoc DL(N);
6555   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6556   // Deal with the Instruction Operands
6557   SmallVector<SDValue, 3> NewOps;
6558   for (SDValue Op : drop_begin(N->ops()))
6559     // Promote the operand to i64 type
6560     NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op));
6561   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps);
6562   // ReplaceNodeResults requires we maintain the same type for the return value.
6563   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6564 }
6565 
6566 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6567 // form of the given Opcode.
6568 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6569   switch (Opcode) {
6570   default:
6571     llvm_unreachable("Unexpected opcode");
6572   case ISD::SHL:
6573     return RISCVISD::SLLW;
6574   case ISD::SRA:
6575     return RISCVISD::SRAW;
6576   case ISD::SRL:
6577     return RISCVISD::SRLW;
6578   case ISD::SDIV:
6579     return RISCVISD::DIVW;
6580   case ISD::UDIV:
6581     return RISCVISD::DIVUW;
6582   case ISD::UREM:
6583     return RISCVISD::REMUW;
6584   case ISD::ROTL:
6585     return RISCVISD::ROLW;
6586   case ISD::ROTR:
6587     return RISCVISD::RORW;
6588   }
6589 }
6590 
6591 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6592 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6593 // otherwise be promoted to i64, making it difficult to select the
6594 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6595 // type i8/i16/i32 is lost.
6596 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6597                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6598   SDLoc DL(N);
6599   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6600   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6601   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6602   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6603   // ReplaceNodeResults requires we maintain the same type for the return value.
6604   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6605 }
6606 
6607 // Converts the given 32-bit operation to a i64 operation with signed extension
6608 // semantic to reduce the signed extension instructions.
6609 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6610   SDLoc DL(N);
6611   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6612   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6613   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6614   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6615                                DAG.getValueType(MVT::i32));
6616   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6617 }
6618 
6619 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6620                                              SmallVectorImpl<SDValue> &Results,
6621                                              SelectionDAG &DAG) const {
6622   SDLoc DL(N);
6623   switch (N->getOpcode()) {
6624   default:
6625     llvm_unreachable("Don't know how to custom type legalize this operation!");
6626   case ISD::STRICT_FP_TO_SINT:
6627   case ISD::STRICT_FP_TO_UINT:
6628   case ISD::FP_TO_SINT:
6629   case ISD::FP_TO_UINT: {
6630     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6631            "Unexpected custom legalisation");
6632     bool IsStrict = N->isStrictFPOpcode();
6633     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6634                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6635     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6636     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6637         TargetLowering::TypeSoftenFloat) {
6638       if (!isTypeLegal(Op0.getValueType()))
6639         return;
6640       if (IsStrict) {
6641         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6642                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6643         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6644         SDValue Res = DAG.getNode(
6645             Opc, DL, VTs, N->getOperand(0), Op0,
6646             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6647         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6648         Results.push_back(Res.getValue(1));
6649         return;
6650       }
6651       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6652       SDValue Res =
6653           DAG.getNode(Opc, DL, MVT::i64, Op0,
6654                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6655       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6656       return;
6657     }
6658     // If the FP type needs to be softened, emit a library call using the 'si'
6659     // version. If we left it to default legalization we'd end up with 'di'. If
6660     // the FP type doesn't need to be softened just let generic type
6661     // legalization promote the result type.
6662     RTLIB::Libcall LC;
6663     if (IsSigned)
6664       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6665     else
6666       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6667     MakeLibCallOptions CallOptions;
6668     EVT OpVT = Op0.getValueType();
6669     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6670     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6671     SDValue Result;
6672     std::tie(Result, Chain) =
6673         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6674     Results.push_back(Result);
6675     if (IsStrict)
6676       Results.push_back(Chain);
6677     break;
6678   }
6679   case ISD::READCYCLECOUNTER: {
6680     assert(!Subtarget.is64Bit() &&
6681            "READCYCLECOUNTER only has custom type legalization on riscv32");
6682 
6683     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6684     SDValue RCW =
6685         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6686 
6687     Results.push_back(
6688         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6689     Results.push_back(RCW.getValue(2));
6690     break;
6691   }
6692   case ISD::MUL: {
6693     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6694     unsigned XLen = Subtarget.getXLen();
6695     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6696     if (Size > XLen) {
6697       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6698       SDValue LHS = N->getOperand(0);
6699       SDValue RHS = N->getOperand(1);
6700       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6701 
6702       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6703       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6704       // We need exactly one side to be unsigned.
6705       if (LHSIsU == RHSIsU)
6706         return;
6707 
6708       auto MakeMULPair = [&](SDValue S, SDValue U) {
6709         MVT XLenVT = Subtarget.getXLenVT();
6710         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6711         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6712         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6713         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6714         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6715       };
6716 
6717       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6718       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6719 
6720       // The other operand should be signed, but still prefer MULH when
6721       // possible.
6722       if (RHSIsU && LHSIsS && !RHSIsS)
6723         Results.push_back(MakeMULPair(LHS, RHS));
6724       else if (LHSIsU && RHSIsS && !LHSIsS)
6725         Results.push_back(MakeMULPair(RHS, LHS));
6726 
6727       return;
6728     }
6729     LLVM_FALLTHROUGH;
6730   }
6731   case ISD::ADD:
6732   case ISD::SUB:
6733     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6734            "Unexpected custom legalisation");
6735     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6736     break;
6737   case ISD::SHL:
6738   case ISD::SRA:
6739   case ISD::SRL:
6740     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6741            "Unexpected custom legalisation");
6742     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6743       Results.push_back(customLegalizeToWOp(N, DAG));
6744       break;
6745     }
6746 
6747     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6748     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6749     // shift amount.
6750     if (N->getOpcode() == ISD::SHL) {
6751       SDLoc DL(N);
6752       SDValue NewOp0 =
6753           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6754       SDValue NewOp1 =
6755           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6756       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6757       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6758                                    DAG.getValueType(MVT::i32));
6759       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6760     }
6761 
6762     break;
6763   case ISD::ROTL:
6764   case ISD::ROTR:
6765     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6766            "Unexpected custom legalisation");
6767     Results.push_back(customLegalizeToWOp(N, DAG));
6768     break;
6769   case ISD::CTTZ:
6770   case ISD::CTTZ_ZERO_UNDEF:
6771   case ISD::CTLZ:
6772   case ISD::CTLZ_ZERO_UNDEF: {
6773     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6774            "Unexpected custom legalisation");
6775 
6776     SDValue NewOp0 =
6777         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6778     bool IsCTZ =
6779         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6780     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6781     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6782     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6783     return;
6784   }
6785   case ISD::SDIV:
6786   case ISD::UDIV:
6787   case ISD::UREM: {
6788     MVT VT = N->getSimpleValueType(0);
6789     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6790            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6791            "Unexpected custom legalisation");
6792     // Don't promote division/remainder by constant since we should expand those
6793     // to multiply by magic constant.
6794     // FIXME: What if the expansion is disabled for minsize.
6795     if (N->getOperand(1).getOpcode() == ISD::Constant)
6796       return;
6797 
6798     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6799     // the upper 32 bits. For other types we need to sign or zero extend
6800     // based on the opcode.
6801     unsigned ExtOpc = ISD::ANY_EXTEND;
6802     if (VT != MVT::i32)
6803       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6804                                            : ISD::ZERO_EXTEND;
6805 
6806     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6807     break;
6808   }
6809   case ISD::UADDO:
6810   case ISD::USUBO: {
6811     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6812            "Unexpected custom legalisation");
6813     bool IsAdd = N->getOpcode() == ISD::UADDO;
6814     // Create an ADDW or SUBW.
6815     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6816     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6817     SDValue Res =
6818         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6819     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6820                       DAG.getValueType(MVT::i32));
6821 
6822     SDValue Overflow;
6823     if (IsAdd && isOneConstant(RHS)) {
6824       // Special case uaddo X, 1 overflowed if the addition result is 0.
6825       // FIXME: We can do this for any constant RHS by using (X + C) < C.
6826       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res,
6827                               DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ);
6828     } else {
6829       // Sign extend the LHS and perform an unsigned compare with the ADDW
6830       // result. Since the inputs are sign extended from i32, this is equivalent
6831       // to comparing the lower 32 bits.
6832       LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6833       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6834                               IsAdd ? ISD::SETULT : ISD::SETUGT);
6835     }
6836 
6837     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6838     Results.push_back(Overflow);
6839     return;
6840   }
6841   case ISD::UADDSAT:
6842   case ISD::USUBSAT: {
6843     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6844            "Unexpected custom legalisation");
6845     if (Subtarget.hasStdExtZbb()) {
6846       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6847       // sign extend allows overflow of the lower 32 bits to be detected on
6848       // the promoted size.
6849       SDValue LHS =
6850           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6851       SDValue RHS =
6852           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6853       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6854       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6855       return;
6856     }
6857 
6858     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6859     // promotion for UADDO/USUBO.
6860     Results.push_back(expandAddSubSat(N, DAG));
6861     return;
6862   }
6863   case ISD::ABS: {
6864     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6865            "Unexpected custom legalisation");
6866           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6867 
6868     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
6869 
6870     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6871 
6872     // Freeze the source so we can increase it's use count.
6873     Src = DAG.getFreeze(Src);
6874 
6875     // Copy sign bit to all bits using the sraiw pattern.
6876     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
6877                                    DAG.getValueType(MVT::i32));
6878     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
6879                            DAG.getConstant(31, DL, MVT::i64));
6880 
6881     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
6882     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
6883 
6884     // NOTE: The result is only required to be anyextended, but sext is
6885     // consistent with type legalization of sub.
6886     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
6887                          DAG.getValueType(MVT::i32));
6888     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6889     return;
6890   }
6891   case ISD::BITCAST: {
6892     EVT VT = N->getValueType(0);
6893     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6894     SDValue Op0 = N->getOperand(0);
6895     EVT Op0VT = Op0.getValueType();
6896     MVT XLenVT = Subtarget.getXLenVT();
6897     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6898       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6899       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6900     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6901                Subtarget.hasStdExtF()) {
6902       SDValue FPConv =
6903           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6904       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6905     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6906                isTypeLegal(Op0VT)) {
6907       // Custom-legalize bitcasts from fixed-length vector types to illegal
6908       // scalar types in order to improve codegen. Bitcast the vector to a
6909       // one-element vector type whose element type is the same as the result
6910       // type, and extract the first element.
6911       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6912       if (isTypeLegal(BVT)) {
6913         SDValue BVec = DAG.getBitcast(BVT, Op0);
6914         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6915                                       DAG.getConstant(0, DL, XLenVT)));
6916       }
6917     }
6918     break;
6919   }
6920   case RISCVISD::GREV:
6921   case RISCVISD::GORC:
6922   case RISCVISD::SHFL: {
6923     MVT VT = N->getSimpleValueType(0);
6924     MVT XLenVT = Subtarget.getXLenVT();
6925     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
6926            "Unexpected custom legalisation");
6927     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6928     assert((Subtarget.hasStdExtZbp() ||
6929             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
6930              N->getConstantOperandVal(1) == 7)) &&
6931            "Unexpected extension");
6932     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6933     SDValue NewOp1 =
6934         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
6935     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
6936     // ReplaceNodeResults requires we maintain the same type for the return
6937     // value.
6938     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
6939     break;
6940   }
6941   case ISD::BSWAP:
6942   case ISD::BITREVERSE: {
6943     MVT VT = N->getSimpleValueType(0);
6944     MVT XLenVT = Subtarget.getXLenVT();
6945     assert((VT == MVT::i8 || VT == MVT::i16 ||
6946             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6947            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6948     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6949     unsigned Imm = VT.getSizeInBits() - 1;
6950     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6951     if (N->getOpcode() == ISD::BSWAP)
6952       Imm &= ~0x7U;
6953     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
6954                                 DAG.getConstant(Imm, DL, XLenVT));
6955     // ReplaceNodeResults requires we maintain the same type for the return
6956     // value.
6957     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6958     break;
6959   }
6960   case ISD::FSHL:
6961   case ISD::FSHR: {
6962     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6963            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6964     SDValue NewOp0 =
6965         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6966     SDValue NewOp1 =
6967         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6968     SDValue NewShAmt =
6969         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6970     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6971     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
6972     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
6973                            DAG.getConstant(0x1f, DL, MVT::i64));
6974     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
6975     // instruction use different orders. fshl will return its first operand for
6976     // shift of zero, fshr will return its second operand. fsl and fsr both
6977     // return rs1 so the ISD nodes need to have different operand orders.
6978     // Shift amount is in rs2.
6979     unsigned Opc = RISCVISD::FSLW;
6980     if (N->getOpcode() == ISD::FSHR) {
6981       std::swap(NewOp0, NewOp1);
6982       Opc = RISCVISD::FSRW;
6983     }
6984     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
6985     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6986     break;
6987   }
6988   case ISD::EXTRACT_VECTOR_ELT: {
6989     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6990     // type is illegal (currently only vXi64 RV32).
6991     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6992     // transferred to the destination register. We issue two of these from the
6993     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6994     // first element.
6995     SDValue Vec = N->getOperand(0);
6996     SDValue Idx = N->getOperand(1);
6997 
6998     // The vector type hasn't been legalized yet so we can't issue target
6999     // specific nodes if it needs legalization.
7000     // FIXME: We would manually legalize if it's important.
7001     if (!isTypeLegal(Vec.getValueType()))
7002       return;
7003 
7004     MVT VecVT = Vec.getSimpleValueType();
7005 
7006     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7007            VecVT.getVectorElementType() == MVT::i64 &&
7008            "Unexpected EXTRACT_VECTOR_ELT legalization");
7009 
7010     // If this is a fixed vector, we need to convert it to a scalable vector.
7011     MVT ContainerVT = VecVT;
7012     if (VecVT.isFixedLengthVector()) {
7013       ContainerVT = getContainerForFixedLengthVector(VecVT);
7014       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7015     }
7016 
7017     MVT XLenVT = Subtarget.getXLenVT();
7018 
7019     // Use a VL of 1 to avoid processing more elements than we need.
7020     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
7021     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7022     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7023 
7024     // Unless the index is known to be 0, we must slide the vector down to get
7025     // the desired element into index 0.
7026     if (!isNullConstant(Idx)) {
7027       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7028                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7029     }
7030 
7031     // Extract the lower XLEN bits of the correct vector element.
7032     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7033 
7034     // To extract the upper XLEN bits of the vector element, shift the first
7035     // element right by 32 bits and re-extract the lower XLEN bits.
7036     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7037                                      DAG.getUNDEF(ContainerVT),
7038                                      DAG.getConstant(32, DL, XLenVT), VL);
7039     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7040                                  ThirtyTwoV, Mask, VL);
7041 
7042     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7043 
7044     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7045     break;
7046   }
7047   case ISD::INTRINSIC_WO_CHAIN: {
7048     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7049     switch (IntNo) {
7050     default:
7051       llvm_unreachable(
7052           "Don't know how to custom type legalize this intrinsic!");
7053     case Intrinsic::riscv_grev:
7054     case Intrinsic::riscv_gorc: {
7055       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7056              "Unexpected custom legalisation");
7057       SDValue NewOp1 =
7058           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7059       SDValue NewOp2 =
7060           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7061       unsigned Opc =
7062           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7063       // If the control is a constant, promote the node by clearing any extra
7064       // bits bits in the control. isel will form greviw/gorciw if the result is
7065       // sign extended.
7066       if (isa<ConstantSDNode>(NewOp2)) {
7067         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7068                              DAG.getConstant(0x1f, DL, MVT::i64));
7069         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7070       }
7071       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7072       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7073       break;
7074     }
7075     case Intrinsic::riscv_bcompress:
7076     case Intrinsic::riscv_bdecompress:
7077     case Intrinsic::riscv_bfp:
7078     case Intrinsic::riscv_fsl:
7079     case Intrinsic::riscv_fsr: {
7080       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7081              "Unexpected custom legalisation");
7082       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7083       break;
7084     }
7085     case Intrinsic::riscv_orc_b: {
7086       // Lower to the GORCI encoding for orc.b with the operand extended.
7087       SDValue NewOp =
7088           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7089       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7090                                 DAG.getConstant(7, DL, MVT::i64));
7091       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7092       return;
7093     }
7094     case Intrinsic::riscv_shfl:
7095     case Intrinsic::riscv_unshfl: {
7096       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7097              "Unexpected custom legalisation");
7098       SDValue NewOp1 =
7099           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7100       SDValue NewOp2 =
7101           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7102       unsigned Opc =
7103           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7104       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7105       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7106       // will be shuffled the same way as the lower 32 bit half, but the two
7107       // halves won't cross.
7108       if (isa<ConstantSDNode>(NewOp2)) {
7109         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7110                              DAG.getConstant(0xf, DL, MVT::i64));
7111         Opc =
7112             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7113       }
7114       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7115       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7116       break;
7117     }
7118     case Intrinsic::riscv_vmv_x_s: {
7119       EVT VT = N->getValueType(0);
7120       MVT XLenVT = Subtarget.getXLenVT();
7121       if (VT.bitsLT(XLenVT)) {
7122         // Simple case just extract using vmv.x.s and truncate.
7123         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7124                                       Subtarget.getXLenVT(), N->getOperand(1));
7125         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7126         return;
7127       }
7128 
7129       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7130              "Unexpected custom legalization");
7131 
7132       // We need to do the move in two steps.
7133       SDValue Vec = N->getOperand(1);
7134       MVT VecVT = Vec.getSimpleValueType();
7135 
7136       // First extract the lower XLEN bits of the element.
7137       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7138 
7139       // To extract the upper XLEN bits of the vector element, shift the first
7140       // element right by 32 bits and re-extract the lower XLEN bits.
7141       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7142       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7143       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7144       SDValue ThirtyTwoV =
7145           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7146                       DAG.getConstant(32, DL, XLenVT), VL);
7147       SDValue LShr32 =
7148           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7149       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7150 
7151       Results.push_back(
7152           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7153       break;
7154     }
7155     }
7156     break;
7157   }
7158   case ISD::VECREDUCE_ADD:
7159   case ISD::VECREDUCE_AND:
7160   case ISD::VECREDUCE_OR:
7161   case ISD::VECREDUCE_XOR:
7162   case ISD::VECREDUCE_SMAX:
7163   case ISD::VECREDUCE_UMAX:
7164   case ISD::VECREDUCE_SMIN:
7165   case ISD::VECREDUCE_UMIN:
7166     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7167       Results.push_back(V);
7168     break;
7169   case ISD::VP_REDUCE_ADD:
7170   case ISD::VP_REDUCE_AND:
7171   case ISD::VP_REDUCE_OR:
7172   case ISD::VP_REDUCE_XOR:
7173   case ISD::VP_REDUCE_SMAX:
7174   case ISD::VP_REDUCE_UMAX:
7175   case ISD::VP_REDUCE_SMIN:
7176   case ISD::VP_REDUCE_UMIN:
7177     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7178       Results.push_back(V);
7179     break;
7180   case ISD::FLT_ROUNDS_: {
7181     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7182     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7183     Results.push_back(Res.getValue(0));
7184     Results.push_back(Res.getValue(1));
7185     break;
7186   }
7187   }
7188 }
7189 
7190 // A structure to hold one of the bit-manipulation patterns below. Together, a
7191 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7192 //   (or (and (shl x, 1), 0xAAAAAAAA),
7193 //       (and (srl x, 1), 0x55555555))
7194 struct RISCVBitmanipPat {
7195   SDValue Op;
7196   unsigned ShAmt;
7197   bool IsSHL;
7198 
7199   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7200     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7201   }
7202 };
7203 
7204 // Matches patterns of the form
7205 //   (and (shl x, C2), (C1 << C2))
7206 //   (and (srl x, C2), C1)
7207 //   (shl (and x, C1), C2)
7208 //   (srl (and x, (C1 << C2)), C2)
7209 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7210 // The expected masks for each shift amount are specified in BitmanipMasks where
7211 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7212 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7213 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7214 // XLen is 64.
7215 static Optional<RISCVBitmanipPat>
7216 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7217   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7218          "Unexpected number of masks");
7219   Optional<uint64_t> Mask;
7220   // Optionally consume a mask around the shift operation.
7221   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7222     Mask = Op.getConstantOperandVal(1);
7223     Op = Op.getOperand(0);
7224   }
7225   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7226     return None;
7227   bool IsSHL = Op.getOpcode() == ISD::SHL;
7228 
7229   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7230     return None;
7231   uint64_t ShAmt = Op.getConstantOperandVal(1);
7232 
7233   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7234   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7235     return None;
7236   // If we don't have enough masks for 64 bit, then we must be trying to
7237   // match SHFL so we're only allowed to shift 1/4 of the width.
7238   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7239     return None;
7240 
7241   SDValue Src = Op.getOperand(0);
7242 
7243   // The expected mask is shifted left when the AND is found around SHL
7244   // patterns.
7245   //   ((x >> 1) & 0x55555555)
7246   //   ((x << 1) & 0xAAAAAAAA)
7247   bool SHLExpMask = IsSHL;
7248 
7249   if (!Mask) {
7250     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7251     // the mask is all ones: consume that now.
7252     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7253       Mask = Src.getConstantOperandVal(1);
7254       Src = Src.getOperand(0);
7255       // The expected mask is now in fact shifted left for SRL, so reverse the
7256       // decision.
7257       //   ((x & 0xAAAAAAAA) >> 1)
7258       //   ((x & 0x55555555) << 1)
7259       SHLExpMask = !SHLExpMask;
7260     } else {
7261       // Use a default shifted mask of all-ones if there's no AND, truncated
7262       // down to the expected width. This simplifies the logic later on.
7263       Mask = maskTrailingOnes<uint64_t>(Width);
7264       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7265     }
7266   }
7267 
7268   unsigned MaskIdx = Log2_32(ShAmt);
7269   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7270 
7271   if (SHLExpMask)
7272     ExpMask <<= ShAmt;
7273 
7274   if (Mask != ExpMask)
7275     return None;
7276 
7277   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7278 }
7279 
7280 // Matches any of the following bit-manipulation patterns:
7281 //   (and (shl x, 1), (0x55555555 << 1))
7282 //   (and (srl x, 1), 0x55555555)
7283 //   (shl (and x, 0x55555555), 1)
7284 //   (srl (and x, (0x55555555 << 1)), 1)
7285 // where the shift amount and mask may vary thus:
7286 //   [1]  = 0x55555555 / 0xAAAAAAAA
7287 //   [2]  = 0x33333333 / 0xCCCCCCCC
7288 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7289 //   [8]  = 0x00FF00FF / 0xFF00FF00
7290 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7291 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7292 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7293   // These are the unshifted masks which we use to match bit-manipulation
7294   // patterns. They may be shifted left in certain circumstances.
7295   static const uint64_t BitmanipMasks[] = {
7296       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7297       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7298 
7299   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7300 }
7301 
7302 // Match the following pattern as a GREVI(W) operation
7303 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7304 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7305                                const RISCVSubtarget &Subtarget) {
7306   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7307   EVT VT = Op.getValueType();
7308 
7309   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7310     auto LHS = matchGREVIPat(Op.getOperand(0));
7311     auto RHS = matchGREVIPat(Op.getOperand(1));
7312     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7313       SDLoc DL(Op);
7314       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7315                          DAG.getConstant(LHS->ShAmt, DL, VT));
7316     }
7317   }
7318   return SDValue();
7319 }
7320 
7321 // Matches any the following pattern as a GORCI(W) operation
7322 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7323 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7324 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7325 // Note that with the variant of 3.,
7326 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7327 // the inner pattern will first be matched as GREVI and then the outer
7328 // pattern will be matched to GORC via the first rule above.
7329 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7330 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7331                                const RISCVSubtarget &Subtarget) {
7332   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7333   EVT VT = Op.getValueType();
7334 
7335   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7336     SDLoc DL(Op);
7337     SDValue Op0 = Op.getOperand(0);
7338     SDValue Op1 = Op.getOperand(1);
7339 
7340     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7341       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7342           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7343           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7344         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7345       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7346       if ((Reverse.getOpcode() == ISD::ROTL ||
7347            Reverse.getOpcode() == ISD::ROTR) &&
7348           Reverse.getOperand(0) == X &&
7349           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7350         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7351         if (RotAmt == (VT.getSizeInBits() / 2))
7352           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7353                              DAG.getConstant(RotAmt, DL, VT));
7354       }
7355       return SDValue();
7356     };
7357 
7358     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7359     if (SDValue V = MatchOROfReverse(Op0, Op1))
7360       return V;
7361     if (SDValue V = MatchOROfReverse(Op1, Op0))
7362       return V;
7363 
7364     // OR is commutable so canonicalize its OR operand to the left
7365     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7366       std::swap(Op0, Op1);
7367     if (Op0.getOpcode() != ISD::OR)
7368       return SDValue();
7369     SDValue OrOp0 = Op0.getOperand(0);
7370     SDValue OrOp1 = Op0.getOperand(1);
7371     auto LHS = matchGREVIPat(OrOp0);
7372     // OR is commutable so swap the operands and try again: x might have been
7373     // on the left
7374     if (!LHS) {
7375       std::swap(OrOp0, OrOp1);
7376       LHS = matchGREVIPat(OrOp0);
7377     }
7378     auto RHS = matchGREVIPat(Op1);
7379     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7380       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7381                          DAG.getConstant(LHS->ShAmt, DL, VT));
7382     }
7383   }
7384   return SDValue();
7385 }
7386 
7387 // Matches any of the following bit-manipulation patterns:
7388 //   (and (shl x, 1), (0x22222222 << 1))
7389 //   (and (srl x, 1), 0x22222222)
7390 //   (shl (and x, 0x22222222), 1)
7391 //   (srl (and x, (0x22222222 << 1)), 1)
7392 // where the shift amount and mask may vary thus:
7393 //   [1]  = 0x22222222 / 0x44444444
7394 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7395 //   [4]  = 0x00F000F0 / 0x0F000F00
7396 //   [8]  = 0x0000FF00 / 0x00FF0000
7397 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7398 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7399   // These are the unshifted masks which we use to match bit-manipulation
7400   // patterns. They may be shifted left in certain circumstances.
7401   static const uint64_t BitmanipMasks[] = {
7402       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7403       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7404 
7405   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7406 }
7407 
7408 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7409 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7410                                const RISCVSubtarget &Subtarget) {
7411   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7412   EVT VT = Op.getValueType();
7413 
7414   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7415     return SDValue();
7416 
7417   SDValue Op0 = Op.getOperand(0);
7418   SDValue Op1 = Op.getOperand(1);
7419 
7420   // Or is commutable so canonicalize the second OR to the LHS.
7421   if (Op0.getOpcode() != ISD::OR)
7422     std::swap(Op0, Op1);
7423   if (Op0.getOpcode() != ISD::OR)
7424     return SDValue();
7425 
7426   // We found an inner OR, so our operands are the operands of the inner OR
7427   // and the other operand of the outer OR.
7428   SDValue A = Op0.getOperand(0);
7429   SDValue B = Op0.getOperand(1);
7430   SDValue C = Op1;
7431 
7432   auto Match1 = matchSHFLPat(A);
7433   auto Match2 = matchSHFLPat(B);
7434 
7435   // If neither matched, we failed.
7436   if (!Match1 && !Match2)
7437     return SDValue();
7438 
7439   // We had at least one match. if one failed, try the remaining C operand.
7440   if (!Match1) {
7441     std::swap(A, C);
7442     Match1 = matchSHFLPat(A);
7443     if (!Match1)
7444       return SDValue();
7445   } else if (!Match2) {
7446     std::swap(B, C);
7447     Match2 = matchSHFLPat(B);
7448     if (!Match2)
7449       return SDValue();
7450   }
7451   assert(Match1 && Match2);
7452 
7453   // Make sure our matches pair up.
7454   if (!Match1->formsPairWith(*Match2))
7455     return SDValue();
7456 
7457   // All the remains is to make sure C is an AND with the same input, that masks
7458   // out the bits that are being shuffled.
7459   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7460       C.getOperand(0) != Match1->Op)
7461     return SDValue();
7462 
7463   uint64_t Mask = C.getConstantOperandVal(1);
7464 
7465   static const uint64_t BitmanipMasks[] = {
7466       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7467       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7468   };
7469 
7470   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7471   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7472   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7473 
7474   if (Mask != ExpMask)
7475     return SDValue();
7476 
7477   SDLoc DL(Op);
7478   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7479                      DAG.getConstant(Match1->ShAmt, DL, VT));
7480 }
7481 
7482 // Optimize (add (shl x, c0), (shl y, c1)) ->
7483 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7484 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7485                                   const RISCVSubtarget &Subtarget) {
7486   // Perform this optimization only in the zba extension.
7487   if (!Subtarget.hasStdExtZba())
7488     return SDValue();
7489 
7490   // Skip for vector types and larger types.
7491   EVT VT = N->getValueType(0);
7492   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7493     return SDValue();
7494 
7495   // The two operand nodes must be SHL and have no other use.
7496   SDValue N0 = N->getOperand(0);
7497   SDValue N1 = N->getOperand(1);
7498   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7499       !N0->hasOneUse() || !N1->hasOneUse())
7500     return SDValue();
7501 
7502   // Check c0 and c1.
7503   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7504   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7505   if (!N0C || !N1C)
7506     return SDValue();
7507   int64_t C0 = N0C->getSExtValue();
7508   int64_t C1 = N1C->getSExtValue();
7509   if (C0 <= 0 || C1 <= 0)
7510     return SDValue();
7511 
7512   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7513   int64_t Bits = std::min(C0, C1);
7514   int64_t Diff = std::abs(C0 - C1);
7515   if (Diff != 1 && Diff != 2 && Diff != 3)
7516     return SDValue();
7517 
7518   // Build nodes.
7519   SDLoc DL(N);
7520   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7521   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7522   SDValue NA0 =
7523       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7524   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7525   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7526 }
7527 
7528 // Combine
7529 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7530 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7531 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7532 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7533 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7534 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7535 // The grev patterns represents BSWAP.
7536 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7537 // off the grev.
7538 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7539                                           const RISCVSubtarget &Subtarget) {
7540   bool IsWInstruction =
7541       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7542   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7543           IsWInstruction) &&
7544          "Unexpected opcode!");
7545   SDValue Src = N->getOperand(0);
7546   EVT VT = N->getValueType(0);
7547   SDLoc DL(N);
7548 
7549   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7550     return SDValue();
7551 
7552   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7553       !isa<ConstantSDNode>(Src.getOperand(1)))
7554     return SDValue();
7555 
7556   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7557   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7558 
7559   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7560   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7561   unsigned ShAmt1 = N->getConstantOperandVal(1);
7562   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7563   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7564     return SDValue();
7565 
7566   Src = Src.getOperand(0);
7567 
7568   // Toggle bit the MSB of the shift.
7569   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7570   if (CombinedShAmt == 0)
7571     return Src;
7572 
7573   SDValue Res = DAG.getNode(
7574       RISCVISD::GREV, DL, VT, Src,
7575       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7576   if (!IsWInstruction)
7577     return Res;
7578 
7579   // Sign extend the result to match the behavior of the rotate. This will be
7580   // selected to GREVIW in isel.
7581   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7582                      DAG.getValueType(MVT::i32));
7583 }
7584 
7585 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7586 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7587 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7588 // not undo itself, but they are redundant.
7589 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7590   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7591   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7592   SDValue Src = N->getOperand(0);
7593 
7594   if (Src.getOpcode() != N->getOpcode())
7595     return SDValue();
7596 
7597   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7598       !isa<ConstantSDNode>(Src.getOperand(1)))
7599     return SDValue();
7600 
7601   unsigned ShAmt1 = N->getConstantOperandVal(1);
7602   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7603   Src = Src.getOperand(0);
7604 
7605   unsigned CombinedShAmt;
7606   if (IsGORC)
7607     CombinedShAmt = ShAmt1 | ShAmt2;
7608   else
7609     CombinedShAmt = ShAmt1 ^ ShAmt2;
7610 
7611   if (CombinedShAmt == 0)
7612     return Src;
7613 
7614   SDLoc DL(N);
7615   return DAG.getNode(
7616       N->getOpcode(), DL, N->getValueType(0), Src,
7617       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7618 }
7619 
7620 // Combine a constant select operand into its use:
7621 //
7622 // (and (select cond, -1, c), x)
7623 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7624 // (or  (select cond, 0, c), x)
7625 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7626 // (xor (select cond, 0, c), x)
7627 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7628 // (add (select cond, 0, c), x)
7629 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7630 // (sub x, (select cond, 0, c))
7631 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7632 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7633                                    SelectionDAG &DAG, bool AllOnes) {
7634   EVT VT = N->getValueType(0);
7635 
7636   // Skip vectors.
7637   if (VT.isVector())
7638     return SDValue();
7639 
7640   if ((Slct.getOpcode() != ISD::SELECT &&
7641        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7642       !Slct.hasOneUse())
7643     return SDValue();
7644 
7645   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7646     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7647   };
7648 
7649   bool SwapSelectOps;
7650   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7651   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7652   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7653   SDValue NonConstantVal;
7654   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7655     SwapSelectOps = false;
7656     NonConstantVal = FalseVal;
7657   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7658     SwapSelectOps = true;
7659     NonConstantVal = TrueVal;
7660   } else
7661     return SDValue();
7662 
7663   // Slct is now know to be the desired identity constant when CC is true.
7664   TrueVal = OtherOp;
7665   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7666   // Unless SwapSelectOps says the condition should be false.
7667   if (SwapSelectOps)
7668     std::swap(TrueVal, FalseVal);
7669 
7670   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7671     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7672                        {Slct.getOperand(0), Slct.getOperand(1),
7673                         Slct.getOperand(2), TrueVal, FalseVal});
7674 
7675   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7676                      {Slct.getOperand(0), TrueVal, FalseVal});
7677 }
7678 
7679 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7680 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7681                                               bool AllOnes) {
7682   SDValue N0 = N->getOperand(0);
7683   SDValue N1 = N->getOperand(1);
7684   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7685     return Result;
7686   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7687     return Result;
7688   return SDValue();
7689 }
7690 
7691 // Transform (add (mul x, c0), c1) ->
7692 //           (add (mul (add x, c1/c0), c0), c1%c0).
7693 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7694 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7695 // to an infinite loop in DAGCombine if transformed.
7696 // Or transform (add (mul x, c0), c1) ->
7697 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7698 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7699 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7700 // lead to an infinite loop in DAGCombine if transformed.
7701 // Or transform (add (mul x, c0), c1) ->
7702 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7703 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7704 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7705 // lead to an infinite loop in DAGCombine if transformed.
7706 // Or transform (add (mul x, c0), c1) ->
7707 //              (mul (add x, c1/c0), c0).
7708 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7709 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7710                                      const RISCVSubtarget &Subtarget) {
7711   // Skip for vector types and larger types.
7712   EVT VT = N->getValueType(0);
7713   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7714     return SDValue();
7715   // The first operand node must be a MUL and has no other use.
7716   SDValue N0 = N->getOperand(0);
7717   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7718     return SDValue();
7719   // Check if c0 and c1 match above conditions.
7720   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7721   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7722   if (!N0C || !N1C)
7723     return SDValue();
7724   // If N0C has multiple uses it's possible one of the cases in
7725   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7726   // in an infinite loop.
7727   if (!N0C->hasOneUse())
7728     return SDValue();
7729   int64_t C0 = N0C->getSExtValue();
7730   int64_t C1 = N1C->getSExtValue();
7731   int64_t CA, CB;
7732   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7733     return SDValue();
7734   // Search for proper CA (non-zero) and CB that both are simm12.
7735   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7736       !isInt<12>(C0 * (C1 / C0))) {
7737     CA = C1 / C0;
7738     CB = C1 % C0;
7739   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7740              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7741     CA = C1 / C0 + 1;
7742     CB = C1 % C0 - C0;
7743   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7744              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7745     CA = C1 / C0 - 1;
7746     CB = C1 % C0 + C0;
7747   } else
7748     return SDValue();
7749   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7750   SDLoc DL(N);
7751   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7752                              DAG.getConstant(CA, DL, VT));
7753   SDValue New1 =
7754       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7755   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7756 }
7757 
7758 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7759                                  const RISCVSubtarget &Subtarget) {
7760   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7761     return V;
7762   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7763     return V;
7764   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7765   //      (select lhs, rhs, cc, x, (add x, y))
7766   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7767 }
7768 
7769 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7770   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7771   //      (select lhs, rhs, cc, x, (sub x, y))
7772   SDValue N0 = N->getOperand(0);
7773   SDValue N1 = N->getOperand(1);
7774   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7775 }
7776 
7777 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7778   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7779   //      (select lhs, rhs, cc, x, (and x, y))
7780   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7781 }
7782 
7783 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7784                                 const RISCVSubtarget &Subtarget) {
7785   if (Subtarget.hasStdExtZbp()) {
7786     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7787       return GREV;
7788     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7789       return GORC;
7790     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7791       return SHFL;
7792   }
7793 
7794   // fold (or (select cond, 0, y), x) ->
7795   //      (select cond, x, (or x, y))
7796   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7797 }
7798 
7799 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7800   SDValue N0 = N->getOperand(0);
7801   SDValue N1 = N->getOperand(1);
7802 
7803   // fold (xor (sllw 1, x), -1) -> (rolw ~1, x)
7804   // NOTE: Assumes ROL being legal means ROLW is legal.
7805   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7806   if (N0.getOpcode() == RISCVISD::SLLW &&
7807       isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) &&
7808       TLI.isOperationLegal(ISD::ROTL, MVT::i64)) {
7809     SDLoc DL(N);
7810     return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64,
7811                        DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1));
7812   }
7813 
7814   // fold (xor (select cond, 0, y), x) ->
7815   //      (select cond, x, (xor x, y))
7816   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7817 }
7818 
7819 static SDValue
7820 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
7821                                 const RISCVSubtarget &Subtarget) {
7822   SDValue Src = N->getOperand(0);
7823   EVT VT = N->getValueType(0);
7824 
7825   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
7826   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7827       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
7828     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
7829                        Src.getOperand(0));
7830 
7831   // Fold (i64 (sext_inreg (abs X), i32)) ->
7832   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
7833   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
7834   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
7835   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
7836   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
7837   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
7838   // may get combined into an earlier operation so we need to use
7839   // ComputeNumSignBits.
7840   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
7841   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
7842   // we can't assume that X has 33 sign bits. We must check.
7843   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
7844       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
7845       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
7846       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
7847     SDLoc DL(N);
7848     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
7849     SDValue Neg =
7850         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
7851     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
7852                       DAG.getValueType(MVT::i32));
7853     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
7854   }
7855 
7856   return SDValue();
7857 }
7858 
7859 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
7860 // vwadd(u).vv/vx or vwsub(u).vv/vx.
7861 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
7862                                              bool Commute = false) {
7863   assert((N->getOpcode() == RISCVISD::ADD_VL ||
7864           N->getOpcode() == RISCVISD::SUB_VL) &&
7865          "Unexpected opcode");
7866   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
7867   SDValue Op0 = N->getOperand(0);
7868   SDValue Op1 = N->getOperand(1);
7869   if (Commute)
7870     std::swap(Op0, Op1);
7871 
7872   MVT VT = N->getSimpleValueType(0);
7873 
7874   // Determine the narrow size for a widening add/sub.
7875   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7876   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7877                                   VT.getVectorElementCount());
7878 
7879   SDValue Mask = N->getOperand(2);
7880   SDValue VL = N->getOperand(3);
7881 
7882   SDLoc DL(N);
7883 
7884   // If the RHS is a sext or zext, we can form a widening op.
7885   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
7886        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
7887       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
7888     unsigned ExtOpc = Op1.getOpcode();
7889     Op1 = Op1.getOperand(0);
7890     // Re-introduce narrower extends if needed.
7891     if (Op1.getValueType() != NarrowVT)
7892       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7893 
7894     unsigned WOpc;
7895     if (ExtOpc == RISCVISD::VSEXT_VL)
7896       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
7897     else
7898       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
7899 
7900     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
7901   }
7902 
7903   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
7904   // sext/zext?
7905 
7906   return SDValue();
7907 }
7908 
7909 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
7910 // vwsub(u).vv/vx.
7911 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
7912   SDValue Op0 = N->getOperand(0);
7913   SDValue Op1 = N->getOperand(1);
7914   SDValue Mask = N->getOperand(2);
7915   SDValue VL = N->getOperand(3);
7916 
7917   MVT VT = N->getSimpleValueType(0);
7918   MVT NarrowVT = Op1.getSimpleValueType();
7919   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
7920 
7921   unsigned VOpc;
7922   switch (N->getOpcode()) {
7923   default: llvm_unreachable("Unexpected opcode");
7924   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
7925   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
7926   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
7927   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
7928   }
7929 
7930   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7931                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
7932 
7933   SDLoc DL(N);
7934 
7935   // If the LHS is a sext or zext, we can narrow this op to the same size as
7936   // the RHS.
7937   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
7938        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
7939       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
7940     unsigned ExtOpc = Op0.getOpcode();
7941     Op0 = Op0.getOperand(0);
7942     // Re-introduce narrower extends if needed.
7943     if (Op0.getValueType() != NarrowVT)
7944       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7945     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
7946   }
7947 
7948   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7949                N->getOpcode() == RISCVISD::VWADDU_W_VL;
7950 
7951   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
7952   // to commute and use a vwadd(u).vx instead.
7953   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
7954       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
7955     Op0 = Op0.getOperand(1);
7956 
7957     // See if have enough sign bits or zero bits in the scalar to use a
7958     // widening add/sub by splatting to smaller element size.
7959     unsigned EltBits = VT.getScalarSizeInBits();
7960     unsigned ScalarBits = Op0.getValueSizeInBits();
7961     // Make sure we're getting all element bits from the scalar register.
7962     // FIXME: Support implicit sign extension of vmv.v.x?
7963     if (ScalarBits < EltBits)
7964       return SDValue();
7965 
7966     if (IsSigned) {
7967       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
7968         return SDValue();
7969     } else {
7970       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7971       if (!DAG.MaskedValueIsZero(Op0, Mask))
7972         return SDValue();
7973     }
7974 
7975     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
7976                       DAG.getUNDEF(NarrowVT), Op0, VL);
7977     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
7978   }
7979 
7980   return SDValue();
7981 }
7982 
7983 // Try to form VWMUL, VWMULU or VWMULSU.
7984 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
7985 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
7986                                        bool Commute) {
7987   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
7988   SDValue Op0 = N->getOperand(0);
7989   SDValue Op1 = N->getOperand(1);
7990   if (Commute)
7991     std::swap(Op0, Op1);
7992 
7993   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
7994   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
7995   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
7996   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
7997     return SDValue();
7998 
7999   SDValue Mask = N->getOperand(2);
8000   SDValue VL = N->getOperand(3);
8001 
8002   // Make sure the mask and VL match.
8003   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8004     return SDValue();
8005 
8006   MVT VT = N->getSimpleValueType(0);
8007 
8008   // Determine the narrow size for a widening multiply.
8009   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8010   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8011                                   VT.getVectorElementCount());
8012 
8013   SDLoc DL(N);
8014 
8015   // See if the other operand is the same opcode.
8016   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8017     if (!Op1.hasOneUse())
8018       return SDValue();
8019 
8020     // Make sure the mask and VL match.
8021     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8022       return SDValue();
8023 
8024     Op1 = Op1.getOperand(0);
8025   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8026     // The operand is a splat of a scalar.
8027 
8028     // The pasthru must be undef for tail agnostic
8029     if (!Op1.getOperand(0).isUndef())
8030       return SDValue();
8031     // The VL must be the same.
8032     if (Op1.getOperand(2) != VL)
8033       return SDValue();
8034 
8035     // Get the scalar value.
8036     Op1 = Op1.getOperand(1);
8037 
8038     // See if have enough sign bits or zero bits in the scalar to use a
8039     // widening multiply by splatting to smaller element size.
8040     unsigned EltBits = VT.getScalarSizeInBits();
8041     unsigned ScalarBits = Op1.getValueSizeInBits();
8042     // Make sure we're getting all element bits from the scalar register.
8043     // FIXME: Support implicit sign extension of vmv.v.x?
8044     if (ScalarBits < EltBits)
8045       return SDValue();
8046 
8047     // If the LHS is a sign extend, try to use vwmul.
8048     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8049       // Can use vwmul.
8050     } else {
8051       // Otherwise try to use vwmulu or vwmulsu.
8052       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8053       if (DAG.MaskedValueIsZero(Op1, Mask))
8054         IsVWMULSU = IsSignExt;
8055       else
8056         return SDValue();
8057     }
8058 
8059     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8060                       DAG.getUNDEF(NarrowVT), Op1, VL);
8061   } else
8062     return SDValue();
8063 
8064   Op0 = Op0.getOperand(0);
8065 
8066   // Re-introduce narrower extends if needed.
8067   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8068   if (Op0.getValueType() != NarrowVT)
8069     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8070   // vwmulsu requires second operand to be zero extended.
8071   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8072   if (Op1.getValueType() != NarrowVT)
8073     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8074 
8075   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8076   if (!IsVWMULSU)
8077     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8078   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8079 }
8080 
8081 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8082   switch (Op.getOpcode()) {
8083   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8084   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8085   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8086   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8087   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8088   }
8089 
8090   return RISCVFPRndMode::Invalid;
8091 }
8092 
8093 // Fold
8094 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8095 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8096 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8097 //   (fp_to_int (fceil X))      -> fcvt X, rup
8098 //   (fp_to_int (fround X))     -> fcvt X, rmm
8099 static SDValue performFP_TO_INTCombine(SDNode *N,
8100                                        TargetLowering::DAGCombinerInfo &DCI,
8101                                        const RISCVSubtarget &Subtarget) {
8102   SelectionDAG &DAG = DCI.DAG;
8103   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8104   MVT XLenVT = Subtarget.getXLenVT();
8105 
8106   // Only handle XLen or i32 types. Other types narrower than XLen will
8107   // eventually be legalized to XLenVT.
8108   EVT VT = N->getValueType(0);
8109   if (VT != MVT::i32 && VT != XLenVT)
8110     return SDValue();
8111 
8112   SDValue Src = N->getOperand(0);
8113 
8114   // Ensure the FP type is also legal.
8115   if (!TLI.isTypeLegal(Src.getValueType()))
8116     return SDValue();
8117 
8118   // Don't do this for f16 with Zfhmin and not Zfh.
8119   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8120     return SDValue();
8121 
8122   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8123   if (FRM == RISCVFPRndMode::Invalid)
8124     return SDValue();
8125 
8126   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8127 
8128   unsigned Opc;
8129   if (VT == XLenVT)
8130     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8131   else
8132     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8133 
8134   SDLoc DL(N);
8135   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8136                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8137   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8138 }
8139 
8140 // Fold
8141 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8142 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8143 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8144 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8145 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8146 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8147                                        TargetLowering::DAGCombinerInfo &DCI,
8148                                        const RISCVSubtarget &Subtarget) {
8149   SelectionDAG &DAG = DCI.DAG;
8150   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8151   MVT XLenVT = Subtarget.getXLenVT();
8152 
8153   // Only handle XLen types. Other types narrower than XLen will eventually be
8154   // legalized to XLenVT.
8155   EVT DstVT = N->getValueType(0);
8156   if (DstVT != XLenVT)
8157     return SDValue();
8158 
8159   SDValue Src = N->getOperand(0);
8160 
8161   // Ensure the FP type is also legal.
8162   if (!TLI.isTypeLegal(Src.getValueType()))
8163     return SDValue();
8164 
8165   // Don't do this for f16 with Zfhmin and not Zfh.
8166   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8167     return SDValue();
8168 
8169   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8170 
8171   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8172   if (FRM == RISCVFPRndMode::Invalid)
8173     return SDValue();
8174 
8175   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8176 
8177   unsigned Opc;
8178   if (SatVT == DstVT)
8179     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8180   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8181     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8182   else
8183     return SDValue();
8184   // FIXME: Support other SatVTs by clamping before or after the conversion.
8185 
8186   Src = Src.getOperand(0);
8187 
8188   SDLoc DL(N);
8189   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8190                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8191 
8192   // RISCV FP-to-int conversions saturate to the destination register size, but
8193   // don't produce 0 for nan.
8194   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8195   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8196 }
8197 
8198 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8199 // smaller than XLenVT.
8200 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8201                                         const RISCVSubtarget &Subtarget) {
8202   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8203 
8204   SDValue Src = N->getOperand(0);
8205   if (Src.getOpcode() != ISD::BSWAP)
8206     return SDValue();
8207 
8208   EVT VT = N->getValueType(0);
8209   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8210       !isPowerOf2_32(VT.getSizeInBits()))
8211     return SDValue();
8212 
8213   SDLoc DL(N);
8214   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8215                      DAG.getConstant(7, DL, VT));
8216 }
8217 
8218 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8219                                                DAGCombinerInfo &DCI) const {
8220   SelectionDAG &DAG = DCI.DAG;
8221 
8222   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8223   // bits are demanded. N will be added to the Worklist if it was not deleted.
8224   // Caller should return SDValue(N, 0) if this returns true.
8225   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8226     SDValue Op = N->getOperand(OpNo);
8227     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8228     if (!SimplifyDemandedBits(Op, Mask, DCI))
8229       return false;
8230 
8231     if (N->getOpcode() != ISD::DELETED_NODE)
8232       DCI.AddToWorklist(N);
8233     return true;
8234   };
8235 
8236   switch (N->getOpcode()) {
8237   default:
8238     break;
8239   case RISCVISD::SplitF64: {
8240     SDValue Op0 = N->getOperand(0);
8241     // If the input to SplitF64 is just BuildPairF64 then the operation is
8242     // redundant. Instead, use BuildPairF64's operands directly.
8243     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8244       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8245 
8246     if (Op0->isUndef()) {
8247       SDValue Lo = DAG.getUNDEF(MVT::i32);
8248       SDValue Hi = DAG.getUNDEF(MVT::i32);
8249       return DCI.CombineTo(N, Lo, Hi);
8250     }
8251 
8252     SDLoc DL(N);
8253 
8254     // It's cheaper to materialise two 32-bit integers than to load a double
8255     // from the constant pool and transfer it to integer registers through the
8256     // stack.
8257     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8258       APInt V = C->getValueAPF().bitcastToAPInt();
8259       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8260       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8261       return DCI.CombineTo(N, Lo, Hi);
8262     }
8263 
8264     // This is a target-specific version of a DAGCombine performed in
8265     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8266     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8267     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8268     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8269         !Op0.getNode()->hasOneUse())
8270       break;
8271     SDValue NewSplitF64 =
8272         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8273                     Op0.getOperand(0));
8274     SDValue Lo = NewSplitF64.getValue(0);
8275     SDValue Hi = NewSplitF64.getValue(1);
8276     APInt SignBit = APInt::getSignMask(32);
8277     if (Op0.getOpcode() == ISD::FNEG) {
8278       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8279                                   DAG.getConstant(SignBit, DL, MVT::i32));
8280       return DCI.CombineTo(N, Lo, NewHi);
8281     }
8282     assert(Op0.getOpcode() == ISD::FABS);
8283     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8284                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8285     return DCI.CombineTo(N, Lo, NewHi);
8286   }
8287   case RISCVISD::SLLW:
8288   case RISCVISD::SRAW:
8289   case RISCVISD::SRLW: {
8290     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8291     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8292         SimplifyDemandedLowBitsHelper(1, 5))
8293       return SDValue(N, 0);
8294 
8295     break;
8296   }
8297   case ISD::ROTR:
8298   case ISD::ROTL:
8299   case RISCVISD::RORW:
8300   case RISCVISD::ROLW: {
8301     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8302       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8303       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8304           SimplifyDemandedLowBitsHelper(1, 5))
8305         return SDValue(N, 0);
8306     }
8307 
8308     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8309   }
8310   case RISCVISD::CLZW:
8311   case RISCVISD::CTZW: {
8312     // Only the lower 32 bits of the first operand are read
8313     if (SimplifyDemandedLowBitsHelper(0, 32))
8314       return SDValue(N, 0);
8315     break;
8316   }
8317   case RISCVISD::GREV:
8318   case RISCVISD::GORC: {
8319     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8320     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8321     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8322     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8323       return SDValue(N, 0);
8324 
8325     return combineGREVI_GORCI(N, DAG);
8326   }
8327   case RISCVISD::GREVW:
8328   case RISCVISD::GORCW: {
8329     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8330     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8331         SimplifyDemandedLowBitsHelper(1, 5))
8332       return SDValue(N, 0);
8333 
8334     break;
8335   }
8336   case RISCVISD::SHFL:
8337   case RISCVISD::UNSHFL: {
8338     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8339     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8340     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8341     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8342       return SDValue(N, 0);
8343 
8344     break;
8345   }
8346   case RISCVISD::SHFLW:
8347   case RISCVISD::UNSHFLW: {
8348     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8349     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8350         SimplifyDemandedLowBitsHelper(1, 4))
8351       return SDValue(N, 0);
8352 
8353     break;
8354   }
8355   case RISCVISD::BCOMPRESSW:
8356   case RISCVISD::BDECOMPRESSW: {
8357     // Only the lower 32 bits of LHS and RHS are read.
8358     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8359         SimplifyDemandedLowBitsHelper(1, 32))
8360       return SDValue(N, 0);
8361 
8362     break;
8363   }
8364   case RISCVISD::FSR:
8365   case RISCVISD::FSL:
8366   case RISCVISD::FSRW:
8367   case RISCVISD::FSLW: {
8368     bool IsWInstruction =
8369         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8370     unsigned BitWidth =
8371         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8372     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8373     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8374     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8375       return SDValue(N, 0);
8376 
8377     break;
8378   }
8379   case RISCVISD::FMV_X_ANYEXTH:
8380   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8381     SDLoc DL(N);
8382     SDValue Op0 = N->getOperand(0);
8383     MVT VT = N->getSimpleValueType(0);
8384     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8385     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8386     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8387     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8388          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8389         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8390          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8391       assert(Op0.getOperand(0).getValueType() == VT &&
8392              "Unexpected value type!");
8393       return Op0.getOperand(0);
8394     }
8395 
8396     // This is a target-specific version of a DAGCombine performed in
8397     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8398     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8399     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8400     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8401         !Op0.getNode()->hasOneUse())
8402       break;
8403     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8404     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8405     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
8406     if (Op0.getOpcode() == ISD::FNEG)
8407       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8408                          DAG.getConstant(SignBit, DL, VT));
8409 
8410     assert(Op0.getOpcode() == ISD::FABS);
8411     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8412                        DAG.getConstant(~SignBit, DL, VT));
8413   }
8414   case ISD::ADD:
8415     return performADDCombine(N, DAG, Subtarget);
8416   case ISD::SUB:
8417     return performSUBCombine(N, DAG);
8418   case ISD::AND:
8419     return performANDCombine(N, DAG);
8420   case ISD::OR:
8421     return performORCombine(N, DAG, Subtarget);
8422   case ISD::XOR:
8423     return performXORCombine(N, DAG);
8424   case ISD::SIGN_EXTEND_INREG:
8425     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8426   case ISD::ZERO_EXTEND:
8427     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8428     // type legalization. This is safe because fp_to_uint produces poison if
8429     // it overflows.
8430     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8431       SDValue Src = N->getOperand(0);
8432       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8433           isTypeLegal(Src.getOperand(0).getValueType()))
8434         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8435                            Src.getOperand(0));
8436       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8437           isTypeLegal(Src.getOperand(1).getValueType())) {
8438         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8439         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8440                                   Src.getOperand(0), Src.getOperand(1));
8441         DCI.CombineTo(N, Res);
8442         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8443         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8444         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8445       }
8446     }
8447     return SDValue();
8448   case RISCVISD::SELECT_CC: {
8449     // Transform
8450     SDValue LHS = N->getOperand(0);
8451     SDValue RHS = N->getOperand(1);
8452     SDValue TrueV = N->getOperand(3);
8453     SDValue FalseV = N->getOperand(4);
8454 
8455     // If the True and False values are the same, we don't need a select_cc.
8456     if (TrueV == FalseV)
8457       return TrueV;
8458 
8459     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8460     if (!ISD::isIntEqualitySetCC(CCVal))
8461       break;
8462 
8463     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8464     //      (select_cc X, Y, lt, trueV, falseV)
8465     // Sometimes the setcc is introduced after select_cc has been formed.
8466     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8467         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8468       // If we're looking for eq 0 instead of ne 0, we need to invert the
8469       // condition.
8470       bool Invert = CCVal == ISD::SETEQ;
8471       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8472       if (Invert)
8473         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8474 
8475       SDLoc DL(N);
8476       RHS = LHS.getOperand(1);
8477       LHS = LHS.getOperand(0);
8478       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8479 
8480       SDValue TargetCC = DAG.getCondCode(CCVal);
8481       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8482                          {LHS, RHS, TargetCC, TrueV, FalseV});
8483     }
8484 
8485     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8486     //      (select_cc X, Y, eq/ne, trueV, falseV)
8487     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8488       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8489                          {LHS.getOperand(0), LHS.getOperand(1),
8490                           N->getOperand(2), TrueV, FalseV});
8491     // (select_cc X, 1, setne, trueV, falseV) ->
8492     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8493     // This can occur when legalizing some floating point comparisons.
8494     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8495     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8496       SDLoc DL(N);
8497       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8498       SDValue TargetCC = DAG.getCondCode(CCVal);
8499       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8500       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8501                          {LHS, RHS, TargetCC, TrueV, FalseV});
8502     }
8503 
8504     break;
8505   }
8506   case RISCVISD::BR_CC: {
8507     SDValue LHS = N->getOperand(1);
8508     SDValue RHS = N->getOperand(2);
8509     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8510     if (!ISD::isIntEqualitySetCC(CCVal))
8511       break;
8512 
8513     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8514     //      (br_cc X, Y, lt, dest)
8515     // Sometimes the setcc is introduced after br_cc has been formed.
8516     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8517         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8518       // If we're looking for eq 0 instead of ne 0, we need to invert the
8519       // condition.
8520       bool Invert = CCVal == ISD::SETEQ;
8521       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8522       if (Invert)
8523         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8524 
8525       SDLoc DL(N);
8526       RHS = LHS.getOperand(1);
8527       LHS = LHS.getOperand(0);
8528       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8529 
8530       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8531                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8532                          N->getOperand(4));
8533     }
8534 
8535     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8536     //      (br_cc X, Y, eq/ne, trueV, falseV)
8537     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8538       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8539                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8540                          N->getOperand(3), N->getOperand(4));
8541 
8542     // (br_cc X, 1, setne, br_cc) ->
8543     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8544     // This can occur when legalizing some floating point comparisons.
8545     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8546     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8547       SDLoc DL(N);
8548       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8549       SDValue TargetCC = DAG.getCondCode(CCVal);
8550       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8551       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8552                          N->getOperand(0), LHS, RHS, TargetCC,
8553                          N->getOperand(4));
8554     }
8555     break;
8556   }
8557   case ISD::BITREVERSE:
8558     return performBITREVERSECombine(N, DAG, Subtarget);
8559   case ISD::FP_TO_SINT:
8560   case ISD::FP_TO_UINT:
8561     return performFP_TO_INTCombine(N, DCI, Subtarget);
8562   case ISD::FP_TO_SINT_SAT:
8563   case ISD::FP_TO_UINT_SAT:
8564     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8565   case ISD::FCOPYSIGN: {
8566     EVT VT = N->getValueType(0);
8567     if (!VT.isVector())
8568       break;
8569     // There is a form of VFSGNJ which injects the negated sign of its second
8570     // operand. Try and bubble any FNEG up after the extend/round to produce
8571     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8572     // TRUNC=1.
8573     SDValue In2 = N->getOperand(1);
8574     // Avoid cases where the extend/round has multiple uses, as duplicating
8575     // those is typically more expensive than removing a fneg.
8576     if (!In2.hasOneUse())
8577       break;
8578     if (In2.getOpcode() != ISD::FP_EXTEND &&
8579         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8580       break;
8581     In2 = In2.getOperand(0);
8582     if (In2.getOpcode() != ISD::FNEG)
8583       break;
8584     SDLoc DL(N);
8585     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8586     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8587                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8588   }
8589   case ISD::MGATHER:
8590   case ISD::MSCATTER:
8591   case ISD::VP_GATHER:
8592   case ISD::VP_SCATTER: {
8593     if (!DCI.isBeforeLegalize())
8594       break;
8595     SDValue Index, ScaleOp;
8596     bool IsIndexScaled = false;
8597     bool IsIndexSigned = false;
8598     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8599       Index = VPGSN->getIndex();
8600       ScaleOp = VPGSN->getScale();
8601       IsIndexScaled = VPGSN->isIndexScaled();
8602       IsIndexSigned = VPGSN->isIndexSigned();
8603     } else {
8604       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8605       Index = MGSN->getIndex();
8606       ScaleOp = MGSN->getScale();
8607       IsIndexScaled = MGSN->isIndexScaled();
8608       IsIndexSigned = MGSN->isIndexSigned();
8609     }
8610     EVT IndexVT = Index.getValueType();
8611     MVT XLenVT = Subtarget.getXLenVT();
8612     // RISCV indexed loads only support the "unsigned unscaled" addressing
8613     // mode, so anything else must be manually legalized.
8614     bool NeedsIdxLegalization =
8615         IsIndexScaled ||
8616         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8617     if (!NeedsIdxLegalization)
8618       break;
8619 
8620     SDLoc DL(N);
8621 
8622     // Any index legalization should first promote to XLenVT, so we don't lose
8623     // bits when scaling. This may create an illegal index type so we let
8624     // LLVM's legalization take care of the splitting.
8625     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8626     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8627       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8628       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8629                           DL, IndexVT, Index);
8630     }
8631 
8632     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8633     if (IsIndexScaled && Scale != 1) {
8634       // Manually scale the indices by the element size.
8635       // TODO: Sanitize the scale operand here?
8636       // TODO: For VP nodes, should we use VP_SHL here?
8637       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8638       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8639       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8640     }
8641 
8642     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
8643     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8644       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8645                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8646                               VPGN->getScale(), VPGN->getMask(),
8647                               VPGN->getVectorLength()},
8648                              VPGN->getMemOperand(), NewIndexTy);
8649     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8650       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8651                               {VPSN->getChain(), VPSN->getValue(),
8652                                VPSN->getBasePtr(), Index, VPSN->getScale(),
8653                                VPSN->getMask(), VPSN->getVectorLength()},
8654                               VPSN->getMemOperand(), NewIndexTy);
8655     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8656       return DAG.getMaskedGather(
8657           N->getVTList(), MGN->getMemoryVT(), DL,
8658           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8659            MGN->getBasePtr(), Index, MGN->getScale()},
8660           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8661     const auto *MSN = cast<MaskedScatterSDNode>(N);
8662     return DAG.getMaskedScatter(
8663         N->getVTList(), MSN->getMemoryVT(), DL,
8664         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8665          Index, MSN->getScale()},
8666         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8667   }
8668   case RISCVISD::SRA_VL:
8669   case RISCVISD::SRL_VL:
8670   case RISCVISD::SHL_VL: {
8671     SDValue ShAmt = N->getOperand(1);
8672     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8673       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8674       SDLoc DL(N);
8675       SDValue VL = N->getOperand(3);
8676       EVT VT = N->getValueType(0);
8677       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8678                           ShAmt.getOperand(1), VL);
8679       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8680                          N->getOperand(2), N->getOperand(3));
8681     }
8682     break;
8683   }
8684   case ISD::SRA:
8685   case ISD::SRL:
8686   case ISD::SHL: {
8687     SDValue ShAmt = N->getOperand(1);
8688     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8689       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8690       SDLoc DL(N);
8691       EVT VT = N->getValueType(0);
8692       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8693                           ShAmt.getOperand(1),
8694                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8695       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8696     }
8697     break;
8698   }
8699   case RISCVISD::ADD_VL:
8700     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8701       return V;
8702     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8703   case RISCVISD::SUB_VL:
8704     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8705   case RISCVISD::VWADD_W_VL:
8706   case RISCVISD::VWADDU_W_VL:
8707   case RISCVISD::VWSUB_W_VL:
8708   case RISCVISD::VWSUBU_W_VL:
8709     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8710   case RISCVISD::MUL_VL:
8711     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8712       return V;
8713     // Mul is commutative.
8714     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8715   case ISD::STORE: {
8716     auto *Store = cast<StoreSDNode>(N);
8717     SDValue Val = Store->getValue();
8718     // Combine store of vmv.x.s to vse with VL of 1.
8719     // FIXME: Support FP.
8720     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8721       SDValue Src = Val.getOperand(0);
8722       EVT VecVT = Src.getValueType();
8723       EVT MemVT = Store->getMemoryVT();
8724       // The memory VT and the element type must match.
8725       if (VecVT.getVectorElementType() == MemVT) {
8726         SDLoc DL(N);
8727         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8728         return DAG.getStoreVP(
8729             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8730             DAG.getConstant(1, DL, MaskVT),
8731             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8732             Store->getMemOperand(), Store->getAddressingMode(),
8733             Store->isTruncatingStore(), /*IsCompress*/ false);
8734       }
8735     }
8736 
8737     break;
8738   }
8739   case ISD::SPLAT_VECTOR: {
8740     EVT VT = N->getValueType(0);
8741     // Only perform this combine on legal MVT types.
8742     if (!isTypeLegal(VT))
8743       break;
8744     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
8745                                          DAG, Subtarget))
8746       return Gather;
8747     break;
8748   }
8749   case RISCVISD::VMV_V_X_VL: {
8750     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
8751     // scalar input.
8752     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
8753     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
8754     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
8755       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
8756         return SDValue(N, 0);
8757 
8758     break;
8759   }
8760   case ISD::INTRINSIC_WO_CHAIN: {
8761     unsigned IntNo = N->getConstantOperandVal(0);
8762     switch (IntNo) {
8763       // By default we do not combine any intrinsic.
8764     default:
8765       return SDValue();
8766     case Intrinsic::riscv_vcpop:
8767     case Intrinsic::riscv_vcpop_mask:
8768     case Intrinsic::riscv_vfirst:
8769     case Intrinsic::riscv_vfirst_mask: {
8770       SDValue VL = N->getOperand(2);
8771       if (IntNo == Intrinsic::riscv_vcpop_mask ||
8772           IntNo == Intrinsic::riscv_vfirst_mask)
8773         VL = N->getOperand(3);
8774       if (!isNullConstant(VL))
8775         return SDValue();
8776       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
8777       SDLoc DL(N);
8778       EVT VT = N->getValueType(0);
8779       if (IntNo == Intrinsic::riscv_vfirst ||
8780           IntNo == Intrinsic::riscv_vfirst_mask)
8781         return DAG.getConstant(-1, DL, VT);
8782       return DAG.getConstant(0, DL, VT);
8783     }
8784     }
8785   }
8786   }
8787 
8788   return SDValue();
8789 }
8790 
8791 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8792     const SDNode *N, CombineLevel Level) const {
8793   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8794   // materialised in fewer instructions than `(OP _, c1)`:
8795   //
8796   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8797   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8798   SDValue N0 = N->getOperand(0);
8799   EVT Ty = N0.getValueType();
8800   if (Ty.isScalarInteger() &&
8801       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8802     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8803     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8804     if (C1 && C2) {
8805       const APInt &C1Int = C1->getAPIntValue();
8806       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8807 
8808       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8809       // and the combine should happen, to potentially allow further combines
8810       // later.
8811       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8812           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8813         return true;
8814 
8815       // We can materialise `c1` in an add immediate, so it's "free", and the
8816       // combine should be prevented.
8817       if (C1Int.getMinSignedBits() <= 64 &&
8818           isLegalAddImmediate(C1Int.getSExtValue()))
8819         return false;
8820 
8821       // Neither constant will fit into an immediate, so find materialisation
8822       // costs.
8823       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8824                                               Subtarget.getFeatureBits(),
8825                                               /*CompressionCost*/true);
8826       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8827           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8828           /*CompressionCost*/true);
8829 
8830       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8831       // combine should be prevented.
8832       if (C1Cost < ShiftedC1Cost)
8833         return false;
8834     }
8835   }
8836   return true;
8837 }
8838 
8839 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8840     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8841     TargetLoweringOpt &TLO) const {
8842   // Delay this optimization as late as possible.
8843   if (!TLO.LegalOps)
8844     return false;
8845 
8846   EVT VT = Op.getValueType();
8847   if (VT.isVector())
8848     return false;
8849 
8850   // Only handle AND for now.
8851   if (Op.getOpcode() != ISD::AND)
8852     return false;
8853 
8854   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8855   if (!C)
8856     return false;
8857 
8858   const APInt &Mask = C->getAPIntValue();
8859 
8860   // Clear all non-demanded bits initially.
8861   APInt ShrunkMask = Mask & DemandedBits;
8862 
8863   // Try to make a smaller immediate by setting undemanded bits.
8864 
8865   APInt ExpandedMask = Mask | ~DemandedBits;
8866 
8867   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8868     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8869   };
8870   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8871     if (NewMask == Mask)
8872       return true;
8873     SDLoc DL(Op);
8874     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8875     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8876     return TLO.CombineTo(Op, NewOp);
8877   };
8878 
8879   // If the shrunk mask fits in sign extended 12 bits, let the target
8880   // independent code apply it.
8881   if (ShrunkMask.isSignedIntN(12))
8882     return false;
8883 
8884   // Preserve (and X, 0xffff) when zext.h is supported.
8885   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8886     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8887     if (IsLegalMask(NewMask))
8888       return UseMask(NewMask);
8889   }
8890 
8891   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8892   if (VT == MVT::i64) {
8893     APInt NewMask = APInt(64, 0xffffffff);
8894     if (IsLegalMask(NewMask))
8895       return UseMask(NewMask);
8896   }
8897 
8898   // For the remaining optimizations, we need to be able to make a negative
8899   // number through a combination of mask and undemanded bits.
8900   if (!ExpandedMask.isNegative())
8901     return false;
8902 
8903   // What is the fewest number of bits we need to represent the negative number.
8904   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8905 
8906   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8907   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8908   APInt NewMask = ShrunkMask;
8909   if (MinSignedBits <= 12)
8910     NewMask.setBitsFrom(11);
8911   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8912     NewMask.setBitsFrom(31);
8913   else
8914     return false;
8915 
8916   // Check that our new mask is a subset of the demanded mask.
8917   assert(IsLegalMask(NewMask));
8918   return UseMask(NewMask);
8919 }
8920 
8921 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
8922   static const uint64_t GREVMasks[] = {
8923       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
8924       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
8925 
8926   for (unsigned Stage = 0; Stage != 6; ++Stage) {
8927     unsigned Shift = 1 << Stage;
8928     if (ShAmt & Shift) {
8929       uint64_t Mask = GREVMasks[Stage];
8930       uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
8931       if (IsGORC)
8932         Res |= x;
8933       x = Res;
8934     }
8935   }
8936 
8937   return x;
8938 }
8939 
8940 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8941                                                         KnownBits &Known,
8942                                                         const APInt &DemandedElts,
8943                                                         const SelectionDAG &DAG,
8944                                                         unsigned Depth) const {
8945   unsigned BitWidth = Known.getBitWidth();
8946   unsigned Opc = Op.getOpcode();
8947   assert((Opc >= ISD::BUILTIN_OP_END ||
8948           Opc == ISD::INTRINSIC_WO_CHAIN ||
8949           Opc == ISD::INTRINSIC_W_CHAIN ||
8950           Opc == ISD::INTRINSIC_VOID) &&
8951          "Should use MaskedValueIsZero if you don't know whether Op"
8952          " is a target node!");
8953 
8954   Known.resetAll();
8955   switch (Opc) {
8956   default: break;
8957   case RISCVISD::SELECT_CC: {
8958     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
8959     // If we don't know any bits, early out.
8960     if (Known.isUnknown())
8961       break;
8962     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
8963 
8964     // Only known if known in both the LHS and RHS.
8965     Known = KnownBits::commonBits(Known, Known2);
8966     break;
8967   }
8968   case RISCVISD::REMUW: {
8969     KnownBits Known2;
8970     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8971     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8972     // We only care about the lower 32 bits.
8973     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
8974     // Restore the original width by sign extending.
8975     Known = Known.sext(BitWidth);
8976     break;
8977   }
8978   case RISCVISD::DIVUW: {
8979     KnownBits Known2;
8980     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8981     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8982     // We only care about the lower 32 bits.
8983     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
8984     // Restore the original width by sign extending.
8985     Known = Known.sext(BitWidth);
8986     break;
8987   }
8988   case RISCVISD::CTZW: {
8989     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8990     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
8991     unsigned LowBits = Log2_32(PossibleTZ) + 1;
8992     Known.Zero.setBitsFrom(LowBits);
8993     break;
8994   }
8995   case RISCVISD::CLZW: {
8996     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8997     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
8998     unsigned LowBits = Log2_32(PossibleLZ) + 1;
8999     Known.Zero.setBitsFrom(LowBits);
9000     break;
9001   }
9002   case RISCVISD::GREV:
9003   case RISCVISD::GORC: {
9004     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9005       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9006       unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1);
9007       bool IsGORC = Op.getOpcode() == RISCVISD::GORC;
9008       // To compute zeros, we need to invert the value and invert it back after.
9009       Known.Zero =
9010           ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC);
9011       Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC);
9012     }
9013     break;
9014   }
9015   case RISCVISD::READ_VLENB: {
9016     // If we know the minimum VLen from Zvl extensions, we can use that to
9017     // determine the trailing zeros of VLENB.
9018     // FIXME: Limit to 128 bit vectors until we have more testing.
9019     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
9020     if (MinVLenB > 0)
9021       Known.Zero.setLowBits(Log2_32(MinVLenB));
9022     // We assume VLENB is no more than 65536 / 8 bytes.
9023     Known.Zero.setBitsFrom(14);
9024     break;
9025   }
9026   case ISD::INTRINSIC_W_CHAIN:
9027   case ISD::INTRINSIC_WO_CHAIN: {
9028     unsigned IntNo =
9029         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9030     switch (IntNo) {
9031     default:
9032       // We can't do anything for most intrinsics.
9033       break;
9034     case Intrinsic::riscv_vsetvli:
9035     case Intrinsic::riscv_vsetvlimax:
9036     case Intrinsic::riscv_vsetvli_opt:
9037     case Intrinsic::riscv_vsetvlimax_opt:
9038       // Assume that VL output is positive and would fit in an int32_t.
9039       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9040       if (BitWidth >= 32)
9041         Known.Zero.setBitsFrom(31);
9042       break;
9043     }
9044     break;
9045   }
9046   }
9047 }
9048 
9049 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9050     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9051     unsigned Depth) const {
9052   switch (Op.getOpcode()) {
9053   default:
9054     break;
9055   case RISCVISD::SELECT_CC: {
9056     unsigned Tmp =
9057         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9058     if (Tmp == 1) return 1;  // Early out.
9059     unsigned Tmp2 =
9060         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9061     return std::min(Tmp, Tmp2);
9062   }
9063   case RISCVISD::SLLW:
9064   case RISCVISD::SRAW:
9065   case RISCVISD::SRLW:
9066   case RISCVISD::DIVW:
9067   case RISCVISD::DIVUW:
9068   case RISCVISD::REMUW:
9069   case RISCVISD::ROLW:
9070   case RISCVISD::RORW:
9071   case RISCVISD::GREVW:
9072   case RISCVISD::GORCW:
9073   case RISCVISD::FSLW:
9074   case RISCVISD::FSRW:
9075   case RISCVISD::SHFLW:
9076   case RISCVISD::UNSHFLW:
9077   case RISCVISD::BCOMPRESSW:
9078   case RISCVISD::BDECOMPRESSW:
9079   case RISCVISD::BFPW:
9080   case RISCVISD::FCVT_W_RV64:
9081   case RISCVISD::FCVT_WU_RV64:
9082   case RISCVISD::STRICT_FCVT_W_RV64:
9083   case RISCVISD::STRICT_FCVT_WU_RV64:
9084     // TODO: As the result is sign-extended, this is conservatively correct. A
9085     // more precise answer could be calculated for SRAW depending on known
9086     // bits in the shift amount.
9087     return 33;
9088   case RISCVISD::SHFL:
9089   case RISCVISD::UNSHFL: {
9090     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9091     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9092     // will stay within the upper 32 bits. If there were more than 32 sign bits
9093     // before there will be at least 33 sign bits after.
9094     if (Op.getValueType() == MVT::i64 &&
9095         isa<ConstantSDNode>(Op.getOperand(1)) &&
9096         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9097       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9098       if (Tmp > 32)
9099         return 33;
9100     }
9101     break;
9102   }
9103   case RISCVISD::VMV_X_S: {
9104     // The number of sign bits of the scalar result is computed by obtaining the
9105     // element type of the input vector operand, subtracting its width from the
9106     // XLEN, and then adding one (sign bit within the element type). If the
9107     // element type is wider than XLen, the least-significant XLEN bits are
9108     // taken.
9109     unsigned XLen = Subtarget.getXLen();
9110     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9111     if (EltBits <= XLen)
9112       return XLen - EltBits + 1;
9113     break;
9114   }
9115   }
9116 
9117   return 1;
9118 }
9119 
9120 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9121                                                   MachineBasicBlock *BB) {
9122   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9123 
9124   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9125   // Should the count have wrapped while it was being read, we need to try
9126   // again.
9127   // ...
9128   // read:
9129   // rdcycleh x3 # load high word of cycle
9130   // rdcycle  x2 # load low word of cycle
9131   // rdcycleh x4 # load high word of cycle
9132   // bne x3, x4, read # check if high word reads match, otherwise try again
9133   // ...
9134 
9135   MachineFunction &MF = *BB->getParent();
9136   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9137   MachineFunction::iterator It = ++BB->getIterator();
9138 
9139   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9140   MF.insert(It, LoopMBB);
9141 
9142   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9143   MF.insert(It, DoneMBB);
9144 
9145   // Transfer the remainder of BB and its successor edges to DoneMBB.
9146   DoneMBB->splice(DoneMBB->begin(), BB,
9147                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9148   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9149 
9150   BB->addSuccessor(LoopMBB);
9151 
9152   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9153   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9154   Register LoReg = MI.getOperand(0).getReg();
9155   Register HiReg = MI.getOperand(1).getReg();
9156   DebugLoc DL = MI.getDebugLoc();
9157 
9158   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9159   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9160       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9161       .addReg(RISCV::X0);
9162   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9163       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9164       .addReg(RISCV::X0);
9165   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9166       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9167       .addReg(RISCV::X0);
9168 
9169   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9170       .addReg(HiReg)
9171       .addReg(ReadAgainReg)
9172       .addMBB(LoopMBB);
9173 
9174   LoopMBB->addSuccessor(LoopMBB);
9175   LoopMBB->addSuccessor(DoneMBB);
9176 
9177   MI.eraseFromParent();
9178 
9179   return DoneMBB;
9180 }
9181 
9182 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9183                                              MachineBasicBlock *BB) {
9184   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9185 
9186   MachineFunction &MF = *BB->getParent();
9187   DebugLoc DL = MI.getDebugLoc();
9188   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9189   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9190   Register LoReg = MI.getOperand(0).getReg();
9191   Register HiReg = MI.getOperand(1).getReg();
9192   Register SrcReg = MI.getOperand(2).getReg();
9193   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9194   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9195 
9196   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9197                           RI);
9198   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9199   MachineMemOperand *MMOLo =
9200       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9201   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9202       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9203   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9204       .addFrameIndex(FI)
9205       .addImm(0)
9206       .addMemOperand(MMOLo);
9207   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9208       .addFrameIndex(FI)
9209       .addImm(4)
9210       .addMemOperand(MMOHi);
9211   MI.eraseFromParent(); // The pseudo instruction is gone now.
9212   return BB;
9213 }
9214 
9215 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9216                                                  MachineBasicBlock *BB) {
9217   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9218          "Unexpected instruction");
9219 
9220   MachineFunction &MF = *BB->getParent();
9221   DebugLoc DL = MI.getDebugLoc();
9222   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9223   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9224   Register DstReg = MI.getOperand(0).getReg();
9225   Register LoReg = MI.getOperand(1).getReg();
9226   Register HiReg = MI.getOperand(2).getReg();
9227   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9228   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9229 
9230   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9231   MachineMemOperand *MMOLo =
9232       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9233   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9234       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9235   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9236       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9237       .addFrameIndex(FI)
9238       .addImm(0)
9239       .addMemOperand(MMOLo);
9240   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9241       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9242       .addFrameIndex(FI)
9243       .addImm(4)
9244       .addMemOperand(MMOHi);
9245   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9246   MI.eraseFromParent(); // The pseudo instruction is gone now.
9247   return BB;
9248 }
9249 
9250 static bool isSelectPseudo(MachineInstr &MI) {
9251   switch (MI.getOpcode()) {
9252   default:
9253     return false;
9254   case RISCV::Select_GPR_Using_CC_GPR:
9255   case RISCV::Select_FPR16_Using_CC_GPR:
9256   case RISCV::Select_FPR32_Using_CC_GPR:
9257   case RISCV::Select_FPR64_Using_CC_GPR:
9258     return true;
9259   }
9260 }
9261 
9262 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9263                                         unsigned RelOpcode, unsigned EqOpcode,
9264                                         const RISCVSubtarget &Subtarget) {
9265   DebugLoc DL = MI.getDebugLoc();
9266   Register DstReg = MI.getOperand(0).getReg();
9267   Register Src1Reg = MI.getOperand(1).getReg();
9268   Register Src2Reg = MI.getOperand(2).getReg();
9269   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9270   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9271   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9272 
9273   // Save the current FFLAGS.
9274   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9275 
9276   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9277                  .addReg(Src1Reg)
9278                  .addReg(Src2Reg);
9279   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9280     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9281 
9282   // Restore the FFLAGS.
9283   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9284       .addReg(SavedFFlags, RegState::Kill);
9285 
9286   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9287   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9288                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9289                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9290   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9291     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9292 
9293   // Erase the pseudoinstruction.
9294   MI.eraseFromParent();
9295   return BB;
9296 }
9297 
9298 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9299                                            MachineBasicBlock *BB,
9300                                            const RISCVSubtarget &Subtarget) {
9301   // To "insert" Select_* instructions, we actually have to insert the triangle
9302   // control-flow pattern.  The incoming instructions know the destination vreg
9303   // to set, the condition code register to branch on, the true/false values to
9304   // select between, and the condcode to use to select the appropriate branch.
9305   //
9306   // We produce the following control flow:
9307   //     HeadMBB
9308   //     |  \
9309   //     |  IfFalseMBB
9310   //     | /
9311   //    TailMBB
9312   //
9313   // When we find a sequence of selects we attempt to optimize their emission
9314   // by sharing the control flow. Currently we only handle cases where we have
9315   // multiple selects with the exact same condition (same LHS, RHS and CC).
9316   // The selects may be interleaved with other instructions if the other
9317   // instructions meet some requirements we deem safe:
9318   // - They are debug instructions. Otherwise,
9319   // - They do not have side-effects, do not access memory and their inputs do
9320   //   not depend on the results of the select pseudo-instructions.
9321   // The TrueV/FalseV operands of the selects cannot depend on the result of
9322   // previous selects in the sequence.
9323   // These conditions could be further relaxed. See the X86 target for a
9324   // related approach and more information.
9325   Register LHS = MI.getOperand(1).getReg();
9326   Register RHS = MI.getOperand(2).getReg();
9327   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9328 
9329   SmallVector<MachineInstr *, 4> SelectDebugValues;
9330   SmallSet<Register, 4> SelectDests;
9331   SelectDests.insert(MI.getOperand(0).getReg());
9332 
9333   MachineInstr *LastSelectPseudo = &MI;
9334 
9335   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9336        SequenceMBBI != E; ++SequenceMBBI) {
9337     if (SequenceMBBI->isDebugInstr())
9338       continue;
9339     else if (isSelectPseudo(*SequenceMBBI)) {
9340       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9341           SequenceMBBI->getOperand(2).getReg() != RHS ||
9342           SequenceMBBI->getOperand(3).getImm() != CC ||
9343           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9344           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9345         break;
9346       LastSelectPseudo = &*SequenceMBBI;
9347       SequenceMBBI->collectDebugValues(SelectDebugValues);
9348       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9349     } else {
9350       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9351           SequenceMBBI->mayLoadOrStore())
9352         break;
9353       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9354             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9355           }))
9356         break;
9357     }
9358   }
9359 
9360   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9361   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9362   DebugLoc DL = MI.getDebugLoc();
9363   MachineFunction::iterator I = ++BB->getIterator();
9364 
9365   MachineBasicBlock *HeadMBB = BB;
9366   MachineFunction *F = BB->getParent();
9367   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9368   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9369 
9370   F->insert(I, IfFalseMBB);
9371   F->insert(I, TailMBB);
9372 
9373   // Transfer debug instructions associated with the selects to TailMBB.
9374   for (MachineInstr *DebugInstr : SelectDebugValues) {
9375     TailMBB->push_back(DebugInstr->removeFromParent());
9376   }
9377 
9378   // Move all instructions after the sequence to TailMBB.
9379   TailMBB->splice(TailMBB->end(), HeadMBB,
9380                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9381   // Update machine-CFG edges by transferring all successors of the current
9382   // block to the new block which will contain the Phi nodes for the selects.
9383   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9384   // Set the successors for HeadMBB.
9385   HeadMBB->addSuccessor(IfFalseMBB);
9386   HeadMBB->addSuccessor(TailMBB);
9387 
9388   // Insert appropriate branch.
9389   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9390     .addReg(LHS)
9391     .addReg(RHS)
9392     .addMBB(TailMBB);
9393 
9394   // IfFalseMBB just falls through to TailMBB.
9395   IfFalseMBB->addSuccessor(TailMBB);
9396 
9397   // Create PHIs for all of the select pseudo-instructions.
9398   auto SelectMBBI = MI.getIterator();
9399   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9400   auto InsertionPoint = TailMBB->begin();
9401   while (SelectMBBI != SelectEnd) {
9402     auto Next = std::next(SelectMBBI);
9403     if (isSelectPseudo(*SelectMBBI)) {
9404       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9405       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9406               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9407           .addReg(SelectMBBI->getOperand(4).getReg())
9408           .addMBB(HeadMBB)
9409           .addReg(SelectMBBI->getOperand(5).getReg())
9410           .addMBB(IfFalseMBB);
9411       SelectMBBI->eraseFromParent();
9412     }
9413     SelectMBBI = Next;
9414   }
9415 
9416   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9417   return TailMBB;
9418 }
9419 
9420 MachineBasicBlock *
9421 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9422                                                  MachineBasicBlock *BB) const {
9423   switch (MI.getOpcode()) {
9424   default:
9425     llvm_unreachable("Unexpected instr type to insert");
9426   case RISCV::ReadCycleWide:
9427     assert(!Subtarget.is64Bit() &&
9428            "ReadCycleWrite is only to be used on riscv32");
9429     return emitReadCycleWidePseudo(MI, BB);
9430   case RISCV::Select_GPR_Using_CC_GPR:
9431   case RISCV::Select_FPR16_Using_CC_GPR:
9432   case RISCV::Select_FPR32_Using_CC_GPR:
9433   case RISCV::Select_FPR64_Using_CC_GPR:
9434     return emitSelectPseudo(MI, BB, Subtarget);
9435   case RISCV::BuildPairF64Pseudo:
9436     return emitBuildPairF64Pseudo(MI, BB);
9437   case RISCV::SplitF64Pseudo:
9438     return emitSplitF64Pseudo(MI, BB);
9439   case RISCV::PseudoQuietFLE_H:
9440     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9441   case RISCV::PseudoQuietFLT_H:
9442     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9443   case RISCV::PseudoQuietFLE_S:
9444     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9445   case RISCV::PseudoQuietFLT_S:
9446     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9447   case RISCV::PseudoQuietFLE_D:
9448     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9449   case RISCV::PseudoQuietFLT_D:
9450     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9451   }
9452 }
9453 
9454 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9455                                                         SDNode *Node) const {
9456   // Add FRM dependency to any instructions with dynamic rounding mode.
9457   unsigned Opc = MI.getOpcode();
9458   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9459   if (Idx < 0)
9460     return;
9461   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9462     return;
9463   // If the instruction already reads FRM, don't add another read.
9464   if (MI.readsRegister(RISCV::FRM))
9465     return;
9466   MI.addOperand(
9467       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9468 }
9469 
9470 // Calling Convention Implementation.
9471 // The expectations for frontend ABI lowering vary from target to target.
9472 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9473 // details, but this is a longer term goal. For now, we simply try to keep the
9474 // role of the frontend as simple and well-defined as possible. The rules can
9475 // be summarised as:
9476 // * Never split up large scalar arguments. We handle them here.
9477 // * If a hardfloat calling convention is being used, and the struct may be
9478 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9479 // available, then pass as two separate arguments. If either the GPRs or FPRs
9480 // are exhausted, then pass according to the rule below.
9481 // * If a struct could never be passed in registers or directly in a stack
9482 // slot (as it is larger than 2*XLEN and the floating point rules don't
9483 // apply), then pass it using a pointer with the byval attribute.
9484 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9485 // word-sized array or a 2*XLEN scalar (depending on alignment).
9486 // * The frontend can determine whether a struct is returned by reference or
9487 // not based on its size and fields. If it will be returned by reference, the
9488 // frontend must modify the prototype so a pointer with the sret annotation is
9489 // passed as the first argument. This is not necessary for large scalar
9490 // returns.
9491 // * Struct return values and varargs should be coerced to structs containing
9492 // register-size fields in the same situations they would be for fixed
9493 // arguments.
9494 
9495 static const MCPhysReg ArgGPRs[] = {
9496   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9497   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9498 };
9499 static const MCPhysReg ArgFPR16s[] = {
9500   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9501   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9502 };
9503 static const MCPhysReg ArgFPR32s[] = {
9504   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9505   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9506 };
9507 static const MCPhysReg ArgFPR64s[] = {
9508   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9509   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9510 };
9511 // This is an interim calling convention and it may be changed in the future.
9512 static const MCPhysReg ArgVRs[] = {
9513     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9514     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9515     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9516 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9517                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9518                                      RISCV::V20M2, RISCV::V22M2};
9519 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9520                                      RISCV::V20M4};
9521 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9522 
9523 // Pass a 2*XLEN argument that has been split into two XLEN values through
9524 // registers or the stack as necessary.
9525 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9526                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9527                                 MVT ValVT2, MVT LocVT2,
9528                                 ISD::ArgFlagsTy ArgFlags2) {
9529   unsigned XLenInBytes = XLen / 8;
9530   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9531     // At least one half can be passed via register.
9532     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9533                                      VA1.getLocVT(), CCValAssign::Full));
9534   } else {
9535     // Both halves must be passed on the stack, with proper alignment.
9536     Align StackAlign =
9537         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9538     State.addLoc(
9539         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9540                             State.AllocateStack(XLenInBytes, StackAlign),
9541                             VA1.getLocVT(), CCValAssign::Full));
9542     State.addLoc(CCValAssign::getMem(
9543         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9544         LocVT2, CCValAssign::Full));
9545     return false;
9546   }
9547 
9548   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9549     // The second half can also be passed via register.
9550     State.addLoc(
9551         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9552   } else {
9553     // The second half is passed via the stack, without additional alignment.
9554     State.addLoc(CCValAssign::getMem(
9555         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9556         LocVT2, CCValAssign::Full));
9557   }
9558 
9559   return false;
9560 }
9561 
9562 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9563                                Optional<unsigned> FirstMaskArgument,
9564                                CCState &State, const RISCVTargetLowering &TLI) {
9565   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9566   if (RC == &RISCV::VRRegClass) {
9567     // Assign the first mask argument to V0.
9568     // This is an interim calling convention and it may be changed in the
9569     // future.
9570     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
9571       return State.AllocateReg(RISCV::V0);
9572     return State.AllocateReg(ArgVRs);
9573   }
9574   if (RC == &RISCV::VRM2RegClass)
9575     return State.AllocateReg(ArgVRM2s);
9576   if (RC == &RISCV::VRM4RegClass)
9577     return State.AllocateReg(ArgVRM4s);
9578   if (RC == &RISCV::VRM8RegClass)
9579     return State.AllocateReg(ArgVRM8s);
9580   llvm_unreachable("Unhandled register class for ValueType");
9581 }
9582 
9583 // Implements the RISC-V calling convention. Returns true upon failure.
9584 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9585                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9586                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9587                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9588                      Optional<unsigned> FirstMaskArgument) {
9589   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9590   assert(XLen == 32 || XLen == 64);
9591   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9592 
9593   // Any return value split in to more than two values can't be returned
9594   // directly. Vectors are returned via the available vector registers.
9595   if (!LocVT.isVector() && IsRet && ValNo > 1)
9596     return true;
9597 
9598   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9599   // variadic argument, or if no F16/F32 argument registers are available.
9600   bool UseGPRForF16_F32 = true;
9601   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9602   // variadic argument, or if no F64 argument registers are available.
9603   bool UseGPRForF64 = true;
9604 
9605   switch (ABI) {
9606   default:
9607     llvm_unreachable("Unexpected ABI");
9608   case RISCVABI::ABI_ILP32:
9609   case RISCVABI::ABI_LP64:
9610     break;
9611   case RISCVABI::ABI_ILP32F:
9612   case RISCVABI::ABI_LP64F:
9613     UseGPRForF16_F32 = !IsFixed;
9614     break;
9615   case RISCVABI::ABI_ILP32D:
9616   case RISCVABI::ABI_LP64D:
9617     UseGPRForF16_F32 = !IsFixed;
9618     UseGPRForF64 = !IsFixed;
9619     break;
9620   }
9621 
9622   // FPR16, FPR32, and FPR64 alias each other.
9623   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9624     UseGPRForF16_F32 = true;
9625     UseGPRForF64 = true;
9626   }
9627 
9628   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9629   // similar local variables rather than directly checking against the target
9630   // ABI.
9631 
9632   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9633     LocVT = XLenVT;
9634     LocInfo = CCValAssign::BCvt;
9635   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9636     LocVT = MVT::i64;
9637     LocInfo = CCValAssign::BCvt;
9638   }
9639 
9640   // If this is a variadic argument, the RISC-V calling convention requires
9641   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9642   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9643   // be used regardless of whether the original argument was split during
9644   // legalisation or not. The argument will not be passed by registers if the
9645   // original type is larger than 2*XLEN, so the register alignment rule does
9646   // not apply.
9647   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9648   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9649       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9650     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9651     // Skip 'odd' register if necessary.
9652     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9653       State.AllocateReg(ArgGPRs);
9654   }
9655 
9656   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9657   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9658       State.getPendingArgFlags();
9659 
9660   assert(PendingLocs.size() == PendingArgFlags.size() &&
9661          "PendingLocs and PendingArgFlags out of sync");
9662 
9663   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9664   // registers are exhausted.
9665   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9666     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9667            "Can't lower f64 if it is split");
9668     // Depending on available argument GPRS, f64 may be passed in a pair of
9669     // GPRs, split between a GPR and the stack, or passed completely on the
9670     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9671     // cases.
9672     Register Reg = State.AllocateReg(ArgGPRs);
9673     LocVT = MVT::i32;
9674     if (!Reg) {
9675       unsigned StackOffset = State.AllocateStack(8, Align(8));
9676       State.addLoc(
9677           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9678       return false;
9679     }
9680     if (!State.AllocateReg(ArgGPRs))
9681       State.AllocateStack(4, Align(4));
9682     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9683     return false;
9684   }
9685 
9686   // Fixed-length vectors are located in the corresponding scalable-vector
9687   // container types.
9688   if (ValVT.isFixedLengthVector())
9689     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9690 
9691   // Split arguments might be passed indirectly, so keep track of the pending
9692   // values. Split vectors are passed via a mix of registers and indirectly, so
9693   // treat them as we would any other argument.
9694   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9695     LocVT = XLenVT;
9696     LocInfo = CCValAssign::Indirect;
9697     PendingLocs.push_back(
9698         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9699     PendingArgFlags.push_back(ArgFlags);
9700     if (!ArgFlags.isSplitEnd()) {
9701       return false;
9702     }
9703   }
9704 
9705   // If the split argument only had two elements, it should be passed directly
9706   // in registers or on the stack.
9707   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9708       PendingLocs.size() <= 2) {
9709     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9710     // Apply the normal calling convention rules to the first half of the
9711     // split argument.
9712     CCValAssign VA = PendingLocs[0];
9713     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9714     PendingLocs.clear();
9715     PendingArgFlags.clear();
9716     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9717                                ArgFlags);
9718   }
9719 
9720   // Allocate to a register if possible, or else a stack slot.
9721   Register Reg;
9722   unsigned StoreSizeBytes = XLen / 8;
9723   Align StackAlign = Align(XLen / 8);
9724 
9725   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9726     Reg = State.AllocateReg(ArgFPR16s);
9727   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9728     Reg = State.AllocateReg(ArgFPR32s);
9729   else if (ValVT == MVT::f64 && !UseGPRForF64)
9730     Reg = State.AllocateReg(ArgFPR64s);
9731   else if (ValVT.isVector()) {
9732     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9733     if (!Reg) {
9734       // For return values, the vector must be passed fully via registers or
9735       // via the stack.
9736       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9737       // but we're using all of them.
9738       if (IsRet)
9739         return true;
9740       // Try using a GPR to pass the address
9741       if ((Reg = State.AllocateReg(ArgGPRs))) {
9742         LocVT = XLenVT;
9743         LocInfo = CCValAssign::Indirect;
9744       } else if (ValVT.isScalableVector()) {
9745         LocVT = XLenVT;
9746         LocInfo = CCValAssign::Indirect;
9747       } else {
9748         // Pass fixed-length vectors on the stack.
9749         LocVT = ValVT;
9750         StoreSizeBytes = ValVT.getStoreSize();
9751         // Align vectors to their element sizes, being careful for vXi1
9752         // vectors.
9753         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9754       }
9755     }
9756   } else {
9757     Reg = State.AllocateReg(ArgGPRs);
9758   }
9759 
9760   unsigned StackOffset =
9761       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9762 
9763   // If we reach this point and PendingLocs is non-empty, we must be at the
9764   // end of a split argument that must be passed indirectly.
9765   if (!PendingLocs.empty()) {
9766     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9767     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9768 
9769     for (auto &It : PendingLocs) {
9770       if (Reg)
9771         It.convertToReg(Reg);
9772       else
9773         It.convertToMem(StackOffset);
9774       State.addLoc(It);
9775     }
9776     PendingLocs.clear();
9777     PendingArgFlags.clear();
9778     return false;
9779   }
9780 
9781   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9782           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9783          "Expected an XLenVT or vector types at this stage");
9784 
9785   if (Reg) {
9786     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9787     return false;
9788   }
9789 
9790   // When a floating-point value is passed on the stack, no bit-conversion is
9791   // needed.
9792   if (ValVT.isFloatingPoint()) {
9793     LocVT = ValVT;
9794     LocInfo = CCValAssign::Full;
9795   }
9796   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9797   return false;
9798 }
9799 
9800 template <typename ArgTy>
9801 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9802   for (const auto &ArgIdx : enumerate(Args)) {
9803     MVT ArgVT = ArgIdx.value().VT;
9804     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9805       return ArgIdx.index();
9806   }
9807   return None;
9808 }
9809 
9810 void RISCVTargetLowering::analyzeInputArgs(
9811     MachineFunction &MF, CCState &CCInfo,
9812     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9813     RISCVCCAssignFn Fn) const {
9814   unsigned NumArgs = Ins.size();
9815   FunctionType *FType = MF.getFunction().getFunctionType();
9816 
9817   Optional<unsigned> FirstMaskArgument;
9818   if (Subtarget.hasVInstructions())
9819     FirstMaskArgument = preAssignMask(Ins);
9820 
9821   for (unsigned i = 0; i != NumArgs; ++i) {
9822     MVT ArgVT = Ins[i].VT;
9823     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9824 
9825     Type *ArgTy = nullptr;
9826     if (IsRet)
9827       ArgTy = FType->getReturnType();
9828     else if (Ins[i].isOrigArg())
9829       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9830 
9831     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9832     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9833            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9834            FirstMaskArgument)) {
9835       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9836                         << EVT(ArgVT).getEVTString() << '\n');
9837       llvm_unreachable(nullptr);
9838     }
9839   }
9840 }
9841 
9842 void RISCVTargetLowering::analyzeOutputArgs(
9843     MachineFunction &MF, CCState &CCInfo,
9844     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9845     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9846   unsigned NumArgs = Outs.size();
9847 
9848   Optional<unsigned> FirstMaskArgument;
9849   if (Subtarget.hasVInstructions())
9850     FirstMaskArgument = preAssignMask(Outs);
9851 
9852   for (unsigned i = 0; i != NumArgs; i++) {
9853     MVT ArgVT = Outs[i].VT;
9854     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9855     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9856 
9857     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9858     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9859            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9860            FirstMaskArgument)) {
9861       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9862                         << EVT(ArgVT).getEVTString() << "\n");
9863       llvm_unreachable(nullptr);
9864     }
9865   }
9866 }
9867 
9868 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9869 // values.
9870 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9871                                    const CCValAssign &VA, const SDLoc &DL,
9872                                    const RISCVSubtarget &Subtarget) {
9873   switch (VA.getLocInfo()) {
9874   default:
9875     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9876   case CCValAssign::Full:
9877     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9878       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9879     break;
9880   case CCValAssign::BCvt:
9881     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9882       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9883     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9884       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9885     else
9886       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9887     break;
9888   }
9889   return Val;
9890 }
9891 
9892 // The caller is responsible for loading the full value if the argument is
9893 // passed with CCValAssign::Indirect.
9894 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9895                                 const CCValAssign &VA, const SDLoc &DL,
9896                                 const RISCVTargetLowering &TLI) {
9897   MachineFunction &MF = DAG.getMachineFunction();
9898   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9899   EVT LocVT = VA.getLocVT();
9900   SDValue Val;
9901   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9902   Register VReg = RegInfo.createVirtualRegister(RC);
9903   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9904   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9905 
9906   if (VA.getLocInfo() == CCValAssign::Indirect)
9907     return Val;
9908 
9909   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9910 }
9911 
9912 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9913                                    const CCValAssign &VA, const SDLoc &DL,
9914                                    const RISCVSubtarget &Subtarget) {
9915   EVT LocVT = VA.getLocVT();
9916 
9917   switch (VA.getLocInfo()) {
9918   default:
9919     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9920   case CCValAssign::Full:
9921     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9922       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9923     break;
9924   case CCValAssign::BCvt:
9925     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9926       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
9927     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9928       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
9929     else
9930       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
9931     break;
9932   }
9933   return Val;
9934 }
9935 
9936 // The caller is responsible for loading the full value if the argument is
9937 // passed with CCValAssign::Indirect.
9938 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
9939                                 const CCValAssign &VA, const SDLoc &DL) {
9940   MachineFunction &MF = DAG.getMachineFunction();
9941   MachineFrameInfo &MFI = MF.getFrameInfo();
9942   EVT LocVT = VA.getLocVT();
9943   EVT ValVT = VA.getValVT();
9944   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
9945   if (ValVT.isScalableVector()) {
9946     // When the value is a scalable vector, we save the pointer which points to
9947     // the scalable vector value in the stack. The ValVT will be the pointer
9948     // type, instead of the scalable vector type.
9949     ValVT = LocVT;
9950   }
9951   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
9952                                  /*IsImmutable=*/true);
9953   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
9954   SDValue Val;
9955 
9956   ISD::LoadExtType ExtType;
9957   switch (VA.getLocInfo()) {
9958   default:
9959     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9960   case CCValAssign::Full:
9961   case CCValAssign::Indirect:
9962   case CCValAssign::BCvt:
9963     ExtType = ISD::NON_EXTLOAD;
9964     break;
9965   }
9966   Val = DAG.getExtLoad(
9967       ExtType, DL, LocVT, Chain, FIN,
9968       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
9969   return Val;
9970 }
9971 
9972 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
9973                                        const CCValAssign &VA, const SDLoc &DL) {
9974   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
9975          "Unexpected VA");
9976   MachineFunction &MF = DAG.getMachineFunction();
9977   MachineFrameInfo &MFI = MF.getFrameInfo();
9978   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9979 
9980   if (VA.isMemLoc()) {
9981     // f64 is passed on the stack.
9982     int FI =
9983         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
9984     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9985     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
9986                        MachinePointerInfo::getFixedStack(MF, FI));
9987   }
9988 
9989   assert(VA.isRegLoc() && "Expected register VA assignment");
9990 
9991   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9992   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
9993   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
9994   SDValue Hi;
9995   if (VA.getLocReg() == RISCV::X17) {
9996     // Second half of f64 is passed on the stack.
9997     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
9998     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9999     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10000                      MachinePointerInfo::getFixedStack(MF, FI));
10001   } else {
10002     // Second half of f64 is passed in another GPR.
10003     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10004     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10005     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10006   }
10007   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10008 }
10009 
10010 // FastCC has less than 1% performance improvement for some particular
10011 // benchmark. But theoretically, it may has benenfit for some cases.
10012 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10013                             unsigned ValNo, MVT ValVT, MVT LocVT,
10014                             CCValAssign::LocInfo LocInfo,
10015                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10016                             bool IsFixed, bool IsRet, Type *OrigTy,
10017                             const RISCVTargetLowering &TLI,
10018                             Optional<unsigned> FirstMaskArgument) {
10019 
10020   // X5 and X6 might be used for save-restore libcall.
10021   static const MCPhysReg GPRList[] = {
10022       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10023       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10024       RISCV::X29, RISCV::X30, RISCV::X31};
10025 
10026   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10027     if (unsigned Reg = State.AllocateReg(GPRList)) {
10028       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10029       return false;
10030     }
10031   }
10032 
10033   if (LocVT == MVT::f16) {
10034     static const MCPhysReg FPR16List[] = {
10035         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10036         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10037         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10038         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10039     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10040       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10041       return false;
10042     }
10043   }
10044 
10045   if (LocVT == MVT::f32) {
10046     static const MCPhysReg FPR32List[] = {
10047         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10048         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10049         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10050         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10051     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10052       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10053       return false;
10054     }
10055   }
10056 
10057   if (LocVT == MVT::f64) {
10058     static const MCPhysReg FPR64List[] = {
10059         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10060         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10061         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10062         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10063     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10064       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10065       return false;
10066     }
10067   }
10068 
10069   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10070     unsigned Offset4 = State.AllocateStack(4, Align(4));
10071     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10072     return false;
10073   }
10074 
10075   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10076     unsigned Offset5 = State.AllocateStack(8, Align(8));
10077     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10078     return false;
10079   }
10080 
10081   if (LocVT.isVector()) {
10082     if (unsigned Reg =
10083             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10084       // Fixed-length vectors are located in the corresponding scalable-vector
10085       // container types.
10086       if (ValVT.isFixedLengthVector())
10087         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10088       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10089     } else {
10090       // Try and pass the address via a "fast" GPR.
10091       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10092         LocInfo = CCValAssign::Indirect;
10093         LocVT = TLI.getSubtarget().getXLenVT();
10094         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10095       } else if (ValVT.isFixedLengthVector()) {
10096         auto StackAlign =
10097             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10098         unsigned StackOffset =
10099             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10100         State.addLoc(
10101             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10102       } else {
10103         // Can't pass scalable vectors on the stack.
10104         return true;
10105       }
10106     }
10107 
10108     return false;
10109   }
10110 
10111   return true; // CC didn't match.
10112 }
10113 
10114 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10115                          CCValAssign::LocInfo LocInfo,
10116                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10117 
10118   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10119     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10120     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10121     static const MCPhysReg GPRList[] = {
10122         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10123         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10124     if (unsigned Reg = State.AllocateReg(GPRList)) {
10125       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10126       return false;
10127     }
10128   }
10129 
10130   if (LocVT == MVT::f32) {
10131     // Pass in STG registers: F1, ..., F6
10132     //                        fs0 ... fs5
10133     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10134                                           RISCV::F18_F, RISCV::F19_F,
10135                                           RISCV::F20_F, RISCV::F21_F};
10136     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10137       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10138       return false;
10139     }
10140   }
10141 
10142   if (LocVT == MVT::f64) {
10143     // Pass in STG registers: D1, ..., D6
10144     //                        fs6 ... fs11
10145     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10146                                           RISCV::F24_D, RISCV::F25_D,
10147                                           RISCV::F26_D, RISCV::F27_D};
10148     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10149       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10150       return false;
10151     }
10152   }
10153 
10154   report_fatal_error("No registers left in GHC calling convention");
10155   return true;
10156 }
10157 
10158 // Transform physical registers into virtual registers.
10159 SDValue RISCVTargetLowering::LowerFormalArguments(
10160     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10161     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10162     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10163 
10164   MachineFunction &MF = DAG.getMachineFunction();
10165 
10166   switch (CallConv) {
10167   default:
10168     report_fatal_error("Unsupported calling convention");
10169   case CallingConv::C:
10170   case CallingConv::Fast:
10171     break;
10172   case CallingConv::GHC:
10173     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10174         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10175       report_fatal_error(
10176         "GHC calling convention requires the F and D instruction set extensions");
10177   }
10178 
10179   const Function &Func = MF.getFunction();
10180   if (Func.hasFnAttribute("interrupt")) {
10181     if (!Func.arg_empty())
10182       report_fatal_error(
10183         "Functions with the interrupt attribute cannot have arguments!");
10184 
10185     StringRef Kind =
10186       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10187 
10188     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10189       report_fatal_error(
10190         "Function interrupt attribute argument not supported!");
10191   }
10192 
10193   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10194   MVT XLenVT = Subtarget.getXLenVT();
10195   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10196   // Used with vargs to acumulate store chains.
10197   std::vector<SDValue> OutChains;
10198 
10199   // Assign locations to all of the incoming arguments.
10200   SmallVector<CCValAssign, 16> ArgLocs;
10201   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10202 
10203   if (CallConv == CallingConv::GHC)
10204     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10205   else
10206     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10207                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10208                                                    : CC_RISCV);
10209 
10210   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10211     CCValAssign &VA = ArgLocs[i];
10212     SDValue ArgValue;
10213     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10214     // case.
10215     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10216       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10217     else if (VA.isRegLoc())
10218       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10219     else
10220       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10221 
10222     if (VA.getLocInfo() == CCValAssign::Indirect) {
10223       // If the original argument was split and passed by reference (e.g. i128
10224       // on RV32), we need to load all parts of it here (using the same
10225       // address). Vectors may be partly split to registers and partly to the
10226       // stack, in which case the base address is partly offset and subsequent
10227       // stores are relative to that.
10228       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10229                                    MachinePointerInfo()));
10230       unsigned ArgIndex = Ins[i].OrigArgIndex;
10231       unsigned ArgPartOffset = Ins[i].PartOffset;
10232       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10233       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10234         CCValAssign &PartVA = ArgLocs[i + 1];
10235         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10236         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10237         if (PartVA.getValVT().isScalableVector())
10238           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10239         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10240         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10241                                      MachinePointerInfo()));
10242         ++i;
10243       }
10244       continue;
10245     }
10246     InVals.push_back(ArgValue);
10247   }
10248 
10249   if (IsVarArg) {
10250     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10251     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10252     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10253     MachineFrameInfo &MFI = MF.getFrameInfo();
10254     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10255     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10256 
10257     // Offset of the first variable argument from stack pointer, and size of
10258     // the vararg save area. For now, the varargs save area is either zero or
10259     // large enough to hold a0-a7.
10260     int VaArgOffset, VarArgsSaveSize;
10261 
10262     // If all registers are allocated, then all varargs must be passed on the
10263     // stack and we don't need to save any argregs.
10264     if (ArgRegs.size() == Idx) {
10265       VaArgOffset = CCInfo.getNextStackOffset();
10266       VarArgsSaveSize = 0;
10267     } else {
10268       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10269       VaArgOffset = -VarArgsSaveSize;
10270     }
10271 
10272     // Record the frame index of the first variable argument
10273     // which is a value necessary to VASTART.
10274     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10275     RVFI->setVarArgsFrameIndex(FI);
10276 
10277     // If saving an odd number of registers then create an extra stack slot to
10278     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10279     // offsets to even-numbered registered remain 2*XLEN-aligned.
10280     if (Idx % 2) {
10281       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10282       VarArgsSaveSize += XLenInBytes;
10283     }
10284 
10285     // Copy the integer registers that may have been used for passing varargs
10286     // to the vararg save area.
10287     for (unsigned I = Idx; I < ArgRegs.size();
10288          ++I, VaArgOffset += XLenInBytes) {
10289       const Register Reg = RegInfo.createVirtualRegister(RC);
10290       RegInfo.addLiveIn(ArgRegs[I], Reg);
10291       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10292       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10293       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10294       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10295                                    MachinePointerInfo::getFixedStack(MF, FI));
10296       cast<StoreSDNode>(Store.getNode())
10297           ->getMemOperand()
10298           ->setValue((Value *)nullptr);
10299       OutChains.push_back(Store);
10300     }
10301     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10302   }
10303 
10304   // All stores are grouped in one node to allow the matching between
10305   // the size of Ins and InVals. This only happens for vararg functions.
10306   if (!OutChains.empty()) {
10307     OutChains.push_back(Chain);
10308     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10309   }
10310 
10311   return Chain;
10312 }
10313 
10314 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10315 /// for tail call optimization.
10316 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10317 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10318     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10319     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10320 
10321   auto &Callee = CLI.Callee;
10322   auto CalleeCC = CLI.CallConv;
10323   auto &Outs = CLI.Outs;
10324   auto &Caller = MF.getFunction();
10325   auto CallerCC = Caller.getCallingConv();
10326 
10327   // Exception-handling functions need a special set of instructions to
10328   // indicate a return to the hardware. Tail-calling another function would
10329   // probably break this.
10330   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10331   // should be expanded as new function attributes are introduced.
10332   if (Caller.hasFnAttribute("interrupt"))
10333     return false;
10334 
10335   // Do not tail call opt if the stack is used to pass parameters.
10336   if (CCInfo.getNextStackOffset() != 0)
10337     return false;
10338 
10339   // Do not tail call opt if any parameters need to be passed indirectly.
10340   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10341   // passed indirectly. So the address of the value will be passed in a
10342   // register, or if not available, then the address is put on the stack. In
10343   // order to pass indirectly, space on the stack often needs to be allocated
10344   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10345   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10346   // are passed CCValAssign::Indirect.
10347   for (auto &VA : ArgLocs)
10348     if (VA.getLocInfo() == CCValAssign::Indirect)
10349       return false;
10350 
10351   // Do not tail call opt if either caller or callee uses struct return
10352   // semantics.
10353   auto IsCallerStructRet = Caller.hasStructRetAttr();
10354   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10355   if (IsCallerStructRet || IsCalleeStructRet)
10356     return false;
10357 
10358   // Externally-defined functions with weak linkage should not be
10359   // tail-called. The behaviour of branch instructions in this situation (as
10360   // used for tail calls) is implementation-defined, so we cannot rely on the
10361   // linker replacing the tail call with a return.
10362   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10363     const GlobalValue *GV = G->getGlobal();
10364     if (GV->hasExternalWeakLinkage())
10365       return false;
10366   }
10367 
10368   // The callee has to preserve all registers the caller needs to preserve.
10369   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10370   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10371   if (CalleeCC != CallerCC) {
10372     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10373     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10374       return false;
10375   }
10376 
10377   // Byval parameters hand the function a pointer directly into the stack area
10378   // we want to reuse during a tail call. Working around this *is* possible
10379   // but less efficient and uglier in LowerCall.
10380   for (auto &Arg : Outs)
10381     if (Arg.Flags.isByVal())
10382       return false;
10383 
10384   return true;
10385 }
10386 
10387 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10388   return DAG.getDataLayout().getPrefTypeAlign(
10389       VT.getTypeForEVT(*DAG.getContext()));
10390 }
10391 
10392 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10393 // and output parameter nodes.
10394 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10395                                        SmallVectorImpl<SDValue> &InVals) const {
10396   SelectionDAG &DAG = CLI.DAG;
10397   SDLoc &DL = CLI.DL;
10398   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10399   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10400   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10401   SDValue Chain = CLI.Chain;
10402   SDValue Callee = CLI.Callee;
10403   bool &IsTailCall = CLI.IsTailCall;
10404   CallingConv::ID CallConv = CLI.CallConv;
10405   bool IsVarArg = CLI.IsVarArg;
10406   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10407   MVT XLenVT = Subtarget.getXLenVT();
10408 
10409   MachineFunction &MF = DAG.getMachineFunction();
10410 
10411   // Analyze the operands of the call, assigning locations to each operand.
10412   SmallVector<CCValAssign, 16> ArgLocs;
10413   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10414 
10415   if (CallConv == CallingConv::GHC)
10416     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10417   else
10418     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10419                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10420                                                     : CC_RISCV);
10421 
10422   // Check if it's really possible to do a tail call.
10423   if (IsTailCall)
10424     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10425 
10426   if (IsTailCall)
10427     ++NumTailCalls;
10428   else if (CLI.CB && CLI.CB->isMustTailCall())
10429     report_fatal_error("failed to perform tail call elimination on a call "
10430                        "site marked musttail");
10431 
10432   // Get a count of how many bytes are to be pushed on the stack.
10433   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10434 
10435   // Create local copies for byval args
10436   SmallVector<SDValue, 8> ByValArgs;
10437   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10438     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10439     if (!Flags.isByVal())
10440       continue;
10441 
10442     SDValue Arg = OutVals[i];
10443     unsigned Size = Flags.getByValSize();
10444     Align Alignment = Flags.getNonZeroByValAlign();
10445 
10446     int FI =
10447         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10448     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10449     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10450 
10451     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10452                           /*IsVolatile=*/false,
10453                           /*AlwaysInline=*/false, IsTailCall,
10454                           MachinePointerInfo(), MachinePointerInfo());
10455     ByValArgs.push_back(FIPtr);
10456   }
10457 
10458   if (!IsTailCall)
10459     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10460 
10461   // Copy argument values to their designated locations.
10462   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10463   SmallVector<SDValue, 8> MemOpChains;
10464   SDValue StackPtr;
10465   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10466     CCValAssign &VA = ArgLocs[i];
10467     SDValue ArgValue = OutVals[i];
10468     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10469 
10470     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10471     bool IsF64OnRV32DSoftABI =
10472         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10473     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10474       SDValue SplitF64 = DAG.getNode(
10475           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10476       SDValue Lo = SplitF64.getValue(0);
10477       SDValue Hi = SplitF64.getValue(1);
10478 
10479       Register RegLo = VA.getLocReg();
10480       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10481 
10482       if (RegLo == RISCV::X17) {
10483         // Second half of f64 is passed on the stack.
10484         // Work out the address of the stack slot.
10485         if (!StackPtr.getNode())
10486           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10487         // Emit the store.
10488         MemOpChains.push_back(
10489             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10490       } else {
10491         // Second half of f64 is passed in another GPR.
10492         assert(RegLo < RISCV::X31 && "Invalid register pair");
10493         Register RegHigh = RegLo + 1;
10494         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10495       }
10496       continue;
10497     }
10498 
10499     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10500     // as any other MemLoc.
10501 
10502     // Promote the value if needed.
10503     // For now, only handle fully promoted and indirect arguments.
10504     if (VA.getLocInfo() == CCValAssign::Indirect) {
10505       // Store the argument in a stack slot and pass its address.
10506       Align StackAlign =
10507           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10508                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10509       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10510       // If the original argument was split (e.g. i128), we need
10511       // to store the required parts of it here (and pass just one address).
10512       // Vectors may be partly split to registers and partly to the stack, in
10513       // which case the base address is partly offset and subsequent stores are
10514       // relative to that.
10515       unsigned ArgIndex = Outs[i].OrigArgIndex;
10516       unsigned ArgPartOffset = Outs[i].PartOffset;
10517       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10518       // Calculate the total size to store. We don't have access to what we're
10519       // actually storing other than performing the loop and collecting the
10520       // info.
10521       SmallVector<std::pair<SDValue, SDValue>> Parts;
10522       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10523         SDValue PartValue = OutVals[i + 1];
10524         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10525         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10526         EVT PartVT = PartValue.getValueType();
10527         if (PartVT.isScalableVector())
10528           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10529         StoredSize += PartVT.getStoreSize();
10530         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10531         Parts.push_back(std::make_pair(PartValue, Offset));
10532         ++i;
10533       }
10534       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10535       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10536       MemOpChains.push_back(
10537           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10538                        MachinePointerInfo::getFixedStack(MF, FI)));
10539       for (const auto &Part : Parts) {
10540         SDValue PartValue = Part.first;
10541         SDValue PartOffset = Part.second;
10542         SDValue Address =
10543             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10544         MemOpChains.push_back(
10545             DAG.getStore(Chain, DL, PartValue, Address,
10546                          MachinePointerInfo::getFixedStack(MF, FI)));
10547       }
10548       ArgValue = SpillSlot;
10549     } else {
10550       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10551     }
10552 
10553     // Use local copy if it is a byval arg.
10554     if (Flags.isByVal())
10555       ArgValue = ByValArgs[j++];
10556 
10557     if (VA.isRegLoc()) {
10558       // Queue up the argument copies and emit them at the end.
10559       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10560     } else {
10561       assert(VA.isMemLoc() && "Argument not register or memory");
10562       assert(!IsTailCall && "Tail call not allowed if stack is used "
10563                             "for passing parameters");
10564 
10565       // Work out the address of the stack slot.
10566       if (!StackPtr.getNode())
10567         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10568       SDValue Address =
10569           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10570                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10571 
10572       // Emit the store.
10573       MemOpChains.push_back(
10574           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10575     }
10576   }
10577 
10578   // Join the stores, which are independent of one another.
10579   if (!MemOpChains.empty())
10580     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10581 
10582   SDValue Glue;
10583 
10584   // Build a sequence of copy-to-reg nodes, chained and glued together.
10585   for (auto &Reg : RegsToPass) {
10586     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10587     Glue = Chain.getValue(1);
10588   }
10589 
10590   // Validate that none of the argument registers have been marked as
10591   // reserved, if so report an error. Do the same for the return address if this
10592   // is not a tailcall.
10593   validateCCReservedRegs(RegsToPass, MF);
10594   if (!IsTailCall &&
10595       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10596     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10597         MF.getFunction(),
10598         "Return address register required, but has been reserved."});
10599 
10600   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10601   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10602   // split it and then direct call can be matched by PseudoCALL.
10603   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10604     const GlobalValue *GV = S->getGlobal();
10605 
10606     unsigned OpFlags = RISCVII::MO_CALL;
10607     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10608       OpFlags = RISCVII::MO_PLT;
10609 
10610     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10611   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10612     unsigned OpFlags = RISCVII::MO_CALL;
10613 
10614     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10615                                                  nullptr))
10616       OpFlags = RISCVII::MO_PLT;
10617 
10618     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10619   }
10620 
10621   // The first call operand is the chain and the second is the target address.
10622   SmallVector<SDValue, 8> Ops;
10623   Ops.push_back(Chain);
10624   Ops.push_back(Callee);
10625 
10626   // Add argument registers to the end of the list so that they are
10627   // known live into the call.
10628   for (auto &Reg : RegsToPass)
10629     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10630 
10631   if (!IsTailCall) {
10632     // Add a register mask operand representing the call-preserved registers.
10633     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10634     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10635     assert(Mask && "Missing call preserved mask for calling convention");
10636     Ops.push_back(DAG.getRegisterMask(Mask));
10637   }
10638 
10639   // Glue the call to the argument copies, if any.
10640   if (Glue.getNode())
10641     Ops.push_back(Glue);
10642 
10643   // Emit the call.
10644   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10645 
10646   if (IsTailCall) {
10647     MF.getFrameInfo().setHasTailCall();
10648     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10649   }
10650 
10651   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10652   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10653   Glue = Chain.getValue(1);
10654 
10655   // Mark the end of the call, which is glued to the call itself.
10656   Chain = DAG.getCALLSEQ_END(Chain,
10657                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10658                              DAG.getConstant(0, DL, PtrVT, true),
10659                              Glue, DL);
10660   Glue = Chain.getValue(1);
10661 
10662   // Assign locations to each value returned by this call.
10663   SmallVector<CCValAssign, 16> RVLocs;
10664   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10665   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10666 
10667   // Copy all of the result registers out of their specified physreg.
10668   for (auto &VA : RVLocs) {
10669     // Copy the value out
10670     SDValue RetValue =
10671         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10672     // Glue the RetValue to the end of the call sequence
10673     Chain = RetValue.getValue(1);
10674     Glue = RetValue.getValue(2);
10675 
10676     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10677       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10678       SDValue RetValue2 =
10679           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10680       Chain = RetValue2.getValue(1);
10681       Glue = RetValue2.getValue(2);
10682       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10683                              RetValue2);
10684     }
10685 
10686     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10687 
10688     InVals.push_back(RetValue);
10689   }
10690 
10691   return Chain;
10692 }
10693 
10694 bool RISCVTargetLowering::CanLowerReturn(
10695     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10696     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10697   SmallVector<CCValAssign, 16> RVLocs;
10698   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10699 
10700   Optional<unsigned> FirstMaskArgument;
10701   if (Subtarget.hasVInstructions())
10702     FirstMaskArgument = preAssignMask(Outs);
10703 
10704   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10705     MVT VT = Outs[i].VT;
10706     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10707     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10708     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10709                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10710                  *this, FirstMaskArgument))
10711       return false;
10712   }
10713   return true;
10714 }
10715 
10716 SDValue
10717 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10718                                  bool IsVarArg,
10719                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10720                                  const SmallVectorImpl<SDValue> &OutVals,
10721                                  const SDLoc &DL, SelectionDAG &DAG) const {
10722   const MachineFunction &MF = DAG.getMachineFunction();
10723   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10724 
10725   // Stores the assignment of the return value to a location.
10726   SmallVector<CCValAssign, 16> RVLocs;
10727 
10728   // Info about the registers and stack slot.
10729   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10730                  *DAG.getContext());
10731 
10732   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10733                     nullptr, CC_RISCV);
10734 
10735   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10736     report_fatal_error("GHC functions return void only");
10737 
10738   SDValue Glue;
10739   SmallVector<SDValue, 4> RetOps(1, Chain);
10740 
10741   // Copy the result values into the output registers.
10742   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10743     SDValue Val = OutVals[i];
10744     CCValAssign &VA = RVLocs[i];
10745     assert(VA.isRegLoc() && "Can only return in registers!");
10746 
10747     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10748       // Handle returning f64 on RV32D with a soft float ABI.
10749       assert(VA.isRegLoc() && "Expected return via registers");
10750       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10751                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10752       SDValue Lo = SplitF64.getValue(0);
10753       SDValue Hi = SplitF64.getValue(1);
10754       Register RegLo = VA.getLocReg();
10755       assert(RegLo < RISCV::X31 && "Invalid register pair");
10756       Register RegHi = RegLo + 1;
10757 
10758       if (STI.isRegisterReservedByUser(RegLo) ||
10759           STI.isRegisterReservedByUser(RegHi))
10760         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10761             MF.getFunction(),
10762             "Return value register required, but has been reserved."});
10763 
10764       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10765       Glue = Chain.getValue(1);
10766       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10767       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10768       Glue = Chain.getValue(1);
10769       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10770     } else {
10771       // Handle a 'normal' return.
10772       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10773       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10774 
10775       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10776         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10777             MF.getFunction(),
10778             "Return value register required, but has been reserved."});
10779 
10780       // Guarantee that all emitted copies are stuck together.
10781       Glue = Chain.getValue(1);
10782       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10783     }
10784   }
10785 
10786   RetOps[0] = Chain; // Update chain.
10787 
10788   // Add the glue node if we have it.
10789   if (Glue.getNode()) {
10790     RetOps.push_back(Glue);
10791   }
10792 
10793   unsigned RetOpc = RISCVISD::RET_FLAG;
10794   // Interrupt service routines use different return instructions.
10795   const Function &Func = DAG.getMachineFunction().getFunction();
10796   if (Func.hasFnAttribute("interrupt")) {
10797     if (!Func.getReturnType()->isVoidTy())
10798       report_fatal_error(
10799           "Functions with the interrupt attribute must have void return type!");
10800 
10801     MachineFunction &MF = DAG.getMachineFunction();
10802     StringRef Kind =
10803       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10804 
10805     if (Kind == "user")
10806       RetOpc = RISCVISD::URET_FLAG;
10807     else if (Kind == "supervisor")
10808       RetOpc = RISCVISD::SRET_FLAG;
10809     else
10810       RetOpc = RISCVISD::MRET_FLAG;
10811   }
10812 
10813   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10814 }
10815 
10816 void RISCVTargetLowering::validateCCReservedRegs(
10817     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10818     MachineFunction &MF) const {
10819   const Function &F = MF.getFunction();
10820   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10821 
10822   if (llvm::any_of(Regs, [&STI](auto Reg) {
10823         return STI.isRegisterReservedByUser(Reg.first);
10824       }))
10825     F.getContext().diagnose(DiagnosticInfoUnsupported{
10826         F, "Argument register required, but has been reserved."});
10827 }
10828 
10829 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10830   return CI->isTailCall();
10831 }
10832 
10833 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10834 #define NODE_NAME_CASE(NODE)                                                   \
10835   case RISCVISD::NODE:                                                         \
10836     return "RISCVISD::" #NODE;
10837   // clang-format off
10838   switch ((RISCVISD::NodeType)Opcode) {
10839   case RISCVISD::FIRST_NUMBER:
10840     break;
10841   NODE_NAME_CASE(RET_FLAG)
10842   NODE_NAME_CASE(URET_FLAG)
10843   NODE_NAME_CASE(SRET_FLAG)
10844   NODE_NAME_CASE(MRET_FLAG)
10845   NODE_NAME_CASE(CALL)
10846   NODE_NAME_CASE(SELECT_CC)
10847   NODE_NAME_CASE(BR_CC)
10848   NODE_NAME_CASE(BuildPairF64)
10849   NODE_NAME_CASE(SplitF64)
10850   NODE_NAME_CASE(TAIL)
10851   NODE_NAME_CASE(MULHSU)
10852   NODE_NAME_CASE(SLLW)
10853   NODE_NAME_CASE(SRAW)
10854   NODE_NAME_CASE(SRLW)
10855   NODE_NAME_CASE(DIVW)
10856   NODE_NAME_CASE(DIVUW)
10857   NODE_NAME_CASE(REMUW)
10858   NODE_NAME_CASE(ROLW)
10859   NODE_NAME_CASE(RORW)
10860   NODE_NAME_CASE(CLZW)
10861   NODE_NAME_CASE(CTZW)
10862   NODE_NAME_CASE(FSLW)
10863   NODE_NAME_CASE(FSRW)
10864   NODE_NAME_CASE(FSL)
10865   NODE_NAME_CASE(FSR)
10866   NODE_NAME_CASE(FMV_H_X)
10867   NODE_NAME_CASE(FMV_X_ANYEXTH)
10868   NODE_NAME_CASE(FMV_X_SIGNEXTH)
10869   NODE_NAME_CASE(FMV_W_X_RV64)
10870   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10871   NODE_NAME_CASE(FCVT_X)
10872   NODE_NAME_CASE(FCVT_XU)
10873   NODE_NAME_CASE(FCVT_W_RV64)
10874   NODE_NAME_CASE(FCVT_WU_RV64)
10875   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10876   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10877   NODE_NAME_CASE(READ_CYCLE_WIDE)
10878   NODE_NAME_CASE(GREV)
10879   NODE_NAME_CASE(GREVW)
10880   NODE_NAME_CASE(GORC)
10881   NODE_NAME_CASE(GORCW)
10882   NODE_NAME_CASE(SHFL)
10883   NODE_NAME_CASE(SHFLW)
10884   NODE_NAME_CASE(UNSHFL)
10885   NODE_NAME_CASE(UNSHFLW)
10886   NODE_NAME_CASE(BFP)
10887   NODE_NAME_CASE(BFPW)
10888   NODE_NAME_CASE(BCOMPRESS)
10889   NODE_NAME_CASE(BCOMPRESSW)
10890   NODE_NAME_CASE(BDECOMPRESS)
10891   NODE_NAME_CASE(BDECOMPRESSW)
10892   NODE_NAME_CASE(VMV_V_X_VL)
10893   NODE_NAME_CASE(VFMV_V_F_VL)
10894   NODE_NAME_CASE(VMV_X_S)
10895   NODE_NAME_CASE(VMV_S_X_VL)
10896   NODE_NAME_CASE(VFMV_S_F_VL)
10897   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10898   NODE_NAME_CASE(READ_VLENB)
10899   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10900   NODE_NAME_CASE(VSLIDEUP_VL)
10901   NODE_NAME_CASE(VSLIDE1UP_VL)
10902   NODE_NAME_CASE(VSLIDEDOWN_VL)
10903   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10904   NODE_NAME_CASE(VID_VL)
10905   NODE_NAME_CASE(VFNCVT_ROD_VL)
10906   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10907   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10908   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10909   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10910   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10911   NODE_NAME_CASE(VECREDUCE_AND_VL)
10912   NODE_NAME_CASE(VECREDUCE_OR_VL)
10913   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10914   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10915   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10916   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10917   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10918   NODE_NAME_CASE(ADD_VL)
10919   NODE_NAME_CASE(AND_VL)
10920   NODE_NAME_CASE(MUL_VL)
10921   NODE_NAME_CASE(OR_VL)
10922   NODE_NAME_CASE(SDIV_VL)
10923   NODE_NAME_CASE(SHL_VL)
10924   NODE_NAME_CASE(SREM_VL)
10925   NODE_NAME_CASE(SRA_VL)
10926   NODE_NAME_CASE(SRL_VL)
10927   NODE_NAME_CASE(SUB_VL)
10928   NODE_NAME_CASE(UDIV_VL)
10929   NODE_NAME_CASE(UREM_VL)
10930   NODE_NAME_CASE(XOR_VL)
10931   NODE_NAME_CASE(SADDSAT_VL)
10932   NODE_NAME_CASE(UADDSAT_VL)
10933   NODE_NAME_CASE(SSUBSAT_VL)
10934   NODE_NAME_CASE(USUBSAT_VL)
10935   NODE_NAME_CASE(FADD_VL)
10936   NODE_NAME_CASE(FSUB_VL)
10937   NODE_NAME_CASE(FMUL_VL)
10938   NODE_NAME_CASE(FDIV_VL)
10939   NODE_NAME_CASE(FNEG_VL)
10940   NODE_NAME_CASE(FABS_VL)
10941   NODE_NAME_CASE(FSQRT_VL)
10942   NODE_NAME_CASE(FMA_VL)
10943   NODE_NAME_CASE(FCOPYSIGN_VL)
10944   NODE_NAME_CASE(SMIN_VL)
10945   NODE_NAME_CASE(SMAX_VL)
10946   NODE_NAME_CASE(UMIN_VL)
10947   NODE_NAME_CASE(UMAX_VL)
10948   NODE_NAME_CASE(FMINNUM_VL)
10949   NODE_NAME_CASE(FMAXNUM_VL)
10950   NODE_NAME_CASE(MULHS_VL)
10951   NODE_NAME_CASE(MULHU_VL)
10952   NODE_NAME_CASE(FP_TO_SINT_VL)
10953   NODE_NAME_CASE(FP_TO_UINT_VL)
10954   NODE_NAME_CASE(SINT_TO_FP_VL)
10955   NODE_NAME_CASE(UINT_TO_FP_VL)
10956   NODE_NAME_CASE(FP_EXTEND_VL)
10957   NODE_NAME_CASE(FP_ROUND_VL)
10958   NODE_NAME_CASE(VWMUL_VL)
10959   NODE_NAME_CASE(VWMULU_VL)
10960   NODE_NAME_CASE(VWMULSU_VL)
10961   NODE_NAME_CASE(VWADD_VL)
10962   NODE_NAME_CASE(VWADDU_VL)
10963   NODE_NAME_CASE(VWSUB_VL)
10964   NODE_NAME_CASE(VWSUBU_VL)
10965   NODE_NAME_CASE(VWADD_W_VL)
10966   NODE_NAME_CASE(VWADDU_W_VL)
10967   NODE_NAME_CASE(VWSUB_W_VL)
10968   NODE_NAME_CASE(VWSUBU_W_VL)
10969   NODE_NAME_CASE(SETCC_VL)
10970   NODE_NAME_CASE(VSELECT_VL)
10971   NODE_NAME_CASE(VP_MERGE_VL)
10972   NODE_NAME_CASE(VMAND_VL)
10973   NODE_NAME_CASE(VMOR_VL)
10974   NODE_NAME_CASE(VMXOR_VL)
10975   NODE_NAME_CASE(VMCLR_VL)
10976   NODE_NAME_CASE(VMSET_VL)
10977   NODE_NAME_CASE(VRGATHER_VX_VL)
10978   NODE_NAME_CASE(VRGATHER_VV_VL)
10979   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
10980   NODE_NAME_CASE(VSEXT_VL)
10981   NODE_NAME_CASE(VZEXT_VL)
10982   NODE_NAME_CASE(VCPOP_VL)
10983   NODE_NAME_CASE(READ_CSR)
10984   NODE_NAME_CASE(WRITE_CSR)
10985   NODE_NAME_CASE(SWAP_CSR)
10986   }
10987   // clang-format on
10988   return nullptr;
10989 #undef NODE_NAME_CASE
10990 }
10991 
10992 /// getConstraintType - Given a constraint letter, return the type of
10993 /// constraint it is for this target.
10994 RISCVTargetLowering::ConstraintType
10995 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
10996   if (Constraint.size() == 1) {
10997     switch (Constraint[0]) {
10998     default:
10999       break;
11000     case 'f':
11001       return C_RegisterClass;
11002     case 'I':
11003     case 'J':
11004     case 'K':
11005       return C_Immediate;
11006     case 'A':
11007       return C_Memory;
11008     case 'S': // A symbolic address
11009       return C_Other;
11010     }
11011   } else {
11012     if (Constraint == "vr" || Constraint == "vm")
11013       return C_RegisterClass;
11014   }
11015   return TargetLowering::getConstraintType(Constraint);
11016 }
11017 
11018 std::pair<unsigned, const TargetRegisterClass *>
11019 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11020                                                   StringRef Constraint,
11021                                                   MVT VT) const {
11022   // First, see if this is a constraint that directly corresponds to a
11023   // RISCV register class.
11024   if (Constraint.size() == 1) {
11025     switch (Constraint[0]) {
11026     case 'r':
11027       // TODO: Support fixed vectors up to XLen for P extension?
11028       if (VT.isVector())
11029         break;
11030       return std::make_pair(0U, &RISCV::GPRRegClass);
11031     case 'f':
11032       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11033         return std::make_pair(0U, &RISCV::FPR16RegClass);
11034       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11035         return std::make_pair(0U, &RISCV::FPR32RegClass);
11036       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11037         return std::make_pair(0U, &RISCV::FPR64RegClass);
11038       break;
11039     default:
11040       break;
11041     }
11042   } else if (Constraint == "vr") {
11043     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11044                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11045       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11046         return std::make_pair(0U, RC);
11047     }
11048   } else if (Constraint == "vm") {
11049     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11050       return std::make_pair(0U, &RISCV::VMV0RegClass);
11051   }
11052 
11053   // Clang will correctly decode the usage of register name aliases into their
11054   // official names. However, other frontends like `rustc` do not. This allows
11055   // users of these frontends to use the ABI names for registers in LLVM-style
11056   // register constraints.
11057   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11058                                .Case("{zero}", RISCV::X0)
11059                                .Case("{ra}", RISCV::X1)
11060                                .Case("{sp}", RISCV::X2)
11061                                .Case("{gp}", RISCV::X3)
11062                                .Case("{tp}", RISCV::X4)
11063                                .Case("{t0}", RISCV::X5)
11064                                .Case("{t1}", RISCV::X6)
11065                                .Case("{t2}", RISCV::X7)
11066                                .Cases("{s0}", "{fp}", RISCV::X8)
11067                                .Case("{s1}", RISCV::X9)
11068                                .Case("{a0}", RISCV::X10)
11069                                .Case("{a1}", RISCV::X11)
11070                                .Case("{a2}", RISCV::X12)
11071                                .Case("{a3}", RISCV::X13)
11072                                .Case("{a4}", RISCV::X14)
11073                                .Case("{a5}", RISCV::X15)
11074                                .Case("{a6}", RISCV::X16)
11075                                .Case("{a7}", RISCV::X17)
11076                                .Case("{s2}", RISCV::X18)
11077                                .Case("{s3}", RISCV::X19)
11078                                .Case("{s4}", RISCV::X20)
11079                                .Case("{s5}", RISCV::X21)
11080                                .Case("{s6}", RISCV::X22)
11081                                .Case("{s7}", RISCV::X23)
11082                                .Case("{s8}", RISCV::X24)
11083                                .Case("{s9}", RISCV::X25)
11084                                .Case("{s10}", RISCV::X26)
11085                                .Case("{s11}", RISCV::X27)
11086                                .Case("{t3}", RISCV::X28)
11087                                .Case("{t4}", RISCV::X29)
11088                                .Case("{t5}", RISCV::X30)
11089                                .Case("{t6}", RISCV::X31)
11090                                .Default(RISCV::NoRegister);
11091   if (XRegFromAlias != RISCV::NoRegister)
11092     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11093 
11094   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11095   // TableGen record rather than the AsmName to choose registers for InlineAsm
11096   // constraints, plus we want to match those names to the widest floating point
11097   // register type available, manually select floating point registers here.
11098   //
11099   // The second case is the ABI name of the register, so that frontends can also
11100   // use the ABI names in register constraint lists.
11101   if (Subtarget.hasStdExtF()) {
11102     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11103                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11104                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11105                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11106                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11107                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11108                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11109                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11110                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11111                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11112                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11113                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11114                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11115                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11116                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11117                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11118                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11119                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11120                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11121                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11122                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11123                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11124                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11125                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11126                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11127                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11128                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11129                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11130                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11131                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11132                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11133                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11134                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11135                         .Default(RISCV::NoRegister);
11136     if (FReg != RISCV::NoRegister) {
11137       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11138       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11139         unsigned RegNo = FReg - RISCV::F0_F;
11140         unsigned DReg = RISCV::F0_D + RegNo;
11141         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11142       }
11143       if (VT == MVT::f32 || VT == MVT::Other)
11144         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11145       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11146         unsigned RegNo = FReg - RISCV::F0_F;
11147         unsigned HReg = RISCV::F0_H + RegNo;
11148         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11149       }
11150     }
11151   }
11152 
11153   if (Subtarget.hasVInstructions()) {
11154     Register VReg = StringSwitch<Register>(Constraint.lower())
11155                         .Case("{v0}", RISCV::V0)
11156                         .Case("{v1}", RISCV::V1)
11157                         .Case("{v2}", RISCV::V2)
11158                         .Case("{v3}", RISCV::V3)
11159                         .Case("{v4}", RISCV::V4)
11160                         .Case("{v5}", RISCV::V5)
11161                         .Case("{v6}", RISCV::V6)
11162                         .Case("{v7}", RISCV::V7)
11163                         .Case("{v8}", RISCV::V8)
11164                         .Case("{v9}", RISCV::V9)
11165                         .Case("{v10}", RISCV::V10)
11166                         .Case("{v11}", RISCV::V11)
11167                         .Case("{v12}", RISCV::V12)
11168                         .Case("{v13}", RISCV::V13)
11169                         .Case("{v14}", RISCV::V14)
11170                         .Case("{v15}", RISCV::V15)
11171                         .Case("{v16}", RISCV::V16)
11172                         .Case("{v17}", RISCV::V17)
11173                         .Case("{v18}", RISCV::V18)
11174                         .Case("{v19}", RISCV::V19)
11175                         .Case("{v20}", RISCV::V20)
11176                         .Case("{v21}", RISCV::V21)
11177                         .Case("{v22}", RISCV::V22)
11178                         .Case("{v23}", RISCV::V23)
11179                         .Case("{v24}", RISCV::V24)
11180                         .Case("{v25}", RISCV::V25)
11181                         .Case("{v26}", RISCV::V26)
11182                         .Case("{v27}", RISCV::V27)
11183                         .Case("{v28}", RISCV::V28)
11184                         .Case("{v29}", RISCV::V29)
11185                         .Case("{v30}", RISCV::V30)
11186                         .Case("{v31}", RISCV::V31)
11187                         .Default(RISCV::NoRegister);
11188     if (VReg != RISCV::NoRegister) {
11189       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11190         return std::make_pair(VReg, &RISCV::VMRegClass);
11191       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11192         return std::make_pair(VReg, &RISCV::VRRegClass);
11193       for (const auto *RC :
11194            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11195         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11196           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11197           return std::make_pair(VReg, RC);
11198         }
11199       }
11200     }
11201   }
11202 
11203   std::pair<Register, const TargetRegisterClass *> Res =
11204       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11205 
11206   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11207   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11208   // Subtarget into account.
11209   if (Res.second == &RISCV::GPRF16RegClass ||
11210       Res.second == &RISCV::GPRF32RegClass ||
11211       Res.second == &RISCV::GPRF64RegClass)
11212     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11213 
11214   return Res;
11215 }
11216 
11217 unsigned
11218 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11219   // Currently only support length 1 constraints.
11220   if (ConstraintCode.size() == 1) {
11221     switch (ConstraintCode[0]) {
11222     case 'A':
11223       return InlineAsm::Constraint_A;
11224     default:
11225       break;
11226     }
11227   }
11228 
11229   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11230 }
11231 
11232 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11233     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11234     SelectionDAG &DAG) const {
11235   // Currently only support length 1 constraints.
11236   if (Constraint.length() == 1) {
11237     switch (Constraint[0]) {
11238     case 'I':
11239       // Validate & create a 12-bit signed immediate operand.
11240       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11241         uint64_t CVal = C->getSExtValue();
11242         if (isInt<12>(CVal))
11243           Ops.push_back(
11244               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11245       }
11246       return;
11247     case 'J':
11248       // Validate & create an integer zero operand.
11249       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11250         if (C->getZExtValue() == 0)
11251           Ops.push_back(
11252               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11253       return;
11254     case 'K':
11255       // Validate & create a 5-bit unsigned immediate operand.
11256       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11257         uint64_t CVal = C->getZExtValue();
11258         if (isUInt<5>(CVal))
11259           Ops.push_back(
11260               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11261       }
11262       return;
11263     case 'S':
11264       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11265         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11266                                                  GA->getValueType(0)));
11267       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11268         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11269                                                 BA->getValueType(0)));
11270       }
11271       return;
11272     default:
11273       break;
11274     }
11275   }
11276   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11277 }
11278 
11279 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11280                                                    Instruction *Inst,
11281                                                    AtomicOrdering Ord) const {
11282   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11283     return Builder.CreateFence(Ord);
11284   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11285     return Builder.CreateFence(AtomicOrdering::Release);
11286   return nullptr;
11287 }
11288 
11289 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11290                                                     Instruction *Inst,
11291                                                     AtomicOrdering Ord) const {
11292   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11293     return Builder.CreateFence(AtomicOrdering::Acquire);
11294   return nullptr;
11295 }
11296 
11297 TargetLowering::AtomicExpansionKind
11298 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11299   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11300   // point operations can't be used in an lr/sc sequence without breaking the
11301   // forward-progress guarantee.
11302   if (AI->isFloatingPointOperation())
11303     return AtomicExpansionKind::CmpXChg;
11304 
11305   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11306   if (Size == 8 || Size == 16)
11307     return AtomicExpansionKind::MaskedIntrinsic;
11308   return AtomicExpansionKind::None;
11309 }
11310 
11311 static Intrinsic::ID
11312 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11313   if (XLen == 32) {
11314     switch (BinOp) {
11315     default:
11316       llvm_unreachable("Unexpected AtomicRMW BinOp");
11317     case AtomicRMWInst::Xchg:
11318       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11319     case AtomicRMWInst::Add:
11320       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11321     case AtomicRMWInst::Sub:
11322       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11323     case AtomicRMWInst::Nand:
11324       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11325     case AtomicRMWInst::Max:
11326       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11327     case AtomicRMWInst::Min:
11328       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11329     case AtomicRMWInst::UMax:
11330       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11331     case AtomicRMWInst::UMin:
11332       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11333     }
11334   }
11335 
11336   if (XLen == 64) {
11337     switch (BinOp) {
11338     default:
11339       llvm_unreachable("Unexpected AtomicRMW BinOp");
11340     case AtomicRMWInst::Xchg:
11341       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11342     case AtomicRMWInst::Add:
11343       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11344     case AtomicRMWInst::Sub:
11345       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11346     case AtomicRMWInst::Nand:
11347       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11348     case AtomicRMWInst::Max:
11349       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11350     case AtomicRMWInst::Min:
11351       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11352     case AtomicRMWInst::UMax:
11353       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11354     case AtomicRMWInst::UMin:
11355       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11356     }
11357   }
11358 
11359   llvm_unreachable("Unexpected XLen\n");
11360 }
11361 
11362 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11363     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11364     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11365   unsigned XLen = Subtarget.getXLen();
11366   Value *Ordering =
11367       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11368   Type *Tys[] = {AlignedAddr->getType()};
11369   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11370       AI->getModule(),
11371       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11372 
11373   if (XLen == 64) {
11374     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11375     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11376     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11377   }
11378 
11379   Value *Result;
11380 
11381   // Must pass the shift amount needed to sign extend the loaded value prior
11382   // to performing a signed comparison for min/max. ShiftAmt is the number of
11383   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11384   // is the number of bits to left+right shift the value in order to
11385   // sign-extend.
11386   if (AI->getOperation() == AtomicRMWInst::Min ||
11387       AI->getOperation() == AtomicRMWInst::Max) {
11388     const DataLayout &DL = AI->getModule()->getDataLayout();
11389     unsigned ValWidth =
11390         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11391     Value *SextShamt =
11392         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11393     Result = Builder.CreateCall(LrwOpScwLoop,
11394                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11395   } else {
11396     Result =
11397         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11398   }
11399 
11400   if (XLen == 64)
11401     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11402   return Result;
11403 }
11404 
11405 TargetLowering::AtomicExpansionKind
11406 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11407     AtomicCmpXchgInst *CI) const {
11408   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11409   if (Size == 8 || Size == 16)
11410     return AtomicExpansionKind::MaskedIntrinsic;
11411   return AtomicExpansionKind::None;
11412 }
11413 
11414 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11415     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11416     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11417   unsigned XLen = Subtarget.getXLen();
11418   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11419   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11420   if (XLen == 64) {
11421     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11422     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11423     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11424     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11425   }
11426   Type *Tys[] = {AlignedAddr->getType()};
11427   Function *MaskedCmpXchg =
11428       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11429   Value *Result = Builder.CreateCall(
11430       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11431   if (XLen == 64)
11432     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11433   return Result;
11434 }
11435 
11436 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
11437   return false;
11438 }
11439 
11440 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11441                                                EVT VT) const {
11442   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11443     return false;
11444 
11445   switch (FPVT.getSimpleVT().SimpleTy) {
11446   case MVT::f16:
11447     return Subtarget.hasStdExtZfh();
11448   case MVT::f32:
11449     return Subtarget.hasStdExtF();
11450   case MVT::f64:
11451     return Subtarget.hasStdExtD();
11452   default:
11453     return false;
11454   }
11455 }
11456 
11457 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11458   // If we are using the small code model, we can reduce size of jump table
11459   // entry to 4 bytes.
11460   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11461       getTargetMachine().getCodeModel() == CodeModel::Small) {
11462     return MachineJumpTableInfo::EK_Custom32;
11463   }
11464   return TargetLowering::getJumpTableEncoding();
11465 }
11466 
11467 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11468     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11469     unsigned uid, MCContext &Ctx) const {
11470   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11471          getTargetMachine().getCodeModel() == CodeModel::Small);
11472   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11473 }
11474 
11475 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11476                                                      EVT VT) const {
11477   VT = VT.getScalarType();
11478 
11479   if (!VT.isSimple())
11480     return false;
11481 
11482   switch (VT.getSimpleVT().SimpleTy) {
11483   case MVT::f16:
11484     return Subtarget.hasStdExtZfh();
11485   case MVT::f32:
11486     return Subtarget.hasStdExtF();
11487   case MVT::f64:
11488     return Subtarget.hasStdExtD();
11489   default:
11490     break;
11491   }
11492 
11493   return false;
11494 }
11495 
11496 Register RISCVTargetLowering::getExceptionPointerRegister(
11497     const Constant *PersonalityFn) const {
11498   return RISCV::X10;
11499 }
11500 
11501 Register RISCVTargetLowering::getExceptionSelectorRegister(
11502     const Constant *PersonalityFn) const {
11503   return RISCV::X11;
11504 }
11505 
11506 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11507   // Return false to suppress the unnecessary extensions if the LibCall
11508   // arguments or return value is f32 type for LP64 ABI.
11509   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11510   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11511     return false;
11512 
11513   return true;
11514 }
11515 
11516 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11517   if (Subtarget.is64Bit() && Type == MVT::i32)
11518     return true;
11519 
11520   return IsSigned;
11521 }
11522 
11523 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11524                                                  SDValue C) const {
11525   // Check integral scalar types.
11526   if (VT.isScalarInteger()) {
11527     // Omit the optimization if the sub target has the M extension and the data
11528     // size exceeds XLen.
11529     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11530       return false;
11531     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11532       // Break the MUL to a SLLI and an ADD/SUB.
11533       const APInt &Imm = ConstNode->getAPIntValue();
11534       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11535           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11536         return true;
11537       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11538       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11539           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11540            (Imm - 8).isPowerOf2()))
11541         return true;
11542       // Omit the following optimization if the sub target has the M extension
11543       // and the data size >= XLen.
11544       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11545         return false;
11546       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11547       // a pair of LUI/ADDI.
11548       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11549         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11550         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11551             (1 - ImmS).isPowerOf2())
11552         return true;
11553       }
11554     }
11555   }
11556 
11557   return false;
11558 }
11559 
11560 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
11561                                                       SDValue ConstNode) const {
11562   // Let the DAGCombiner decide for vectors.
11563   EVT VT = AddNode.getValueType();
11564   if (VT.isVector())
11565     return true;
11566 
11567   // Let the DAGCombiner decide for larger types.
11568   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11569     return true;
11570 
11571   // It is worse if c1 is simm12 while c1*c2 is not.
11572   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11573   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11574   const APInt &C1 = C1Node->getAPIntValue();
11575   const APInt &C2 = C2Node->getAPIntValue();
11576   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11577     return false;
11578 
11579   // Default to true and let the DAGCombiner decide.
11580   return true;
11581 }
11582 
11583 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11584     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11585     bool *Fast) const {
11586   if (!VT.isVector())
11587     return false;
11588 
11589   EVT ElemVT = VT.getVectorElementType();
11590   if (Alignment >= ElemVT.getStoreSize()) {
11591     if (Fast)
11592       *Fast = true;
11593     return true;
11594   }
11595 
11596   return false;
11597 }
11598 
11599 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11600     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11601     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11602   bool IsABIRegCopy = CC.hasValue();
11603   EVT ValueVT = Val.getValueType();
11604   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11605     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11606     // and cast to f32.
11607     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11608     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11609     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11610                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11611     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11612     Parts[0] = Val;
11613     return true;
11614   }
11615 
11616   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11617     LLVMContext &Context = *DAG.getContext();
11618     EVT ValueEltVT = ValueVT.getVectorElementType();
11619     EVT PartEltVT = PartVT.getVectorElementType();
11620     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11621     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11622     if (PartVTBitSize % ValueVTBitSize == 0) {
11623       assert(PartVTBitSize >= ValueVTBitSize);
11624       // If the element types are different, bitcast to the same element type of
11625       // PartVT first.
11626       // Give an example here, we want copy a <vscale x 1 x i8> value to
11627       // <vscale x 4 x i16>.
11628       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11629       // subvector, then we can bitcast to <vscale x 4 x i16>.
11630       if (ValueEltVT != PartEltVT) {
11631         if (PartVTBitSize > ValueVTBitSize) {
11632           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11633           assert(Count != 0 && "The number of element should not be zero.");
11634           EVT SameEltTypeVT =
11635               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11636           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11637                             DAG.getUNDEF(SameEltTypeVT), Val,
11638                             DAG.getVectorIdxConstant(0, DL));
11639         }
11640         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11641       } else {
11642         Val =
11643             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11644                         Val, DAG.getVectorIdxConstant(0, DL));
11645       }
11646       Parts[0] = Val;
11647       return true;
11648     }
11649   }
11650   return false;
11651 }
11652 
11653 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11654     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11655     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11656   bool IsABIRegCopy = CC.hasValue();
11657   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11658     SDValue Val = Parts[0];
11659 
11660     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11661     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11662     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11663     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11664     return Val;
11665   }
11666 
11667   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11668     LLVMContext &Context = *DAG.getContext();
11669     SDValue Val = Parts[0];
11670     EVT ValueEltVT = ValueVT.getVectorElementType();
11671     EVT PartEltVT = PartVT.getVectorElementType();
11672     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11673     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11674     if (PartVTBitSize % ValueVTBitSize == 0) {
11675       assert(PartVTBitSize >= ValueVTBitSize);
11676       EVT SameEltTypeVT = ValueVT;
11677       // If the element types are different, convert it to the same element type
11678       // of PartVT.
11679       // Give an example here, we want copy a <vscale x 1 x i8> value from
11680       // <vscale x 4 x i16>.
11681       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11682       // then we can extract <vscale x 1 x i8>.
11683       if (ValueEltVT != PartEltVT) {
11684         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11685         assert(Count != 0 && "The number of element should not be zero.");
11686         SameEltTypeVT =
11687             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11688         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11689       }
11690       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11691                         DAG.getVectorIdxConstant(0, DL));
11692       return Val;
11693     }
11694   }
11695   return SDValue();
11696 }
11697 
11698 SDValue
11699 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11700                                    SelectionDAG &DAG,
11701                                    SmallVectorImpl<SDNode *> &Created) const {
11702   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11703   if (isIntDivCheap(N->getValueType(0), Attr))
11704     return SDValue(N, 0); // Lower SDIV as SDIV
11705 
11706   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11707          "Unexpected divisor!");
11708 
11709   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11710   if (!Subtarget.hasStdExtZbt())
11711     return SDValue();
11712 
11713   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11714   // Besides, more critical path instructions will be generated when dividing
11715   // by 2. So we keep using the original DAGs for these cases.
11716   unsigned Lg2 = Divisor.countTrailingZeros();
11717   if (Lg2 == 1 || Lg2 >= 12)
11718     return SDValue();
11719 
11720   // fold (sdiv X, pow2)
11721   EVT VT = N->getValueType(0);
11722   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11723     return SDValue();
11724 
11725   SDLoc DL(N);
11726   SDValue N0 = N->getOperand(0);
11727   SDValue Zero = DAG.getConstant(0, DL, VT);
11728   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11729 
11730   // Add (N0 < 0) ? Pow2 - 1 : 0;
11731   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
11732   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11733   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11734 
11735   Created.push_back(Cmp.getNode());
11736   Created.push_back(Add.getNode());
11737   Created.push_back(Sel.getNode());
11738 
11739   // Divide by pow2.
11740   SDValue SRA =
11741       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11742 
11743   // If we're dividing by a positive value, we're done.  Otherwise, we must
11744   // negate the result.
11745   if (Divisor.isNonNegative())
11746     return SRA;
11747 
11748   Created.push_back(SRA.getNode());
11749   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11750 }
11751 
11752 #define GET_REGISTER_MATCHER
11753 #include "RISCVGenAsmMatcher.inc"
11754 
11755 Register
11756 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11757                                        const MachineFunction &MF) const {
11758   Register Reg = MatchRegisterAltName(RegName);
11759   if (Reg == RISCV::NoRegister)
11760     Reg = MatchRegisterName(RegName);
11761   if (Reg == RISCV::NoRegister)
11762     report_fatal_error(
11763         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11764   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11765   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11766     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11767                              StringRef(RegName) + "\"."));
11768   return Reg;
11769 }
11770 
11771 namespace llvm {
11772 namespace RISCVVIntrinsicsTable {
11773 
11774 #define GET_RISCVVIntrinsicsTable_IMPL
11775 #include "RISCVGenSearchableTables.inc"
11776 
11777 } // namespace RISCVVIntrinsicsTable
11778 
11779 } // namespace llvm
11780