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       // Disable the smallest fractional LMUL types if ELEN is less than
116       // RVVBitsPerBlock.
117       unsigned MinElts = RISCV::RVVBitsPerBlock / Subtarget.getELEN();
118       if (VT.getVectorMinNumElements() < MinElts)
119         return;
120 
121       unsigned Size = VT.getSizeInBits().getKnownMinValue();
122       const TargetRegisterClass *RC;
123       if (Size <= RISCV::RVVBitsPerBlock)
124         RC = &RISCV::VRRegClass;
125       else if (Size == 2 * RISCV::RVVBitsPerBlock)
126         RC = &RISCV::VRM2RegClass;
127       else if (Size == 4 * RISCV::RVVBitsPerBlock)
128         RC = &RISCV::VRM4RegClass;
129       else if (Size == 8 * RISCV::RVVBitsPerBlock)
130         RC = &RISCV::VRM8RegClass;
131       else
132         llvm_unreachable("Unexpected size");
133 
134       addRegisterClass(VT, RC);
135     };
136 
137     for (MVT VT : BoolVecVTs)
138       addRegClassForRVV(VT);
139     for (MVT VT : IntVecVTs) {
140       if (VT.getVectorElementType() == MVT::i64 &&
141           !Subtarget.hasVInstructionsI64())
142         continue;
143       addRegClassForRVV(VT);
144     }
145 
146     if (Subtarget.hasVInstructionsF16())
147       for (MVT VT : F16VecVTs)
148         addRegClassForRVV(VT);
149 
150     if (Subtarget.hasVInstructionsF32())
151       for (MVT VT : F32VecVTs)
152         addRegClassForRVV(VT);
153 
154     if (Subtarget.hasVInstructionsF64())
155       for (MVT VT : F64VecVTs)
156         addRegClassForRVV(VT);
157 
158     if (Subtarget.useRVVForFixedLengthVectors()) {
159       auto addRegClassForFixedVectors = [this](MVT VT) {
160         MVT ContainerVT = getContainerForFixedLengthVector(VT);
161         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
162         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
163         addRegisterClass(VT, TRI.getRegClass(RCID));
164       };
165       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
166         if (useRVVForFixedLengthVectorVT(VT))
167           addRegClassForFixedVectors(VT);
168 
169       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
170         if (useRVVForFixedLengthVectorVT(VT))
171           addRegClassForFixedVectors(VT);
172     }
173   }
174 
175   // Compute derived properties from the register classes.
176   computeRegisterProperties(STI.getRegisterInfo());
177 
178   setStackPointerRegisterToSaveRestore(RISCV::X2);
179 
180   setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, XLenVT,
181                    MVT::i1, Promote);
182 
183   // TODO: add all necessary setOperationAction calls.
184   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
185 
186   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
187   setOperationAction(ISD::BR_CC, XLenVT, Expand);
188   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
189   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
190 
191   setOperationAction({ISD::STACKSAVE, ISD::STACKRESTORE}, MVT::Other, Expand);
192 
193   setOperationAction(ISD::VASTART, MVT::Other, Custom);
194   setOperationAction({ISD::VAARG, ISD::VACOPY, ISD::VAEND}, MVT::Other, Expand);
195 
196   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
197 
198   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
199 
200   if (!Subtarget.hasStdExtZbb())
201     setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand);
202 
203   if (Subtarget.is64Bit()) {
204     setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
205 
206     setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL},
207                        MVT::i32, Custom);
208 
209     setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT},
210                        MVT::i32, Custom);
211   } else {
212     setLibcallName(
213         {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128},
214         nullptr);
215     setLibcallName(RTLIB::MULO_I64, nullptr);
216   }
217 
218   if (!Subtarget.hasStdExtM()) {
219     setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::SDIV, ISD::UDIV,
220                         ISD::SREM, ISD::UREM},
221                        XLenVT, Expand);
222   } else {
223     if (Subtarget.is64Bit()) {
224       setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom);
225 
226       setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM},
227                          {MVT::i8, MVT::i16, MVT::i32}, Custom);
228     } else {
229       setOperationAction(ISD::MUL, MVT::i64, Custom);
230     }
231   }
232 
233   setOperationAction(
234       {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT,
235       Expand);
236 
237   setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT,
238                      Custom);
239 
240   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
241       Subtarget.hasStdExtZbkb()) {
242     if (Subtarget.is64Bit())
243       setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom);
244   } else {
245     setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand);
246   }
247 
248   if (Subtarget.hasStdExtZbp()) {
249     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
250     // more combining.
251     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom);
252 
253     // BSWAP i8 doesn't exist.
254     setOperationAction(ISD::BITREVERSE, MVT::i8, Custom);
255 
256     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom);
257 
258     if (Subtarget.is64Bit())
259       setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom);
260   } else {
261     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
262     // pattern match it directly in isel.
263     setOperationAction(ISD::BSWAP, XLenVT,
264                        (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
265                            ? Legal
266                            : Expand);
267     // Zbkb can use rev8+brev8 to implement bitreverse.
268     setOperationAction(ISD::BITREVERSE, XLenVT,
269                        Subtarget.hasStdExtZbkb() ? Custom : Expand);
270   }
271 
272   if (Subtarget.hasStdExtZbb()) {
273     setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT,
274                        Legal);
275 
276     if (Subtarget.is64Bit())
277       setOperationAction(
278           {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF},
279           MVT::i32, Custom);
280   } else {
281     setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand);
282 
283     if (Subtarget.is64Bit())
284       setOperationAction(ISD::ABS, MVT::i32, Custom);
285   }
286 
287   if (Subtarget.hasStdExtZbt()) {
288     setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom);
289     setOperationAction(ISD::SELECT, XLenVT, Legal);
290 
291     if (Subtarget.is64Bit())
292       setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom);
293   } else {
294     setOperationAction(ISD::SELECT, XLenVT, Custom);
295   }
296 
297   static constexpr ISD::NodeType FPLegalNodeTypes[] = {
298       ISD::FMINNUM,        ISD::FMAXNUM,       ISD::LRINT,
299       ISD::LLRINT,         ISD::LROUND,        ISD::LLROUND,
300       ISD::STRICT_LRINT,   ISD::STRICT_LLRINT, ISD::STRICT_LROUND,
301       ISD::STRICT_LLROUND, ISD::STRICT_FMA,    ISD::STRICT_FADD,
302       ISD::STRICT_FSUB,    ISD::STRICT_FMUL,   ISD::STRICT_FDIV,
303       ISD::STRICT_FSQRT,   ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS};
304 
305   static const ISD::CondCode FPCCToExpand[] = {
306       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
307       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
308       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
309 
310   static const ISD::NodeType FPOpToExpand[] = {
311       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
312       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
313 
314   if (Subtarget.hasStdExtZfh())
315     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
316 
317   if (Subtarget.hasStdExtZfh()) {
318     for (auto NT : FPLegalNodeTypes)
319       setOperationAction(NT, MVT::f16, Legal);
320     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
321     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
322     setCondCodeAction(FPCCToExpand, MVT::f16, Expand);
323     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
324     setOperationAction(ISD::SELECT, MVT::f16, Custom);
325     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
326 
327     setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT,
328                         ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC,
329                         ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN,
330                         ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG,
331                         ISD::FLOG2, ISD::FLOG10},
332                        MVT::f16, Promote);
333 
334     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
335     // complete support for all operations in LegalizeDAG.
336 
337     // We need to custom promote this.
338     if (Subtarget.is64Bit())
339       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
340   }
341 
342   if (Subtarget.hasStdExtF()) {
343     for (auto NT : FPLegalNodeTypes)
344       setOperationAction(NT, MVT::f32, Legal);
345     setCondCodeAction(FPCCToExpand, MVT::f32, Expand);
346     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
347     setOperationAction(ISD::SELECT, MVT::f32, Custom);
348     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
349     for (auto Op : FPOpToExpand)
350       setOperationAction(Op, MVT::f32, Expand);
351     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
352     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
353   }
354 
355   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
356     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
357 
358   if (Subtarget.hasStdExtD()) {
359     for (auto NT : FPLegalNodeTypes)
360       setOperationAction(NT, MVT::f64, Legal);
361     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
362     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
363     setCondCodeAction(FPCCToExpand, MVT::f64, Expand);
364     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
365     setOperationAction(ISD::SELECT, MVT::f64, Custom);
366     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
367     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
368     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
369     for (auto Op : FPOpToExpand)
370       setOperationAction(Op, MVT::f64, Expand);
371     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
372     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
373   }
374 
375   if (Subtarget.is64Bit())
376     setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT,
377                         ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT},
378                        MVT::i32, Custom);
379 
380   if (Subtarget.hasStdExtF()) {
381     setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT,
382                        Custom);
383 
384     setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT,
385                         ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP},
386                        XLenVT, Legal);
387 
388     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
389     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
390   }
391 
392   setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool,
393                       ISD::JumpTable},
394                      XLenVT, Custom);
395 
396   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
397 
398   if (Subtarget.is64Bit())
399     setOperationAction(ISD::Constant, MVT::i64, Custom);
400 
401   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
402   // Unfortunately this can't be determined just from the ISA naming string.
403   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
404                      Subtarget.is64Bit() ? Legal : Custom);
405 
406   setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal);
407   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
408   if (Subtarget.is64Bit())
409     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
410 
411   if (Subtarget.hasStdExtA()) {
412     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
413     setMinCmpXchgSizeInBits(32);
414   } else {
415     setMaxAtomicSizeInBitsSupported(0);
416   }
417 
418   setBooleanContents(ZeroOrOneBooleanContent);
419 
420   if (Subtarget.hasVInstructions()) {
421     setBooleanVectorContents(ZeroOrOneBooleanContent);
422 
423     setOperationAction(ISD::VSCALE, XLenVT, Custom);
424 
425     // RVV intrinsics may have illegal operands.
426     // We also need to custom legalize vmv.x.s.
427     setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
428                        {MVT::i8, MVT::i16}, Custom);
429     if (Subtarget.is64Bit())
430       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
431     else
432       setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
433                          MVT::i64, Custom);
434 
435     setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID},
436                        MVT::Other, Custom);
437 
438     static const unsigned IntegerVPOps[] = {
439         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
440         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
441         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
442         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
443         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
444         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
445         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
446         ISD::VP_MERGE,       ISD::VP_SELECT,      ISD::VP_FPTOSI,
447         ISD::VP_FPTOUI,      ISD::VP_SETCC,       ISD::VP_SIGN_EXTEND,
448         ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE};
449 
450     static const unsigned FloatingPointVPOps[] = {
451         ISD::VP_FADD,        ISD::VP_FSUB,
452         ISD::VP_FMUL,        ISD::VP_FDIV,
453         ISD::VP_FNEG,        ISD::VP_FMA,
454         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
455         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX,
456         ISD::VP_MERGE,       ISD::VP_SELECT,
457         ISD::VP_SITOFP,      ISD::VP_UITOFP,
458         ISD::VP_SETCC,       ISD::VP_FP_ROUND,
459         ISD::VP_FP_EXTEND};
460 
461     if (!Subtarget.is64Bit()) {
462       // We must custom-lower certain vXi64 operations on RV32 due to the vector
463       // element type being illegal.
464       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
465                          MVT::i64, Custom);
466 
467       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
468                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
469                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
470                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
471                          MVT::i64, Custom);
472 
473       setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND,
474                           ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR,
475                           ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN,
476                           ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN},
477                          MVT::i64, Custom);
478     }
479 
480     for (MVT VT : BoolVecVTs) {
481       if (!isTypeLegal(VT))
482         continue;
483 
484       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
485 
486       // Mask VTs are custom-expanded into a series of standard nodes
487       setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS,
488                           ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
489                          VT, Custom);
490 
491       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
492                          Custom);
493 
494       setOperationAction(ISD::SELECT, VT, Custom);
495       setOperationAction(
496           {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT,
497           Expand);
498 
499       setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom);
500 
501       setOperationAction(
502           {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
503           Custom);
504 
505       setOperationAction(
506           {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
507           Custom);
508 
509       // RVV has native int->float & float->int conversions where the
510       // element type sizes are within one power-of-two of each other. Any
511       // wider distances between type sizes have to be lowered as sequences
512       // which progressively narrow the gap in stages.
513       setOperationAction(
514           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
515           VT, Custom);
516 
517       // Expand all extending loads to types larger than this, and truncating
518       // stores from types larger than this.
519       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
520         setTruncStoreAction(OtherVT, VT, Expand);
521         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
522                          VT, Expand);
523       }
524 
525       setOperationAction(
526           {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT,
527           Custom);
528     }
529 
530     for (MVT VT : IntVecVTs) {
531       if (!isTypeLegal(VT))
532         continue;
533 
534       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
535       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
536 
537       // Vectors implement MULHS/MULHU.
538       setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand);
539 
540       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
541       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV())
542         setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand);
543 
544       setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT,
545                          Legal);
546 
547       setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand);
548 
549       setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT,
550                          Expand);
551 
552       setOperationAction(ISD::BSWAP, VT, Expand);
553 
554       // Custom-lower extensions and truncations from/to mask types.
555       setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND},
556                          VT, Custom);
557 
558       // RVV has native int->float & float->int conversions where the
559       // element type sizes are within one power-of-two of each other. Any
560       // wider distances between type sizes have to be lowered as sequences
561       // which progressively narrow the gap in stages.
562       setOperationAction(
563           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
564           VT, Custom);
565 
566       setOperationAction(
567           {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal);
568 
569       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
570       // nodes which truncate by one power of two at a time.
571       setOperationAction(ISD::TRUNCATE, VT, Custom);
572 
573       // Custom-lower insert/extract operations to simplify patterns.
574       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
575                          Custom);
576 
577       // Custom-lower reduction operations to set up the corresponding custom
578       // nodes' operands.
579       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
580                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
581                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
582                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
583                          VT, Custom);
584 
585       setOperationAction(IntegerVPOps, VT, Custom);
586 
587       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
588 
589       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
590                          VT, Custom);
591 
592       setOperationAction(
593           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
594           Custom);
595 
596       setOperationAction(
597           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
598           VT, Custom);
599 
600       setOperationAction(ISD::SELECT, VT, Custom);
601       setOperationAction(ISD::SELECT_CC, VT, Expand);
602 
603       setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom);
604 
605       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
606         setTruncStoreAction(VT, OtherVT, Expand);
607         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
608                          VT, Expand);
609       }
610 
611       // Splice
612       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
613 
614       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
615       // type that can represent the value exactly.
616       if (VT.getVectorElementType() != MVT::i64) {
617         MVT FloatEltVT =
618             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
619         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
620         if (isTypeLegal(FloatVT)) {
621           setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
622                              Custom);
623         }
624       }
625     }
626 
627     // Expand various CCs to best match the RVV ISA, which natively supports UNE
628     // but no other unordered comparisons, and supports all ordered comparisons
629     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
630     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
631     // and we pattern-match those back to the "original", swapping operands once
632     // more. This way we catch both operations and both "vf" and "fv" forms with
633     // fewer patterns.
634     static const ISD::CondCode VFPCCToExpand[] = {
635         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
636         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
637         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
638     };
639 
640     // Sets common operation actions on RVV floating-point vector types.
641     const auto SetCommonVFPActions = [&](MVT VT) {
642       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
643       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
644       // sizes are within one power-of-two of each other. Therefore conversions
645       // between vXf16 and vXf64 must be lowered as sequences which convert via
646       // vXf32.
647       setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
648       // Custom-lower insert/extract operations to simplify patterns.
649       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
650                          Custom);
651       // Expand various condition codes (explained above).
652       setCondCodeAction(VFPCCToExpand, VT, Expand);
653 
654       setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal);
655 
656       setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
657                          VT, Custom);
658 
659       setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
660                           ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
661                          VT, Custom);
662 
663       // Expand FP operations that need libcalls.
664       setOperationAction(ISD::FREM, VT, Expand);
665       setOperationAction(ISD::FPOW, VT, Expand);
666       setOperationAction(ISD::FCOS, VT, Expand);
667       setOperationAction(ISD::FSIN, VT, Expand);
668       setOperationAction(ISD::FSINCOS, VT, Expand);
669       setOperationAction(ISD::FEXP, VT, Expand);
670       setOperationAction(ISD::FEXP2, VT, Expand);
671       setOperationAction(ISD::FLOG, VT, Expand);
672       setOperationAction(ISD::FLOG2, VT, Expand);
673       setOperationAction(ISD::FLOG10, VT, Expand);
674       setOperationAction(ISD::FRINT, VT, Expand);
675       setOperationAction(ISD::FNEARBYINT, VT, Expand);
676 
677       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
678       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
679       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
680       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
681 
682       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
683 
684       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
685 
686       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
687                          VT, Custom);
688 
689       setOperationAction(
690           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
691           Custom);
692 
693       setOperationAction(ISD::SELECT, VT, Custom);
694       setOperationAction(ISD::SELECT_CC, VT, Expand);
695 
696       setOperationAction(
697           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
698           VT, Custom);
699 
700       setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom);
701 
702       setOperationAction(FloatingPointVPOps, VT, Custom);
703     };
704 
705     // Sets common extload/truncstore actions on RVV floating-point vector
706     // types.
707     const auto SetCommonVFPExtLoadTruncStoreActions =
708         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
709           for (auto SmallVT : SmallerVTs) {
710             setTruncStoreAction(VT, SmallVT, Expand);
711             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
712           }
713         };
714 
715     if (Subtarget.hasVInstructionsF16()) {
716       for (MVT VT : F16VecVTs) {
717         if (!isTypeLegal(VT))
718           continue;
719         SetCommonVFPActions(VT);
720       }
721     }
722 
723     if (Subtarget.hasVInstructionsF32()) {
724       for (MVT VT : F32VecVTs) {
725         if (!isTypeLegal(VT))
726           continue;
727         SetCommonVFPActions(VT);
728         SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
729       }
730     }
731 
732     if (Subtarget.hasVInstructionsF64()) {
733       for (MVT VT : F64VecVTs) {
734         if (!isTypeLegal(VT))
735           continue;
736         SetCommonVFPActions(VT);
737         SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
738         SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
739       }
740     }
741 
742     if (Subtarget.useRVVForFixedLengthVectors()) {
743       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
744         if (!useRVVForFixedLengthVectorVT(VT))
745           continue;
746 
747         // By default everything must be expanded.
748         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
749           setOperationAction(Op, VT, Expand);
750         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
751           setTruncStoreAction(VT, OtherVT, Expand);
752           setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD},
753                            OtherVT, VT, Expand);
754         }
755 
756         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
757         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
758                            Custom);
759 
760         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT,
761                            Custom);
762 
763         setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
764                            VT, Custom);
765 
766         setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
767 
768         setOperationAction(ISD::SETCC, VT, Custom);
769 
770         setOperationAction(ISD::SELECT, VT, Custom);
771 
772         setOperationAction(ISD::TRUNCATE, VT, Custom);
773 
774         setOperationAction(ISD::BITCAST, VT, Custom);
775 
776         setOperationAction(
777             {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
778             Custom);
779 
780         setOperationAction(
781             {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
782             Custom);
783 
784         setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT,
785                             ISD::FP_TO_UINT},
786                            VT, Custom);
787 
788         // Operations below are different for between masks and other vectors.
789         if (VT.getVectorElementType() == MVT::i1) {
790           setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND,
791                               ISD::OR, ISD::XOR},
792                              VT, Custom);
793 
794           setOperationAction(
795               {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE},
796               VT, Custom);
797           continue;
798         }
799 
800         // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
801         // it before type legalization for i64 vectors on RV32. It will then be
802         // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
803         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
804         // improvements first.
805         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
806           setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
807           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
808         }
809 
810         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
811         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
812 
813         setOperationAction(
814             {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom);
815 
816         setOperationAction(
817             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
818             Custom);
819 
820         setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR,
821                             ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV,
822                             ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL},
823                            VT, Custom);
824 
825         setOperationAction(
826             {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom);
827 
828         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
829         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV())
830           setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom);
831 
832         setOperationAction(
833             {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT,
834             Custom);
835 
836         setOperationAction(ISD::VSELECT, VT, Custom);
837         setOperationAction(ISD::SELECT_CC, VT, Expand);
838 
839         setOperationAction(
840             {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom);
841 
842         // Custom-lower reduction operations to set up the corresponding custom
843         // nodes' operands.
844         setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX,
845                             ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX,
846                             ISD::VECREDUCE_UMIN},
847                            VT, Custom);
848 
849         setOperationAction(IntegerVPOps, VT, Custom);
850 
851         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
852         // type that can represent the value exactly.
853         if (VT.getVectorElementType() != MVT::i64) {
854           MVT FloatEltVT =
855               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
856           EVT FloatVT =
857               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
858           if (isTypeLegal(FloatVT))
859             setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
860                                Custom);
861         }
862       }
863 
864       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
865         if (!useRVVForFixedLengthVectorVT(VT))
866           continue;
867 
868         // By default everything must be expanded.
869         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
870           setOperationAction(Op, VT, Expand);
871         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
872           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
873           setTruncStoreAction(VT, OtherVT, Expand);
874         }
875 
876         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
877         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
878                            Custom);
879 
880         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS,
881                             ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT,
882                             ISD::EXTRACT_VECTOR_ELT},
883                            VT, Custom);
884 
885         setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE,
886                             ISD::MGATHER, ISD::MSCATTER},
887                            VT, Custom);
888 
889         setOperationAction(
890             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
891             Custom);
892 
893         setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV,
894                             ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT,
895                             ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM},
896                            VT, Custom);
897 
898         setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
899 
900         setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
901                            VT, Custom);
902 
903         for (auto CC : VFPCCToExpand)
904           setCondCodeAction(CC, VT, Expand);
905 
906         setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom);
907         setOperationAction(ISD::SELECT_CC, VT, Expand);
908 
909         setOperationAction(ISD::BITCAST, VT, Custom);
910 
911         setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
912                             ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
913                            VT, Custom);
914 
915         setOperationAction(FloatingPointVPOps, VT, Custom);
916       }
917 
918       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
919       setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64},
920                          Custom);
921       if (Subtarget.hasStdExtZfh())
922         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
923       if (Subtarget.hasStdExtF())
924         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
925       if (Subtarget.hasStdExtD())
926         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
927     }
928   }
929 
930   // Function alignments.
931   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
932   setMinFunctionAlignment(FunctionAlignment);
933   setPrefFunctionAlignment(FunctionAlignment);
934 
935   setMinimumJumpTableEntries(5);
936 
937   // Jumps are expensive, compared to logic
938   setJumpIsExpensive();
939 
940   setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND,
941                        ISD::OR, ISD::XOR});
942 
943   if (Subtarget.hasStdExtF())
944     setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM});
945 
946   if (Subtarget.hasStdExtZbp())
947     setTargetDAGCombine({ISD::ROTL, ISD::ROTR});
948 
949   if (Subtarget.hasStdExtZbb())
950     setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN});
951 
952   if (Subtarget.hasStdExtZbkb())
953     setTargetDAGCombine(ISD::BITREVERSE);
954   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
955     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
956   if (Subtarget.hasStdExtF())
957     setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
958                          ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT});
959   if (Subtarget.hasVInstructions())
960     setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER,
961                          ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL,
962                          ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR});
963   if (Subtarget.useRVVForFixedLengthVectors())
964     setTargetDAGCombine(ISD::BITCAST);
965 
966   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
967   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
968 }
969 
970 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
971                                             LLVMContext &Context,
972                                             EVT VT) const {
973   if (!VT.isVector())
974     return getPointerTy(DL);
975   if (Subtarget.hasVInstructions() &&
976       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
977     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
978   return VT.changeVectorElementTypeToInteger();
979 }
980 
981 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
982   return Subtarget.getXLenVT();
983 }
984 
985 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
986                                              const CallInst &I,
987                                              MachineFunction &MF,
988                                              unsigned Intrinsic) const {
989   auto &DL = I.getModule()->getDataLayout();
990   switch (Intrinsic) {
991   default:
992     return false;
993   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
994   case Intrinsic::riscv_masked_atomicrmw_add_i32:
995   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
996   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
997   case Intrinsic::riscv_masked_atomicrmw_max_i32:
998   case Intrinsic::riscv_masked_atomicrmw_min_i32:
999   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1000   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1001   case Intrinsic::riscv_masked_cmpxchg_i32:
1002     Info.opc = ISD::INTRINSIC_W_CHAIN;
1003     Info.memVT = MVT::i32;
1004     Info.ptrVal = I.getArgOperand(0);
1005     Info.offset = 0;
1006     Info.align = Align(4);
1007     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1008                  MachineMemOperand::MOVolatile;
1009     return true;
1010   case Intrinsic::riscv_masked_strided_load:
1011     Info.opc = ISD::INTRINSIC_W_CHAIN;
1012     Info.ptrVal = I.getArgOperand(1);
1013     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1014     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1015     Info.size = MemoryLocation::UnknownSize;
1016     Info.flags |= MachineMemOperand::MOLoad;
1017     return true;
1018   case Intrinsic::riscv_masked_strided_store:
1019     Info.opc = ISD::INTRINSIC_VOID;
1020     Info.ptrVal = I.getArgOperand(1);
1021     Info.memVT =
1022         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1023     Info.align = Align(
1024         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1025         8);
1026     Info.size = MemoryLocation::UnknownSize;
1027     Info.flags |= MachineMemOperand::MOStore;
1028     return true;
1029   case Intrinsic::riscv_seg2_load:
1030   case Intrinsic::riscv_seg3_load:
1031   case Intrinsic::riscv_seg4_load:
1032   case Intrinsic::riscv_seg5_load:
1033   case Intrinsic::riscv_seg6_load:
1034   case Intrinsic::riscv_seg7_load:
1035   case Intrinsic::riscv_seg8_load:
1036     Info.opc = ISD::INTRINSIC_W_CHAIN;
1037     Info.ptrVal = I.getArgOperand(0);
1038     Info.memVT =
1039         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
1040     Info.align =
1041         Align(DL.getTypeSizeInBits(
1042                   I.getType()->getStructElementType(0)->getScalarType()) /
1043               8);
1044     Info.size = MemoryLocation::UnknownSize;
1045     Info.flags |= MachineMemOperand::MOLoad;
1046     return true;
1047   }
1048 }
1049 
1050 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1051                                                 const AddrMode &AM, Type *Ty,
1052                                                 unsigned AS,
1053                                                 Instruction *I) const {
1054   // No global is ever allowed as a base.
1055   if (AM.BaseGV)
1056     return false;
1057 
1058   // RVV instructions only support register addressing.
1059   if (Subtarget.hasVInstructions() && isa<VectorType>(Ty))
1060     return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs;
1061 
1062   // Require a 12-bit signed offset.
1063   if (!isInt<12>(AM.BaseOffs))
1064     return false;
1065 
1066   switch (AM.Scale) {
1067   case 0: // "r+i" or just "i", depending on HasBaseReg.
1068     break;
1069   case 1:
1070     if (!AM.HasBaseReg) // allow "r+i".
1071       break;
1072     return false; // disallow "r+r" or "r+r+i".
1073   default:
1074     return false;
1075   }
1076 
1077   return true;
1078 }
1079 
1080 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1081   return isInt<12>(Imm);
1082 }
1083 
1084 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1085   return isInt<12>(Imm);
1086 }
1087 
1088 // On RV32, 64-bit integers are split into their high and low parts and held
1089 // in two different registers, so the trunc is free since the low register can
1090 // just be used.
1091 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1092   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1093     return false;
1094   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1095   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1096   return (SrcBits == 64 && DestBits == 32);
1097 }
1098 
1099 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1100   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1101       !SrcVT.isInteger() || !DstVT.isInteger())
1102     return false;
1103   unsigned SrcBits = SrcVT.getSizeInBits();
1104   unsigned DestBits = DstVT.getSizeInBits();
1105   return (SrcBits == 64 && DestBits == 32);
1106 }
1107 
1108 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1109   // Zexts are free if they can be combined with a load.
1110   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1111   // poorly with type legalization of compares preferring sext.
1112   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1113     EVT MemVT = LD->getMemoryVT();
1114     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1115         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1116          LD->getExtensionType() == ISD::ZEXTLOAD))
1117       return true;
1118   }
1119 
1120   return TargetLowering::isZExtFree(Val, VT2);
1121 }
1122 
1123 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1124   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1125 }
1126 
1127 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const {
1128   return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
1129 }
1130 
1131 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1132   return Subtarget.hasStdExtZbb();
1133 }
1134 
1135 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1136   return Subtarget.hasStdExtZbb();
1137 }
1138 
1139 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1140   EVT VT = Y.getValueType();
1141 
1142   // FIXME: Support vectors once we have tests.
1143   if (VT.isVector())
1144     return false;
1145 
1146   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1147           Subtarget.hasStdExtZbkb()) &&
1148          !isa<ConstantSDNode>(Y);
1149 }
1150 
1151 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
1152   // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1153   auto *C = dyn_cast<ConstantSDNode>(Y);
1154   return C && C->getAPIntValue().ule(10);
1155 }
1156 
1157 bool RISCVTargetLowering::
1158     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
1159         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
1160         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
1161         SelectionDAG &DAG) const {
1162   // One interesting pattern that we'd want to form is 'bit extract':
1163   //   ((1 >> Y) & 1) ==/!= 0
1164   // But we also need to be careful not to try to reverse that fold.
1165 
1166   // Is this '((1 >> Y) & 1)'?
1167   if (XC && OldShiftOpcode == ISD::SRL && XC->isOne())
1168     return false; // Keep the 'bit extract' pattern.
1169 
1170   // Will this be '((1 >> Y) & 1)' after the transform?
1171   if (NewShiftOpcode == ISD::SRL && CC->isOne())
1172     return true; // Do form the 'bit extract' pattern.
1173 
1174   // If 'X' is a constant, and we transform, then we will immediately
1175   // try to undo the fold, thus causing endless combine loop.
1176   // So only do the transform if X is not a constant. This matches the default
1177   // implementation of this function.
1178   return !XC;
1179 }
1180 
1181 /// Check if sinking \p I's operands to I's basic block is profitable, because
1182 /// the operands can be folded into a target instruction, e.g.
1183 /// splats of scalars can fold into vector instructions.
1184 bool RISCVTargetLowering::shouldSinkOperands(
1185     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1186   using namespace llvm::PatternMatch;
1187 
1188   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1189     return false;
1190 
1191   auto IsSinker = [&](Instruction *I, int Operand) {
1192     switch (I->getOpcode()) {
1193     case Instruction::Add:
1194     case Instruction::Sub:
1195     case Instruction::Mul:
1196     case Instruction::And:
1197     case Instruction::Or:
1198     case Instruction::Xor:
1199     case Instruction::FAdd:
1200     case Instruction::FSub:
1201     case Instruction::FMul:
1202     case Instruction::FDiv:
1203     case Instruction::ICmp:
1204     case Instruction::FCmp:
1205       return true;
1206     case Instruction::Shl:
1207     case Instruction::LShr:
1208     case Instruction::AShr:
1209     case Instruction::UDiv:
1210     case Instruction::SDiv:
1211     case Instruction::URem:
1212     case Instruction::SRem:
1213       return Operand == 1;
1214     case Instruction::Call:
1215       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1216         switch (II->getIntrinsicID()) {
1217         case Intrinsic::fma:
1218         case Intrinsic::vp_fma:
1219           return Operand == 0 || Operand == 1;
1220         // FIXME: Our patterns can only match vx/vf instructions when the splat
1221         // it on the RHS, because TableGen doesn't recognize our VP operations
1222         // as commutative.
1223         case Intrinsic::vp_add:
1224         case Intrinsic::vp_mul:
1225         case Intrinsic::vp_and:
1226         case Intrinsic::vp_or:
1227         case Intrinsic::vp_xor:
1228         case Intrinsic::vp_fadd:
1229         case Intrinsic::vp_fmul:
1230         case Intrinsic::vp_shl:
1231         case Intrinsic::vp_lshr:
1232         case Intrinsic::vp_ashr:
1233         case Intrinsic::vp_udiv:
1234         case Intrinsic::vp_sdiv:
1235         case Intrinsic::vp_urem:
1236         case Intrinsic::vp_srem:
1237           return Operand == 1;
1238         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1239         // explicit patterns for both LHS and RHS (as 'vr' versions).
1240         case Intrinsic::vp_sub:
1241         case Intrinsic::vp_fsub:
1242         case Intrinsic::vp_fdiv:
1243           return Operand == 0 || Operand == 1;
1244         default:
1245           return false;
1246         }
1247       }
1248       return false;
1249     default:
1250       return false;
1251     }
1252   };
1253 
1254   for (auto OpIdx : enumerate(I->operands())) {
1255     if (!IsSinker(I, OpIdx.index()))
1256       continue;
1257 
1258     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1259     // Make sure we are not already sinking this operand
1260     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1261       continue;
1262 
1263     // We are looking for a splat that can be sunk.
1264     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1265                              m_Undef(), m_ZeroMask())))
1266       continue;
1267 
1268     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1269     // and vector registers
1270     for (Use &U : Op->uses()) {
1271       Instruction *Insn = cast<Instruction>(U.getUser());
1272       if (!IsSinker(Insn, U.getOperandNo()))
1273         return false;
1274     }
1275 
1276     Ops.push_back(&Op->getOperandUse(0));
1277     Ops.push_back(&OpIdx.value());
1278   }
1279   return true;
1280 }
1281 
1282 bool RISCVTargetLowering::isOffsetFoldingLegal(
1283     const GlobalAddressSDNode *GA) const {
1284   // In order to maximise the opportunity for common subexpression elimination,
1285   // keep a separate ADD node for the global address offset instead of folding
1286   // it in the global address node. Later peephole optimisations may choose to
1287   // fold it back in when profitable.
1288   return false;
1289 }
1290 
1291 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1292                                        bool ForCodeSize) const {
1293   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1294   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1295     return false;
1296   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1297     return false;
1298   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1299     return false;
1300   return Imm.isZero();
1301 }
1302 
1303 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1304   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1305          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1306          (VT == MVT::f64 && Subtarget.hasStdExtD());
1307 }
1308 
1309 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1310                                                       CallingConv::ID CC,
1311                                                       EVT VT) const {
1312   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1313   // We might still end up using a GPR but that will be decided based on ABI.
1314   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1315   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1316     return MVT::f32;
1317 
1318   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1319 }
1320 
1321 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1322                                                            CallingConv::ID CC,
1323                                                            EVT VT) const {
1324   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1325   // We might still end up using a GPR but that will be decided based on ABI.
1326   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1327   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1328     return 1;
1329 
1330   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1331 }
1332 
1333 // Changes the condition code and swaps operands if necessary, so the SetCC
1334 // operation matches one of the comparisons supported directly by branches
1335 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1336 // with 1/-1.
1337 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1338                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1339   // Convert X > -1 to X >= 0.
1340   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1341     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1342     CC = ISD::SETGE;
1343     return;
1344   }
1345   // Convert X < 1 to 0 >= X.
1346   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1347     RHS = LHS;
1348     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1349     CC = ISD::SETGE;
1350     return;
1351   }
1352 
1353   switch (CC) {
1354   default:
1355     break;
1356   case ISD::SETGT:
1357   case ISD::SETLE:
1358   case ISD::SETUGT:
1359   case ISD::SETULE:
1360     CC = ISD::getSetCCSwappedOperands(CC);
1361     std::swap(LHS, RHS);
1362     break;
1363   }
1364 }
1365 
1366 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1367   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1368   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1369   if (VT.getVectorElementType() == MVT::i1)
1370     KnownSize *= 8;
1371 
1372   switch (KnownSize) {
1373   default:
1374     llvm_unreachable("Invalid LMUL.");
1375   case 8:
1376     return RISCVII::VLMUL::LMUL_F8;
1377   case 16:
1378     return RISCVII::VLMUL::LMUL_F4;
1379   case 32:
1380     return RISCVII::VLMUL::LMUL_F2;
1381   case 64:
1382     return RISCVII::VLMUL::LMUL_1;
1383   case 128:
1384     return RISCVII::VLMUL::LMUL_2;
1385   case 256:
1386     return RISCVII::VLMUL::LMUL_4;
1387   case 512:
1388     return RISCVII::VLMUL::LMUL_8;
1389   }
1390 }
1391 
1392 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1393   switch (LMul) {
1394   default:
1395     llvm_unreachable("Invalid LMUL.");
1396   case RISCVII::VLMUL::LMUL_F8:
1397   case RISCVII::VLMUL::LMUL_F4:
1398   case RISCVII::VLMUL::LMUL_F2:
1399   case RISCVII::VLMUL::LMUL_1:
1400     return RISCV::VRRegClassID;
1401   case RISCVII::VLMUL::LMUL_2:
1402     return RISCV::VRM2RegClassID;
1403   case RISCVII::VLMUL::LMUL_4:
1404     return RISCV::VRM4RegClassID;
1405   case RISCVII::VLMUL::LMUL_8:
1406     return RISCV::VRM8RegClassID;
1407   }
1408 }
1409 
1410 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1411   RISCVII::VLMUL LMUL = getLMUL(VT);
1412   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1413       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1414       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1415       LMUL == RISCVII::VLMUL::LMUL_1) {
1416     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1417                   "Unexpected subreg numbering");
1418     return RISCV::sub_vrm1_0 + Index;
1419   }
1420   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1421     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1422                   "Unexpected subreg numbering");
1423     return RISCV::sub_vrm2_0 + Index;
1424   }
1425   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1426     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1427                   "Unexpected subreg numbering");
1428     return RISCV::sub_vrm4_0 + Index;
1429   }
1430   llvm_unreachable("Invalid vector type.");
1431 }
1432 
1433 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1434   if (VT.getVectorElementType() == MVT::i1)
1435     return RISCV::VRRegClassID;
1436   return getRegClassIDForLMUL(getLMUL(VT));
1437 }
1438 
1439 // Attempt to decompose a subvector insert/extract between VecVT and
1440 // SubVecVT via subregister indices. Returns the subregister index that
1441 // can perform the subvector insert/extract with the given element index, as
1442 // well as the index corresponding to any leftover subvectors that must be
1443 // further inserted/extracted within the register class for SubVecVT.
1444 std::pair<unsigned, unsigned>
1445 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1446     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1447     const RISCVRegisterInfo *TRI) {
1448   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1449                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1450                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1451                 "Register classes not ordered");
1452   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1453   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1454   // Try to compose a subregister index that takes us from the incoming
1455   // LMUL>1 register class down to the outgoing one. At each step we half
1456   // the LMUL:
1457   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1458   // Note that this is not guaranteed to find a subregister index, such as
1459   // when we are extracting from one VR type to another.
1460   unsigned SubRegIdx = RISCV::NoSubRegister;
1461   for (const unsigned RCID :
1462        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1463     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1464       VecVT = VecVT.getHalfNumVectorElementsVT();
1465       bool IsHi =
1466           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1467       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1468                                             getSubregIndexByMVT(VecVT, IsHi));
1469       if (IsHi)
1470         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1471     }
1472   return {SubRegIdx, InsertExtractIdx};
1473 }
1474 
1475 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1476 // stores for those types.
1477 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1478   return !Subtarget.useRVVForFixedLengthVectors() ||
1479          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1480 }
1481 
1482 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1483   if (ScalarTy->isPointerTy())
1484     return true;
1485 
1486   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1487       ScalarTy->isIntegerTy(32))
1488     return true;
1489 
1490   if (ScalarTy->isIntegerTy(64))
1491     return Subtarget.hasVInstructionsI64();
1492 
1493   if (ScalarTy->isHalfTy())
1494     return Subtarget.hasVInstructionsF16();
1495   if (ScalarTy->isFloatTy())
1496     return Subtarget.hasVInstructionsF32();
1497   if (ScalarTy->isDoubleTy())
1498     return Subtarget.hasVInstructionsF64();
1499 
1500   return false;
1501 }
1502 
1503 static SDValue getVLOperand(SDValue Op) {
1504   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1505           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1506          "Unexpected opcode");
1507   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1508   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1509   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1510       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1511   if (!II)
1512     return SDValue();
1513   return Op.getOperand(II->VLOperand + 1 + HasChain);
1514 }
1515 
1516 static bool useRVVForFixedLengthVectorVT(MVT VT,
1517                                          const RISCVSubtarget &Subtarget) {
1518   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1519   if (!Subtarget.useRVVForFixedLengthVectors())
1520     return false;
1521 
1522   // We only support a set of vector types with a consistent maximum fixed size
1523   // across all supported vector element types to avoid legalization issues.
1524   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1525   // fixed-length vector type we support is 1024 bytes.
1526   if (VT.getFixedSizeInBits() > 1024 * 8)
1527     return false;
1528 
1529   unsigned MinVLen = Subtarget.getRealMinVLen();
1530 
1531   MVT EltVT = VT.getVectorElementType();
1532 
1533   // Don't use RVV for vectors we cannot scalarize if required.
1534   switch (EltVT.SimpleTy) {
1535   // i1 is supported but has different rules.
1536   default:
1537     return false;
1538   case MVT::i1:
1539     // Masks can only use a single register.
1540     if (VT.getVectorNumElements() > MinVLen)
1541       return false;
1542     MinVLen /= 8;
1543     break;
1544   case MVT::i8:
1545   case MVT::i16:
1546   case MVT::i32:
1547     break;
1548   case MVT::i64:
1549     if (!Subtarget.hasVInstructionsI64())
1550       return false;
1551     break;
1552   case MVT::f16:
1553     if (!Subtarget.hasVInstructionsF16())
1554       return false;
1555     break;
1556   case MVT::f32:
1557     if (!Subtarget.hasVInstructionsF32())
1558       return false;
1559     break;
1560   case MVT::f64:
1561     if (!Subtarget.hasVInstructionsF64())
1562       return false;
1563     break;
1564   }
1565 
1566   // Reject elements larger than ELEN.
1567   if (EltVT.getSizeInBits() > Subtarget.getELEN())
1568     return false;
1569 
1570   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1571   // Don't use RVV for types that don't fit.
1572   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1573     return false;
1574 
1575   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1576   // the base fixed length RVV support in place.
1577   if (!VT.isPow2VectorType())
1578     return false;
1579 
1580   return true;
1581 }
1582 
1583 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1584   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1585 }
1586 
1587 // Return the largest legal scalable vector type that matches VT's element type.
1588 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1589                                             const RISCVSubtarget &Subtarget) {
1590   // This may be called before legal types are setup.
1591   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1592           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1593          "Expected legal fixed length vector!");
1594 
1595   unsigned MinVLen = Subtarget.getRealMinVLen();
1596   unsigned MaxELen = Subtarget.getELEN();
1597 
1598   MVT EltVT = VT.getVectorElementType();
1599   switch (EltVT.SimpleTy) {
1600   default:
1601     llvm_unreachable("unexpected element type for RVV container");
1602   case MVT::i1:
1603   case MVT::i8:
1604   case MVT::i16:
1605   case MVT::i32:
1606   case MVT::i64:
1607   case MVT::f16:
1608   case MVT::f32:
1609   case MVT::f64: {
1610     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1611     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1612     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1613     unsigned NumElts =
1614         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1615     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1616     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1617     return MVT::getScalableVectorVT(EltVT, NumElts);
1618   }
1619   }
1620 }
1621 
1622 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1623                                             const RISCVSubtarget &Subtarget) {
1624   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1625                                           Subtarget);
1626 }
1627 
1628 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1629   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1630 }
1631 
1632 // Grow V to consume an entire RVV register.
1633 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1634                                        const RISCVSubtarget &Subtarget) {
1635   assert(VT.isScalableVector() &&
1636          "Expected to convert into a scalable vector!");
1637   assert(V.getValueType().isFixedLengthVector() &&
1638          "Expected a fixed length vector operand!");
1639   SDLoc DL(V);
1640   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1641   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1642 }
1643 
1644 // Shrink V so it's just big enough to maintain a VT's worth of data.
1645 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1646                                          const RISCVSubtarget &Subtarget) {
1647   assert(VT.isFixedLengthVector() &&
1648          "Expected to convert into a fixed length vector!");
1649   assert(V.getValueType().isScalableVector() &&
1650          "Expected a scalable vector operand!");
1651   SDLoc DL(V);
1652   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1653   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1654 }
1655 
1656 /// Return the type of the mask type suitable for masking the provided
1657 /// vector type.  This is simply an i1 element type vector of the same
1658 /// (possibly scalable) length.
1659 static MVT getMaskTypeFor(EVT VecVT) {
1660   assert(VecVT.isVector());
1661   ElementCount EC = VecVT.getVectorElementCount();
1662   return MVT::getVectorVT(MVT::i1, EC);
1663 }
1664 
1665 /// Creates an all ones mask suitable for masking a vector of type VecTy with
1666 /// vector length VL.  .
1667 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL,
1668                               SelectionDAG &DAG) {
1669   MVT MaskVT = getMaskTypeFor(VecVT);
1670   return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1671 }
1672 
1673 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1674 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1675 // the vector type that it is contained in.
1676 static std::pair<SDValue, SDValue>
1677 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1678                 const RISCVSubtarget &Subtarget) {
1679   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1680   MVT XLenVT = Subtarget.getXLenVT();
1681   SDValue VL = VecVT.isFixedLengthVector()
1682                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1683                    : DAG.getRegister(RISCV::X0, XLenVT);
1684   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
1685   return {Mask, VL};
1686 }
1687 
1688 // As above but assuming the given type is a scalable vector type.
1689 static std::pair<SDValue, SDValue>
1690 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1691                         const RISCVSubtarget &Subtarget) {
1692   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1693   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1694 }
1695 
1696 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1697 // of either is (currently) supported. This can get us into an infinite loop
1698 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1699 // as a ..., etc.
1700 // Until either (or both) of these can reliably lower any node, reporting that
1701 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1702 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1703 // which is not desirable.
1704 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1705     EVT VT, unsigned DefinedValues) const {
1706   return false;
1707 }
1708 
1709 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1710                                   const RISCVSubtarget &Subtarget) {
1711   // RISCV FP-to-int conversions saturate to the destination register size, but
1712   // don't produce 0 for nan. We can use a conversion instruction and fix the
1713   // nan case with a compare and a select.
1714   SDValue Src = Op.getOperand(0);
1715 
1716   EVT DstVT = Op.getValueType();
1717   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1718 
1719   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1720   unsigned Opc;
1721   if (SatVT == DstVT)
1722     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1723   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1724     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1725   else
1726     return SDValue();
1727   // FIXME: Support other SatVTs by clamping before or after the conversion.
1728 
1729   SDLoc DL(Op);
1730   SDValue FpToInt = DAG.getNode(
1731       Opc, DL, DstVT, Src,
1732       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1733 
1734   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1735   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1736 }
1737 
1738 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1739 // and back. Taking care to avoid converting values that are nan or already
1740 // correct.
1741 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1742 // have FRM dependencies modeled yet.
1743 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1744   MVT VT = Op.getSimpleValueType();
1745   assert(VT.isVector() && "Unexpected type");
1746 
1747   SDLoc DL(Op);
1748 
1749   // Freeze the source since we are increasing the number of uses.
1750   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1751 
1752   // Truncate to integer and convert back to FP.
1753   MVT IntVT = VT.changeVectorElementTypeToInteger();
1754   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1755   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1756 
1757   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1758 
1759   if (Op.getOpcode() == ISD::FCEIL) {
1760     // If the truncated value is the greater than or equal to the original
1761     // value, we've computed the ceil. Otherwise, we went the wrong way and
1762     // need to increase by 1.
1763     // FIXME: This should use a masked operation. Handle here or in isel?
1764     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1765                                  DAG.getConstantFP(1.0, DL, VT));
1766     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1767     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1768   } else if (Op.getOpcode() == ISD::FFLOOR) {
1769     // If the truncated value is the less than or equal to the original value,
1770     // we've computed the floor. Otherwise, we went the wrong way and need to
1771     // decrease by 1.
1772     // FIXME: This should use a masked operation. Handle here or in isel?
1773     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1774                                  DAG.getConstantFP(1.0, DL, VT));
1775     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1776     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1777   }
1778 
1779   // Restore the original sign so that -0.0 is preserved.
1780   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1781 
1782   // Determine the largest integer that can be represented exactly. This and
1783   // values larger than it don't have any fractional bits so don't need to
1784   // be converted.
1785   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1786   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1787   APFloat MaxVal = APFloat(FltSem);
1788   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1789                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1790   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1791 
1792   // If abs(Src) was larger than MaxVal or nan, keep it.
1793   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1794   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1795   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1796 }
1797 
1798 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1799 // This mode isn't supported in vector hardware on RISCV. But as long as we
1800 // aren't compiling with trapping math, we can emulate this with
1801 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1802 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1803 // dependencies modeled yet.
1804 // FIXME: Use masked operations to avoid final merge.
1805 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1806   MVT VT = Op.getSimpleValueType();
1807   assert(VT.isVector() && "Unexpected type");
1808 
1809   SDLoc DL(Op);
1810 
1811   // Freeze the source since we are increasing the number of uses.
1812   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1813 
1814   // We do the conversion on the absolute value and fix the sign at the end.
1815   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1816 
1817   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1818   bool Ignored;
1819   APFloat Point5Pred = APFloat(0.5f);
1820   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1821   Point5Pred.next(/*nextDown*/ true);
1822 
1823   // Add the adjustment.
1824   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1825                                DAG.getConstantFP(Point5Pred, DL, VT));
1826 
1827   // Truncate to integer and convert back to fp.
1828   MVT IntVT = VT.changeVectorElementTypeToInteger();
1829   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1830   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1831 
1832   // Restore the original sign.
1833   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1834 
1835   // Determine the largest integer that can be represented exactly. This and
1836   // values larger than it don't have any fractional bits so don't need to
1837   // be converted.
1838   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1839   APFloat MaxVal = APFloat(FltSem);
1840   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1841                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1842   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1843 
1844   // If abs(Src) was larger than MaxVal or nan, keep it.
1845   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1846   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1847   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1848 }
1849 
1850 struct VIDSequence {
1851   int64_t StepNumerator;
1852   unsigned StepDenominator;
1853   int64_t Addend;
1854 };
1855 
1856 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1857 // to the (non-zero) step S and start value X. This can be then lowered as the
1858 // RVV sequence (VID * S) + X, for example.
1859 // The step S is represented as an integer numerator divided by a positive
1860 // denominator. Note that the implementation currently only identifies
1861 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1862 // cannot detect 2/3, for example.
1863 // Note that this method will also match potentially unappealing index
1864 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1865 // determine whether this is worth generating code for.
1866 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1867   unsigned NumElts = Op.getNumOperands();
1868   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1869   if (!Op.getValueType().isInteger())
1870     return None;
1871 
1872   Optional<unsigned> SeqStepDenom;
1873   Optional<int64_t> SeqStepNum, SeqAddend;
1874   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1875   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1876   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1877     // Assume undef elements match the sequence; we just have to be careful
1878     // when interpolating across them.
1879     if (Op.getOperand(Idx).isUndef())
1880       continue;
1881     // The BUILD_VECTOR must be all constants.
1882     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1883       return None;
1884 
1885     uint64_t Val = Op.getConstantOperandVal(Idx) &
1886                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1887 
1888     if (PrevElt) {
1889       // Calculate the step since the last non-undef element, and ensure
1890       // it's consistent across the entire sequence.
1891       unsigned IdxDiff = Idx - PrevElt->second;
1892       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1893 
1894       // A zero-value value difference means that we're somewhere in the middle
1895       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1896       // step change before evaluating the sequence.
1897       if (ValDiff == 0)
1898         continue;
1899 
1900       int64_t Remainder = ValDiff % IdxDiff;
1901       // Normalize the step if it's greater than 1.
1902       if (Remainder != ValDiff) {
1903         // The difference must cleanly divide the element span.
1904         if (Remainder != 0)
1905           return None;
1906         ValDiff /= IdxDiff;
1907         IdxDiff = 1;
1908       }
1909 
1910       if (!SeqStepNum)
1911         SeqStepNum = ValDiff;
1912       else if (ValDiff != SeqStepNum)
1913         return None;
1914 
1915       if (!SeqStepDenom)
1916         SeqStepDenom = IdxDiff;
1917       else if (IdxDiff != *SeqStepDenom)
1918         return None;
1919     }
1920 
1921     // Record this non-undef element for later.
1922     if (!PrevElt || PrevElt->first != Val)
1923       PrevElt = std::make_pair(Val, Idx);
1924   }
1925 
1926   // We need to have logged a step for this to count as a legal index sequence.
1927   if (!SeqStepNum || !SeqStepDenom)
1928     return None;
1929 
1930   // Loop back through the sequence and validate elements we might have skipped
1931   // while waiting for a valid step. While doing this, log any sequence addend.
1932   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1933     if (Op.getOperand(Idx).isUndef())
1934       continue;
1935     uint64_t Val = Op.getConstantOperandVal(Idx) &
1936                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1937     uint64_t ExpectedVal =
1938         (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1939     int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1940     if (!SeqAddend)
1941       SeqAddend = Addend;
1942     else if (Addend != SeqAddend)
1943       return None;
1944   }
1945 
1946   assert(SeqAddend && "Must have an addend if we have a step");
1947 
1948   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1949 }
1950 
1951 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1952 // and lower it as a VRGATHER_VX_VL from the source vector.
1953 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
1954                                   SelectionDAG &DAG,
1955                                   const RISCVSubtarget &Subtarget) {
1956   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1957     return SDValue();
1958   SDValue Vec = SplatVal.getOperand(0);
1959   // Only perform this optimization on vectors of the same size for simplicity.
1960   // Don't perform this optimization for i1 vectors.
1961   // FIXME: Support i1 vectors, maybe by promoting to i8?
1962   if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1)
1963     return SDValue();
1964   SDValue Idx = SplatVal.getOperand(1);
1965   // The index must be a legal type.
1966   if (Idx.getValueType() != Subtarget.getXLenVT())
1967     return SDValue();
1968 
1969   MVT ContainerVT = VT;
1970   if (VT.isFixedLengthVector()) {
1971     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1972     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
1973   }
1974 
1975   SDValue Mask, VL;
1976   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1977 
1978   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
1979                                Idx, Mask, DAG.getUNDEF(ContainerVT), VL);
1980 
1981   if (!VT.isFixedLengthVector())
1982     return Gather;
1983 
1984   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
1985 }
1986 
1987 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1988                                  const RISCVSubtarget &Subtarget) {
1989   MVT VT = Op.getSimpleValueType();
1990   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1991 
1992   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1993 
1994   SDLoc DL(Op);
1995   SDValue Mask, VL;
1996   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1997 
1998   MVT XLenVT = Subtarget.getXLenVT();
1999   unsigned NumElts = Op.getNumOperands();
2000 
2001   if (VT.getVectorElementType() == MVT::i1) {
2002     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
2003       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
2004       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
2005     }
2006 
2007     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
2008       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
2009       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
2010     }
2011 
2012     // Lower constant mask BUILD_VECTORs via an integer vector type, in
2013     // scalar integer chunks whose bit-width depends on the number of mask
2014     // bits and XLEN.
2015     // First, determine the most appropriate scalar integer type to use. This
2016     // is at most XLenVT, but may be shrunk to a smaller vector element type
2017     // according to the size of the final vector - use i8 chunks rather than
2018     // XLenVT if we're producing a v8i1. This results in more consistent
2019     // codegen across RV32 and RV64.
2020     unsigned NumViaIntegerBits =
2021         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2022     NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN());
2023     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2024       // If we have to use more than one INSERT_VECTOR_ELT then this
2025       // optimization is likely to increase code size; avoid peforming it in
2026       // such a case. We can use a load from a constant pool in this case.
2027       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2028         return SDValue();
2029       // Now we can create our integer vector type. Note that it may be larger
2030       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2031       MVT IntegerViaVecVT =
2032           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2033                            divideCeil(NumElts, NumViaIntegerBits));
2034 
2035       uint64_t Bits = 0;
2036       unsigned BitPos = 0, IntegerEltIdx = 0;
2037       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2038 
2039       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2040         // Once we accumulate enough bits to fill our scalar type, insert into
2041         // our vector and clear our accumulated data.
2042         if (I != 0 && I % NumViaIntegerBits == 0) {
2043           if (NumViaIntegerBits <= 32)
2044             Bits = SignExtend64<32>(Bits);
2045           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2046           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2047                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2048           Bits = 0;
2049           BitPos = 0;
2050           IntegerEltIdx++;
2051         }
2052         SDValue V = Op.getOperand(I);
2053         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2054         Bits |= ((uint64_t)BitValue << BitPos);
2055       }
2056 
2057       // Insert the (remaining) scalar value into position in our integer
2058       // vector type.
2059       if (NumViaIntegerBits <= 32)
2060         Bits = SignExtend64<32>(Bits);
2061       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2062       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2063                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2064 
2065       if (NumElts < NumViaIntegerBits) {
2066         // If we're producing a smaller vector than our minimum legal integer
2067         // type, bitcast to the equivalent (known-legal) mask type, and extract
2068         // our final mask.
2069         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2070         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2071         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2072                           DAG.getConstant(0, DL, XLenVT));
2073       } else {
2074         // Else we must have produced an integer type with the same size as the
2075         // mask type; bitcast for the final result.
2076         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2077         Vec = DAG.getBitcast(VT, Vec);
2078       }
2079 
2080       return Vec;
2081     }
2082 
2083     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2084     // vector type, we have a legal equivalently-sized i8 type, so we can use
2085     // that.
2086     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2087     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2088 
2089     SDValue WideVec;
2090     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2091       // For a splat, perform a scalar truncate before creating the wider
2092       // vector.
2093       assert(Splat.getValueType() == XLenVT &&
2094              "Unexpected type for i1 splat value");
2095       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2096                           DAG.getConstant(1, DL, XLenVT));
2097       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2098     } else {
2099       SmallVector<SDValue, 8> Ops(Op->op_values());
2100       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2101       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2102       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2103     }
2104 
2105     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2106   }
2107 
2108   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2109     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2110       return Gather;
2111     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2112                                         : RISCVISD::VMV_V_X_VL;
2113     Splat =
2114         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2115     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2116   }
2117 
2118   // Try and match index sequences, which we can lower to the vid instruction
2119   // with optional modifications. An all-undef vector is matched by
2120   // getSplatValue, above.
2121   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2122     int64_t StepNumerator = SimpleVID->StepNumerator;
2123     unsigned StepDenominator = SimpleVID->StepDenominator;
2124     int64_t Addend = SimpleVID->Addend;
2125 
2126     assert(StepNumerator != 0 && "Invalid step");
2127     bool Negate = false;
2128     int64_t SplatStepVal = StepNumerator;
2129     unsigned StepOpcode = ISD::MUL;
2130     if (StepNumerator != 1) {
2131       if (isPowerOf2_64(std::abs(StepNumerator))) {
2132         Negate = StepNumerator < 0;
2133         StepOpcode = ISD::SHL;
2134         SplatStepVal = Log2_64(std::abs(StepNumerator));
2135       }
2136     }
2137 
2138     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2139     // threshold since it's the immediate value many RVV instructions accept.
2140     // There is no vmul.vi instruction so ensure multiply constant can fit in
2141     // a single addi instruction.
2142     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2143          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2144         isPowerOf2_32(StepDenominator) &&
2145         (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) {
2146       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2147       // Convert right out of the scalable type so we can use standard ISD
2148       // nodes for the rest of the computation. If we used scalable types with
2149       // these, we'd lose the fixed-length vector info and generate worse
2150       // vsetvli code.
2151       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2152       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2153           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2154         SDValue SplatStep = DAG.getSplatBuildVector(
2155             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2156         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2157       }
2158       if (StepDenominator != 1) {
2159         SDValue SplatStep = DAG.getSplatBuildVector(
2160             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2161         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2162       }
2163       if (Addend != 0 || Negate) {
2164         SDValue SplatAddend = DAG.getSplatBuildVector(
2165             VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2166         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2167       }
2168       return VID;
2169     }
2170   }
2171 
2172   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2173   // when re-interpreted as a vector with a larger element type. For example,
2174   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2175   // could be instead splat as
2176   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2177   // TODO: This optimization could also work on non-constant splats, but it
2178   // would require bit-manipulation instructions to construct the splat value.
2179   SmallVector<SDValue> Sequence;
2180   unsigned EltBitSize = VT.getScalarSizeInBits();
2181   const auto *BV = cast<BuildVectorSDNode>(Op);
2182   if (VT.isInteger() && EltBitSize < 64 &&
2183       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2184       BV->getRepeatedSequence(Sequence) &&
2185       (Sequence.size() * EltBitSize) <= 64) {
2186     unsigned SeqLen = Sequence.size();
2187     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2188     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2189     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2190             ViaIntVT == MVT::i64) &&
2191            "Unexpected sequence type");
2192 
2193     unsigned EltIdx = 0;
2194     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2195     uint64_t SplatValue = 0;
2196     // Construct the amalgamated value which can be splatted as this larger
2197     // vector type.
2198     for (const auto &SeqV : Sequence) {
2199       if (!SeqV.isUndef())
2200         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2201                        << (EltIdx * EltBitSize));
2202       EltIdx++;
2203     }
2204 
2205     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2206     // achieve better constant materializion.
2207     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2208       SplatValue = SignExtend64<32>(SplatValue);
2209 
2210     // Since we can't introduce illegal i64 types at this stage, we can only
2211     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2212     // way we can use RVV instructions to splat.
2213     assert((ViaIntVT.bitsLE(XLenVT) ||
2214             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2215            "Unexpected bitcast sequence");
2216     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2217       SDValue ViaVL =
2218           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2219       MVT ViaContainerVT =
2220           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2221       SDValue Splat =
2222           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2223                       DAG.getUNDEF(ViaContainerVT),
2224                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2225       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2226       return DAG.getBitcast(VT, Splat);
2227     }
2228   }
2229 
2230   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2231   // which constitute a large proportion of the elements. In such cases we can
2232   // splat a vector with the dominant element and make up the shortfall with
2233   // INSERT_VECTOR_ELTs.
2234   // Note that this includes vectors of 2 elements by association. The
2235   // upper-most element is the "dominant" one, allowing us to use a splat to
2236   // "insert" the upper element, and an insert of the lower element at position
2237   // 0, which improves codegen.
2238   SDValue DominantValue;
2239   unsigned MostCommonCount = 0;
2240   DenseMap<SDValue, unsigned> ValueCounts;
2241   unsigned NumUndefElts =
2242       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2243 
2244   // Track the number of scalar loads we know we'd be inserting, estimated as
2245   // any non-zero floating-point constant. Other kinds of element are either
2246   // already in registers or are materialized on demand. The threshold at which
2247   // a vector load is more desirable than several scalar materializion and
2248   // vector-insertion instructions is not known.
2249   unsigned NumScalarLoads = 0;
2250 
2251   for (SDValue V : Op->op_values()) {
2252     if (V.isUndef())
2253       continue;
2254 
2255     ValueCounts.insert(std::make_pair(V, 0));
2256     unsigned &Count = ValueCounts[V];
2257 
2258     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2259       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2260 
2261     // Is this value dominant? In case of a tie, prefer the highest element as
2262     // it's cheaper to insert near the beginning of a vector than it is at the
2263     // end.
2264     if (++Count >= MostCommonCount) {
2265       DominantValue = V;
2266       MostCommonCount = Count;
2267     }
2268   }
2269 
2270   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2271   unsigned NumDefElts = NumElts - NumUndefElts;
2272   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2273 
2274   // Don't perform this optimization when optimizing for size, since
2275   // materializing elements and inserting them tends to cause code bloat.
2276   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2277       ((MostCommonCount > DominantValueCountThreshold) ||
2278        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2279     // Start by splatting the most common element.
2280     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2281 
2282     DenseSet<SDValue> Processed{DominantValue};
2283     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2284     for (const auto &OpIdx : enumerate(Op->ops())) {
2285       const SDValue &V = OpIdx.value();
2286       if (V.isUndef() || !Processed.insert(V).second)
2287         continue;
2288       if (ValueCounts[V] == 1) {
2289         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2290                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2291       } else {
2292         // Blend in all instances of this value using a VSELECT, using a
2293         // mask where each bit signals whether that element is the one
2294         // we're after.
2295         SmallVector<SDValue> Ops;
2296         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2297           return DAG.getConstant(V == V1, DL, XLenVT);
2298         });
2299         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2300                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2301                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2302       }
2303     }
2304 
2305     return Vec;
2306   }
2307 
2308   return SDValue();
2309 }
2310 
2311 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2312                                    SDValue Lo, SDValue Hi, SDValue VL,
2313                                    SelectionDAG &DAG) {
2314   if (!Passthru)
2315     Passthru = DAG.getUNDEF(VT);
2316   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2317     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2318     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2319     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2320     // node in order to try and match RVV vector/scalar instructions.
2321     if ((LoC >> 31) == HiC)
2322       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2323 
2324     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2325     // vmv.v.x whose EEW = 32 to lower it.
2326     auto *Const = dyn_cast<ConstantSDNode>(VL);
2327     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2328       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2329       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2330       // access the subtarget here now.
2331       auto InterVec = DAG.getNode(
2332           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2333                                   DAG.getRegister(RISCV::X0, MVT::i32));
2334       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2335     }
2336   }
2337 
2338   // Fall back to a stack store and stride x0 vector load.
2339   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2340                      Hi, VL);
2341 }
2342 
2343 // Called by type legalization to handle splat of i64 on RV32.
2344 // FIXME: We can optimize this when the type has sign or zero bits in one
2345 // of the halves.
2346 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2347                                    SDValue Scalar, SDValue VL,
2348                                    SelectionDAG &DAG) {
2349   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2350   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2351                            DAG.getConstant(0, DL, MVT::i32));
2352   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2353                            DAG.getConstant(1, DL, MVT::i32));
2354   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2355 }
2356 
2357 // This function lowers a splat of a scalar operand Splat with the vector
2358 // length VL. It ensures the final sequence is type legal, which is useful when
2359 // lowering a splat after type legalization.
2360 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2361                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2362                                 const RISCVSubtarget &Subtarget) {
2363   bool HasPassthru = Passthru && !Passthru.isUndef();
2364   if (!HasPassthru && !Passthru)
2365     Passthru = DAG.getUNDEF(VT);
2366   if (VT.isFloatingPoint()) {
2367     // If VL is 1, we could use vfmv.s.f.
2368     if (isOneConstant(VL))
2369       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2370     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2371   }
2372 
2373   MVT XLenVT = Subtarget.getXLenVT();
2374 
2375   // Simplest case is that the operand needs to be promoted to XLenVT.
2376   if (Scalar.getValueType().bitsLE(XLenVT)) {
2377     // If the operand is a constant, sign extend to increase our chances
2378     // of being able to use a .vi instruction. ANY_EXTEND would become a
2379     // a zero extend and the simm5 check in isel would fail.
2380     // FIXME: Should we ignore the upper bits in isel instead?
2381     unsigned ExtOpc =
2382         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2383     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2384     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2385     // If VL is 1 and the scalar value won't benefit from immediate, we could
2386     // use vmv.s.x.
2387     if (isOneConstant(VL) &&
2388         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2389       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2390     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2391   }
2392 
2393   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2394          "Unexpected scalar for splat lowering!");
2395 
2396   if (isOneConstant(VL) && isNullConstant(Scalar))
2397     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2398                        DAG.getConstant(0, DL, XLenVT), VL);
2399 
2400   // Otherwise use the more complicated splatting algorithm.
2401   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2402 }
2403 
2404 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2405                                 const RISCVSubtarget &Subtarget) {
2406   // We need to be able to widen elements to the next larger integer type.
2407   if (VT.getScalarSizeInBits() >= Subtarget.getELEN())
2408     return false;
2409 
2410   int Size = Mask.size();
2411   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2412 
2413   int Srcs[] = {-1, -1};
2414   for (int i = 0; i != Size; ++i) {
2415     // Ignore undef elements.
2416     if (Mask[i] < 0)
2417       continue;
2418 
2419     // Is this an even or odd element.
2420     int Pol = i % 2;
2421 
2422     // Ensure we consistently use the same source for this element polarity.
2423     int Src = Mask[i] / Size;
2424     if (Srcs[Pol] < 0)
2425       Srcs[Pol] = Src;
2426     if (Srcs[Pol] != Src)
2427       return false;
2428 
2429     // Make sure the element within the source is appropriate for this element
2430     // in the destination.
2431     int Elt = Mask[i] % Size;
2432     if (Elt != i / 2)
2433       return false;
2434   }
2435 
2436   // We need to find a source for each polarity and they can't be the same.
2437   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2438     return false;
2439 
2440   // Swap the sources if the second source was in the even polarity.
2441   SwapSources = Srcs[0] > Srcs[1];
2442 
2443   return true;
2444 }
2445 
2446 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2447 /// and then extract the original number of elements from the rotated result.
2448 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2449 /// returned rotation amount is for a rotate right, where elements move from
2450 /// higher elements to lower elements. \p LoSrc indicates the first source
2451 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2452 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2453 /// 0 or 1 if a rotation is found.
2454 ///
2455 /// NOTE: We talk about rotate to the right which matches how bit shift and
2456 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2457 /// and the table below write vectors with the lowest elements on the left.
2458 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2459   int Size = Mask.size();
2460 
2461   // We need to detect various ways of spelling a rotation:
2462   //   [11, 12, 13, 14, 15,  0,  1,  2]
2463   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2464   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2465   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2466   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2467   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2468   int Rotation = 0;
2469   LoSrc = -1;
2470   HiSrc = -1;
2471   for (int i = 0; i != Size; ++i) {
2472     int M = Mask[i];
2473     if (M < 0)
2474       continue;
2475 
2476     // Determine where a rotate vector would have started.
2477     int StartIdx = i - (M % Size);
2478     // The identity rotation isn't interesting, stop.
2479     if (StartIdx == 0)
2480       return -1;
2481 
2482     // If we found the tail of a vector the rotation must be the missing
2483     // front. If we found the head of a vector, it must be how much of the
2484     // head.
2485     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2486 
2487     if (Rotation == 0)
2488       Rotation = CandidateRotation;
2489     else if (Rotation != CandidateRotation)
2490       // The rotations don't match, so we can't match this mask.
2491       return -1;
2492 
2493     // Compute which value this mask is pointing at.
2494     int MaskSrc = M < Size ? 0 : 1;
2495 
2496     // Compute which of the two target values this index should be assigned to.
2497     // This reflects whether the high elements are remaining or the low elemnts
2498     // are remaining.
2499     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2500 
2501     // Either set up this value if we've not encountered it before, or check
2502     // that it remains consistent.
2503     if (TargetSrc < 0)
2504       TargetSrc = MaskSrc;
2505     else if (TargetSrc != MaskSrc)
2506       // This may be a rotation, but it pulls from the inputs in some
2507       // unsupported interleaving.
2508       return -1;
2509   }
2510 
2511   // Check that we successfully analyzed the mask, and normalize the results.
2512   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2513   assert((LoSrc >= 0 || HiSrc >= 0) &&
2514          "Failed to find a rotated input vector!");
2515 
2516   return Rotation;
2517 }
2518 
2519 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2520                                    const RISCVSubtarget &Subtarget) {
2521   SDValue V1 = Op.getOperand(0);
2522   SDValue V2 = Op.getOperand(1);
2523   SDLoc DL(Op);
2524   MVT XLenVT = Subtarget.getXLenVT();
2525   MVT VT = Op.getSimpleValueType();
2526   unsigned NumElts = VT.getVectorNumElements();
2527   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2528 
2529   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2530 
2531   SDValue TrueMask, VL;
2532   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2533 
2534   if (SVN->isSplat()) {
2535     const int Lane = SVN->getSplatIndex();
2536     if (Lane >= 0) {
2537       MVT SVT = VT.getVectorElementType();
2538 
2539       // Turn splatted vector load into a strided load with an X0 stride.
2540       SDValue V = V1;
2541       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2542       // with undef.
2543       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2544       int Offset = Lane;
2545       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2546         int OpElements =
2547             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2548         V = V.getOperand(Offset / OpElements);
2549         Offset %= OpElements;
2550       }
2551 
2552       // We need to ensure the load isn't atomic or volatile.
2553       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2554         auto *Ld = cast<LoadSDNode>(V);
2555         Offset *= SVT.getStoreSize();
2556         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2557                                                    TypeSize::Fixed(Offset), DL);
2558 
2559         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2560         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2561           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2562           SDValue IntID =
2563               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2564           SDValue Ops[] = {Ld->getChain(),
2565                            IntID,
2566                            DAG.getUNDEF(ContainerVT),
2567                            NewAddr,
2568                            DAG.getRegister(RISCV::X0, XLenVT),
2569                            VL};
2570           SDValue NewLoad = DAG.getMemIntrinsicNode(
2571               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2572               DAG.getMachineFunction().getMachineMemOperand(
2573                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2574           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2575           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2576         }
2577 
2578         // Otherwise use a scalar load and splat. This will give the best
2579         // opportunity to fold a splat into the operation. ISel can turn it into
2580         // the x0 strided load if we aren't able to fold away the select.
2581         if (SVT.isFloatingPoint())
2582           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2583                           Ld->getPointerInfo().getWithOffset(Offset),
2584                           Ld->getOriginalAlign(),
2585                           Ld->getMemOperand()->getFlags());
2586         else
2587           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2588                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2589                              Ld->getOriginalAlign(),
2590                              Ld->getMemOperand()->getFlags());
2591         DAG.makeEquivalentMemoryOrdering(Ld, V);
2592 
2593         unsigned Opc =
2594             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2595         SDValue Splat =
2596             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2597         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2598       }
2599 
2600       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2601       assert(Lane < (int)NumElts && "Unexpected lane!");
2602       SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT,
2603                                    V1, DAG.getConstant(Lane, DL, XLenVT),
2604                                    TrueMask, DAG.getUNDEF(ContainerVT), VL);
2605       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2606     }
2607   }
2608 
2609   ArrayRef<int> Mask = SVN->getMask();
2610 
2611   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2612   // be undef which can be handled with a single SLIDEDOWN/UP.
2613   int LoSrc, HiSrc;
2614   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2615   if (Rotation > 0) {
2616     SDValue LoV, HiV;
2617     if (LoSrc >= 0) {
2618       LoV = LoSrc == 0 ? V1 : V2;
2619       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2620     }
2621     if (HiSrc >= 0) {
2622       HiV = HiSrc == 0 ? V1 : V2;
2623       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2624     }
2625 
2626     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2627     // to slide LoV up by (NumElts - Rotation).
2628     unsigned InvRotate = NumElts - Rotation;
2629 
2630     SDValue Res = DAG.getUNDEF(ContainerVT);
2631     if (HiV) {
2632       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2633       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2634       // causes multiple vsetvlis in some test cases such as lowering
2635       // reduce.mul
2636       SDValue DownVL = VL;
2637       if (LoV)
2638         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2639       Res =
2640           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2641                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2642     }
2643     if (LoV)
2644       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2645                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2646 
2647     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2648   }
2649 
2650   // Detect an interleave shuffle and lower to
2651   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2652   bool SwapSources;
2653   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2654     // Swap sources if needed.
2655     if (SwapSources)
2656       std::swap(V1, V2);
2657 
2658     // Extract the lower half of the vectors.
2659     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2660     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2661                      DAG.getConstant(0, DL, XLenVT));
2662     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2663                      DAG.getConstant(0, DL, XLenVT));
2664 
2665     // Double the element width and halve the number of elements in an int type.
2666     unsigned EltBits = VT.getScalarSizeInBits();
2667     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2668     MVT WideIntVT =
2669         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2670     // Convert this to a scalable vector. We need to base this on the
2671     // destination size to ensure there's always a type with a smaller LMUL.
2672     MVT WideIntContainerVT =
2673         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2674 
2675     // Convert sources to scalable vectors with the same element count as the
2676     // larger type.
2677     MVT HalfContainerVT = MVT::getVectorVT(
2678         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2679     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2680     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2681 
2682     // Cast sources to integer.
2683     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2684     MVT IntHalfVT =
2685         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2686     V1 = DAG.getBitcast(IntHalfVT, V1);
2687     V2 = DAG.getBitcast(IntHalfVT, V2);
2688 
2689     // Freeze V2 since we use it twice and we need to be sure that the add and
2690     // multiply see the same value.
2691     V2 = DAG.getFreeze(V2);
2692 
2693     // Recreate TrueMask using the widened type's element count.
2694     TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG);
2695 
2696     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2697     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2698                               V2, TrueMask, VL);
2699     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2700     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2701                                      DAG.getUNDEF(IntHalfVT),
2702                                      DAG.getAllOnesConstant(DL, XLenVT));
2703     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2704                                    V2, Multiplier, TrueMask, VL);
2705     // Add the new copies to our previous addition giving us 2^eltbits copies of
2706     // V2. This is equivalent to shifting V2 left by eltbits. This should
2707     // combine with the vwmulu.vv above to form vwmaccu.vv.
2708     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2709                       TrueMask, VL);
2710     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2711     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2712     // vector VT.
2713     ContainerVT =
2714         MVT::getVectorVT(VT.getVectorElementType(),
2715                          WideIntContainerVT.getVectorElementCount() * 2);
2716     Add = DAG.getBitcast(ContainerVT, Add);
2717     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2718   }
2719 
2720   // Detect shuffles which can be re-expressed as vector selects; these are
2721   // shuffles in which each element in the destination is taken from an element
2722   // at the corresponding index in either source vectors.
2723   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2724     int MaskIndex = MaskIdx.value();
2725     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2726   });
2727 
2728   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2729 
2730   SmallVector<SDValue> MaskVals;
2731   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2732   // merged with a second vrgather.
2733   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2734 
2735   // By default we preserve the original operand order, and use a mask to
2736   // select LHS as true and RHS as false. However, since RVV vector selects may
2737   // feature splats but only on the LHS, we may choose to invert our mask and
2738   // instead select between RHS and LHS.
2739   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2740   bool InvertMask = IsSelect == SwapOps;
2741 
2742   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2743   // half.
2744   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2745 
2746   // Now construct the mask that will be used by the vselect or blended
2747   // vrgather operation. For vrgathers, construct the appropriate indices into
2748   // each vector.
2749   for (int MaskIndex : Mask) {
2750     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2751     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2752     if (!IsSelect) {
2753       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2754       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2755                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2756                                      : DAG.getUNDEF(XLenVT));
2757       GatherIndicesRHS.push_back(
2758           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2759                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2760       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2761         ++LHSIndexCounts[MaskIndex];
2762       if (!IsLHSOrUndefIndex)
2763         ++RHSIndexCounts[MaskIndex - NumElts];
2764     }
2765   }
2766 
2767   if (SwapOps) {
2768     std::swap(V1, V2);
2769     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2770   }
2771 
2772   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2773   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2774   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2775 
2776   if (IsSelect)
2777     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2778 
2779   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2780     // On such a large vector we're unable to use i8 as the index type.
2781     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2782     // may involve vector splitting if we're already at LMUL=8, or our
2783     // user-supplied maximum fixed-length LMUL.
2784     return SDValue();
2785   }
2786 
2787   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2788   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2789   MVT IndexVT = VT.changeTypeToInteger();
2790   // Since we can't introduce illegal index types at this stage, use i16 and
2791   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2792   // than XLenVT.
2793   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2794     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2795     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2796   }
2797 
2798   MVT IndexContainerVT =
2799       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2800 
2801   SDValue Gather;
2802   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2803   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2804   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2805     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2806                               Subtarget);
2807   } else {
2808     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2809     // If only one index is used, we can use a "splat" vrgather.
2810     // TODO: We can splat the most-common index and fix-up any stragglers, if
2811     // that's beneficial.
2812     if (LHSIndexCounts.size() == 1) {
2813       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2814       Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2815                            DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask,
2816                            DAG.getUNDEF(ContainerVT), VL);
2817     } else {
2818       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2819       LHSIndices =
2820           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2821 
2822       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2823                            TrueMask, DAG.getUNDEF(ContainerVT), VL);
2824     }
2825   }
2826 
2827   // If a second vector operand is used by this shuffle, blend it in with an
2828   // additional vrgather.
2829   if (!V2.isUndef()) {
2830     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2831 
2832     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2833     SelectMask =
2834         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2835 
2836     // If only one index is used, we can use a "splat" vrgather.
2837     // TODO: We can splat the most-common index and fix-up any stragglers, if
2838     // that's beneficial.
2839     if (RHSIndexCounts.size() == 1) {
2840       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2841       Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2842                            DAG.getConstant(SplatIndex, DL, XLenVT), SelectMask,
2843                            Gather, VL);
2844     } else {
2845       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2846       RHSIndices =
2847           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2848       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices,
2849                            SelectMask, Gather, VL);
2850     }
2851   }
2852 
2853   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2854 }
2855 
2856 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2857   // Support splats for any type. These should type legalize well.
2858   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2859     return true;
2860 
2861   // Only support legal VTs for other shuffles for now.
2862   if (!isTypeLegal(VT))
2863     return false;
2864 
2865   MVT SVT = VT.getSimpleVT();
2866 
2867   bool SwapSources;
2868   int LoSrc, HiSrc;
2869   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2870          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2871 }
2872 
2873 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2874 // the exponent.
2875 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2876   MVT VT = Op.getSimpleValueType();
2877   unsigned EltSize = VT.getScalarSizeInBits();
2878   SDValue Src = Op.getOperand(0);
2879   SDLoc DL(Op);
2880 
2881   // We need a FP type that can represent the value.
2882   // TODO: Use f16 for i8 when possible?
2883   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2884   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2885 
2886   // Legal types should have been checked in the RISCVTargetLowering
2887   // constructor.
2888   // TODO: Splitting may make sense in some cases.
2889   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2890          "Expected legal float type!");
2891 
2892   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2893   // The trailing zero count is equal to log2 of this single bit value.
2894   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2895     SDValue Neg =
2896         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2897     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2898   }
2899 
2900   // We have a legal FP type, convert to it.
2901   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2902   // Bitcast to integer and shift the exponent to the LSB.
2903   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2904   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2905   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2906   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2907                               DAG.getConstant(ShiftAmt, DL, IntVT));
2908   // Truncate back to original type to allow vnsrl.
2909   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2910   // The exponent contains log2 of the value in biased form.
2911   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2912 
2913   // For trailing zeros, we just need to subtract the bias.
2914   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2915     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2916                        DAG.getConstant(ExponentBias, DL, VT));
2917 
2918   // For leading zeros, we need to remove the bias and convert from log2 to
2919   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2920   unsigned Adjust = ExponentBias + (EltSize - 1);
2921   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2922 }
2923 
2924 // While RVV has alignment restrictions, we should always be able to load as a
2925 // legal equivalently-sized byte-typed vector instead. This method is
2926 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2927 // the load is already correctly-aligned, it returns SDValue().
2928 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2929                                                     SelectionDAG &DAG) const {
2930   auto *Load = cast<LoadSDNode>(Op);
2931   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2932 
2933   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2934                                      Load->getMemoryVT(),
2935                                      *Load->getMemOperand()))
2936     return SDValue();
2937 
2938   SDLoc DL(Op);
2939   MVT VT = Op.getSimpleValueType();
2940   unsigned EltSizeBits = VT.getScalarSizeInBits();
2941   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2942          "Unexpected unaligned RVV load type");
2943   MVT NewVT =
2944       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2945   assert(NewVT.isValid() &&
2946          "Expecting equally-sized RVV vector types to be legal");
2947   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2948                           Load->getPointerInfo(), Load->getOriginalAlign(),
2949                           Load->getMemOperand()->getFlags());
2950   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2951 }
2952 
2953 // While RVV has alignment restrictions, we should always be able to store as a
2954 // legal equivalently-sized byte-typed vector instead. This method is
2955 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2956 // returns SDValue() if the store is already correctly aligned.
2957 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2958                                                      SelectionDAG &DAG) const {
2959   auto *Store = cast<StoreSDNode>(Op);
2960   assert(Store && Store->getValue().getValueType().isVector() &&
2961          "Expected vector store");
2962 
2963   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2964                                      Store->getMemoryVT(),
2965                                      *Store->getMemOperand()))
2966     return SDValue();
2967 
2968   SDLoc DL(Op);
2969   SDValue StoredVal = Store->getValue();
2970   MVT VT = StoredVal.getSimpleValueType();
2971   unsigned EltSizeBits = VT.getScalarSizeInBits();
2972   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2973          "Unexpected unaligned RVV store type");
2974   MVT NewVT =
2975       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2976   assert(NewVT.isValid() &&
2977          "Expecting equally-sized RVV vector types to be legal");
2978   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2979   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2980                       Store->getPointerInfo(), Store->getOriginalAlign(),
2981                       Store->getMemOperand()->getFlags());
2982 }
2983 
2984 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG,
2985                              const RISCVSubtarget &Subtarget) {
2986   assert(Op.getValueType() == MVT::i64 && "Unexpected VT");
2987 
2988   int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue();
2989 
2990   // All simm32 constants should be handled by isel.
2991   // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making
2992   // this check redundant, but small immediates are common so this check
2993   // should have better compile time.
2994   if (isInt<32>(Imm))
2995     return Op;
2996 
2997   // We only need to cost the immediate, if constant pool lowering is enabled.
2998   if (!Subtarget.useConstantPoolForLargeInts())
2999     return Op;
3000 
3001   RISCVMatInt::InstSeq Seq =
3002       RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits());
3003   if (Seq.size() <= Subtarget.getMaxBuildIntsCost())
3004     return Op;
3005 
3006   // Expand to a constant pool using the default expansion code.
3007   return SDValue();
3008 }
3009 
3010 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
3011                                             SelectionDAG &DAG) const {
3012   switch (Op.getOpcode()) {
3013   default:
3014     report_fatal_error("unimplemented operand");
3015   case ISD::GlobalAddress:
3016     return lowerGlobalAddress(Op, DAG);
3017   case ISD::BlockAddress:
3018     return lowerBlockAddress(Op, DAG);
3019   case ISD::ConstantPool:
3020     return lowerConstantPool(Op, DAG);
3021   case ISD::JumpTable:
3022     return lowerJumpTable(Op, DAG);
3023   case ISD::GlobalTLSAddress:
3024     return lowerGlobalTLSAddress(Op, DAG);
3025   case ISD::Constant:
3026     return lowerConstant(Op, DAG, Subtarget);
3027   case ISD::SELECT:
3028     return lowerSELECT(Op, DAG);
3029   case ISD::BRCOND:
3030     return lowerBRCOND(Op, DAG);
3031   case ISD::VASTART:
3032     return lowerVASTART(Op, DAG);
3033   case ISD::FRAMEADDR:
3034     return lowerFRAMEADDR(Op, DAG);
3035   case ISD::RETURNADDR:
3036     return lowerRETURNADDR(Op, DAG);
3037   case ISD::SHL_PARTS:
3038     return lowerShiftLeftParts(Op, DAG);
3039   case ISD::SRA_PARTS:
3040     return lowerShiftRightParts(Op, DAG, true);
3041   case ISD::SRL_PARTS:
3042     return lowerShiftRightParts(Op, DAG, false);
3043   case ISD::BITCAST: {
3044     SDLoc DL(Op);
3045     EVT VT = Op.getValueType();
3046     SDValue Op0 = Op.getOperand(0);
3047     EVT Op0VT = Op0.getValueType();
3048     MVT XLenVT = Subtarget.getXLenVT();
3049     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3050       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3051       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3052       return FPConv;
3053     }
3054     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3055         Subtarget.hasStdExtF()) {
3056       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3057       SDValue FPConv =
3058           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3059       return FPConv;
3060     }
3061 
3062     // Consider other scalar<->scalar casts as legal if the types are legal.
3063     // Otherwise expand them.
3064     if (!VT.isVector() && !Op0VT.isVector()) {
3065       if (isTypeLegal(VT) && isTypeLegal(Op0VT))
3066         return Op;
3067       return SDValue();
3068     }
3069 
3070     assert(!VT.isScalableVector() && !Op0VT.isScalableVector() &&
3071            "Unexpected types");
3072 
3073     if (VT.isFixedLengthVector()) {
3074       // We can handle fixed length vector bitcasts with a simple replacement
3075       // in isel.
3076       if (Op0VT.isFixedLengthVector())
3077         return Op;
3078       // When bitcasting from scalar to fixed-length vector, insert the scalar
3079       // into a one-element vector of the result type, and perform a vector
3080       // bitcast.
3081       if (!Op0VT.isVector()) {
3082         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3083         if (!isTypeLegal(BVT))
3084           return SDValue();
3085         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3086                                               DAG.getUNDEF(BVT), Op0,
3087                                               DAG.getConstant(0, DL, XLenVT)));
3088       }
3089       return SDValue();
3090     }
3091     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3092     // thus: bitcast the vector to a one-element vector type whose element type
3093     // is the same as the result type, and extract the first element.
3094     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3095       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3096       if (!isTypeLegal(BVT))
3097         return SDValue();
3098       SDValue BVec = DAG.getBitcast(BVT, Op0);
3099       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3100                          DAG.getConstant(0, DL, XLenVT));
3101     }
3102     return SDValue();
3103   }
3104   case ISD::INTRINSIC_WO_CHAIN:
3105     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3106   case ISD::INTRINSIC_W_CHAIN:
3107     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3108   case ISD::INTRINSIC_VOID:
3109     return LowerINTRINSIC_VOID(Op, DAG);
3110   case ISD::BSWAP:
3111   case ISD::BITREVERSE: {
3112     MVT VT = Op.getSimpleValueType();
3113     SDLoc DL(Op);
3114     if (Subtarget.hasStdExtZbp()) {
3115       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3116       // Start with the maximum immediate value which is the bitwidth - 1.
3117       unsigned Imm = VT.getSizeInBits() - 1;
3118       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3119       if (Op.getOpcode() == ISD::BSWAP)
3120         Imm &= ~0x7U;
3121       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3122                          DAG.getConstant(Imm, DL, VT));
3123     }
3124     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3125     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3126     // Expand bitreverse to a bswap(rev8) followed by brev8.
3127     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3128     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3129     // as brev8 by an isel pattern.
3130     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3131                        DAG.getConstant(7, DL, VT));
3132   }
3133   case ISD::FSHL:
3134   case ISD::FSHR: {
3135     MVT VT = Op.getSimpleValueType();
3136     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3137     SDLoc DL(Op);
3138     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3139     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3140     // accidentally setting the extra bit.
3141     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3142     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3143                                 DAG.getConstant(ShAmtWidth, DL, VT));
3144     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3145     // instruction use different orders. fshl will return its first operand for
3146     // shift of zero, fshr will return its second operand. fsl and fsr both
3147     // return rs1 so the ISD nodes need to have different operand orders.
3148     // Shift amount is in rs2.
3149     SDValue Op0 = Op.getOperand(0);
3150     SDValue Op1 = Op.getOperand(1);
3151     unsigned Opc = RISCVISD::FSL;
3152     if (Op.getOpcode() == ISD::FSHR) {
3153       std::swap(Op0, Op1);
3154       Opc = RISCVISD::FSR;
3155     }
3156     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3157   }
3158   case ISD::TRUNCATE:
3159     // Only custom-lower vector truncates
3160     if (!Op.getSimpleValueType().isVector())
3161       return Op;
3162     return lowerVectorTruncLike(Op, DAG);
3163   case ISD::ANY_EXTEND:
3164   case ISD::ZERO_EXTEND:
3165     if (Op.getOperand(0).getValueType().isVector() &&
3166         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3167       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3168     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3169   case ISD::SIGN_EXTEND:
3170     if (Op.getOperand(0).getValueType().isVector() &&
3171         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3172       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3173     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3174   case ISD::SPLAT_VECTOR_PARTS:
3175     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3176   case ISD::INSERT_VECTOR_ELT:
3177     return lowerINSERT_VECTOR_ELT(Op, DAG);
3178   case ISD::EXTRACT_VECTOR_ELT:
3179     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3180   case ISD::VSCALE: {
3181     MVT VT = Op.getSimpleValueType();
3182     SDLoc DL(Op);
3183     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3184     // We define our scalable vector types for lmul=1 to use a 64 bit known
3185     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3186     // vscale as VLENB / 8.
3187     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3188     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3189       report_fatal_error("Support for VLEN==32 is incomplete.");
3190     // We assume VLENB is a multiple of 8. We manually choose the best shift
3191     // here because SimplifyDemandedBits isn't always able to simplify it.
3192     uint64_t Val = Op.getConstantOperandVal(0);
3193     if (isPowerOf2_64(Val)) {
3194       uint64_t Log2 = Log2_64(Val);
3195       if (Log2 < 3)
3196         return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3197                            DAG.getConstant(3 - Log2, DL, VT));
3198       if (Log2 > 3)
3199         return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3200                            DAG.getConstant(Log2 - 3, DL, VT));
3201       return VLENB;
3202     }
3203     // If the multiplier is a multiple of 8, scale it down to avoid needing
3204     // to shift the VLENB value.
3205     if ((Val % 8) == 0)
3206       return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3207                          DAG.getConstant(Val / 8, DL, VT));
3208 
3209     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3210                                  DAG.getConstant(3, DL, VT));
3211     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3212   }
3213   case ISD::FPOWI: {
3214     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3215     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3216     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3217         Op.getOperand(1).getValueType() == MVT::i32) {
3218       SDLoc DL(Op);
3219       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3220       SDValue Powi =
3221           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3222       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3223                          DAG.getIntPtrConstant(0, DL));
3224     }
3225     return SDValue();
3226   }
3227   case ISD::FP_EXTEND:
3228   case ISD::FP_ROUND:
3229     if (!Op.getValueType().isVector())
3230       return Op;
3231     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3232   case ISD::FP_TO_SINT:
3233   case ISD::FP_TO_UINT:
3234   case ISD::SINT_TO_FP:
3235   case ISD::UINT_TO_FP: {
3236     // RVV can only do fp<->int conversions to types half/double the size as
3237     // the source. We custom-lower any conversions that do two hops into
3238     // sequences.
3239     MVT VT = Op.getSimpleValueType();
3240     if (!VT.isVector())
3241       return Op;
3242     SDLoc DL(Op);
3243     SDValue Src = Op.getOperand(0);
3244     MVT EltVT = VT.getVectorElementType();
3245     MVT SrcVT = Src.getSimpleValueType();
3246     MVT SrcEltVT = SrcVT.getVectorElementType();
3247     unsigned EltSize = EltVT.getSizeInBits();
3248     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3249     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3250            "Unexpected vector element types");
3251 
3252     bool IsInt2FP = SrcEltVT.isInteger();
3253     // Widening conversions
3254     if (EltSize > (2 * SrcEltSize)) {
3255       if (IsInt2FP) {
3256         // Do a regular integer sign/zero extension then convert to float.
3257         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize),
3258                                       VT.getVectorElementCount());
3259         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3260                                  ? ISD::ZERO_EXTEND
3261                                  : ISD::SIGN_EXTEND;
3262         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3263         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3264       }
3265       // FP2Int
3266       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3267       // Do one doubling fp_extend then complete the operation by converting
3268       // to int.
3269       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3270       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3271       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3272     }
3273 
3274     // Narrowing conversions
3275     if (SrcEltSize > (2 * EltSize)) {
3276       if (IsInt2FP) {
3277         // One narrowing int_to_fp, then an fp_round.
3278         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3279         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3280         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3281         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3282       }
3283       // FP2Int
3284       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3285       // representable by the integer, the result is poison.
3286       MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
3287                                     VT.getVectorElementCount());
3288       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3289       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3290     }
3291 
3292     // Scalable vectors can exit here. Patterns will handle equally-sized
3293     // conversions halving/doubling ones.
3294     if (!VT.isFixedLengthVector())
3295       return Op;
3296 
3297     // For fixed-length vectors we lower to a custom "VL" node.
3298     unsigned RVVOpc = 0;
3299     switch (Op.getOpcode()) {
3300     default:
3301       llvm_unreachable("Impossible opcode");
3302     case ISD::FP_TO_SINT:
3303       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3304       break;
3305     case ISD::FP_TO_UINT:
3306       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3307       break;
3308     case ISD::SINT_TO_FP:
3309       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3310       break;
3311     case ISD::UINT_TO_FP:
3312       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3313       break;
3314     }
3315 
3316     MVT ContainerVT, SrcContainerVT;
3317     // Derive the reference container type from the larger vector type.
3318     if (SrcEltSize > EltSize) {
3319       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3320       ContainerVT =
3321           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3322     } else {
3323       ContainerVT = getContainerForFixedLengthVector(VT);
3324       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3325     }
3326 
3327     SDValue Mask, VL;
3328     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3329 
3330     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3331     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3332     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3333   }
3334   case ISD::FP_TO_SINT_SAT:
3335   case ISD::FP_TO_UINT_SAT:
3336     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3337   case ISD::FTRUNC:
3338   case ISD::FCEIL:
3339   case ISD::FFLOOR:
3340     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3341   case ISD::FROUND:
3342     return lowerFROUND(Op, DAG);
3343   case ISD::VECREDUCE_ADD:
3344   case ISD::VECREDUCE_UMAX:
3345   case ISD::VECREDUCE_SMAX:
3346   case ISD::VECREDUCE_UMIN:
3347   case ISD::VECREDUCE_SMIN:
3348     return lowerVECREDUCE(Op, DAG);
3349   case ISD::VECREDUCE_AND:
3350   case ISD::VECREDUCE_OR:
3351   case ISD::VECREDUCE_XOR:
3352     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3353       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3354     return lowerVECREDUCE(Op, DAG);
3355   case ISD::VECREDUCE_FADD:
3356   case ISD::VECREDUCE_SEQ_FADD:
3357   case ISD::VECREDUCE_FMIN:
3358   case ISD::VECREDUCE_FMAX:
3359     return lowerFPVECREDUCE(Op, DAG);
3360   case ISD::VP_REDUCE_ADD:
3361   case ISD::VP_REDUCE_UMAX:
3362   case ISD::VP_REDUCE_SMAX:
3363   case ISD::VP_REDUCE_UMIN:
3364   case ISD::VP_REDUCE_SMIN:
3365   case ISD::VP_REDUCE_FADD:
3366   case ISD::VP_REDUCE_SEQ_FADD:
3367   case ISD::VP_REDUCE_FMIN:
3368   case ISD::VP_REDUCE_FMAX:
3369     return lowerVPREDUCE(Op, DAG);
3370   case ISD::VP_REDUCE_AND:
3371   case ISD::VP_REDUCE_OR:
3372   case ISD::VP_REDUCE_XOR:
3373     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3374       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3375     return lowerVPREDUCE(Op, DAG);
3376   case ISD::INSERT_SUBVECTOR:
3377     return lowerINSERT_SUBVECTOR(Op, DAG);
3378   case ISD::EXTRACT_SUBVECTOR:
3379     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3380   case ISD::STEP_VECTOR:
3381     return lowerSTEP_VECTOR(Op, DAG);
3382   case ISD::VECTOR_REVERSE:
3383     return lowerVECTOR_REVERSE(Op, DAG);
3384   case ISD::VECTOR_SPLICE:
3385     return lowerVECTOR_SPLICE(Op, DAG);
3386   case ISD::BUILD_VECTOR:
3387     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3388   case ISD::SPLAT_VECTOR:
3389     if (Op.getValueType().getVectorElementType() == MVT::i1)
3390       return lowerVectorMaskSplat(Op, DAG);
3391     return SDValue();
3392   case ISD::VECTOR_SHUFFLE:
3393     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3394   case ISD::CONCAT_VECTORS: {
3395     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3396     // better than going through the stack, as the default expansion does.
3397     SDLoc DL(Op);
3398     MVT VT = Op.getSimpleValueType();
3399     unsigned NumOpElts =
3400         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3401     SDValue Vec = DAG.getUNDEF(VT);
3402     for (const auto &OpIdx : enumerate(Op->ops())) {
3403       SDValue SubVec = OpIdx.value();
3404       // Don't insert undef subvectors.
3405       if (SubVec.isUndef())
3406         continue;
3407       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3408                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3409     }
3410     return Vec;
3411   }
3412   case ISD::LOAD:
3413     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3414       return V;
3415     if (Op.getValueType().isFixedLengthVector())
3416       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3417     return Op;
3418   case ISD::STORE:
3419     if (auto V = expandUnalignedRVVStore(Op, DAG))
3420       return V;
3421     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3422       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3423     return Op;
3424   case ISD::MLOAD:
3425   case ISD::VP_LOAD:
3426     return lowerMaskedLoad(Op, DAG);
3427   case ISD::MSTORE:
3428   case ISD::VP_STORE:
3429     return lowerMaskedStore(Op, DAG);
3430   case ISD::SETCC:
3431     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3432   case ISD::ADD:
3433     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3434   case ISD::SUB:
3435     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3436   case ISD::MUL:
3437     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3438   case ISD::MULHS:
3439     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3440   case ISD::MULHU:
3441     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3442   case ISD::AND:
3443     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3444                                               RISCVISD::AND_VL);
3445   case ISD::OR:
3446     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3447                                               RISCVISD::OR_VL);
3448   case ISD::XOR:
3449     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3450                                               RISCVISD::XOR_VL);
3451   case ISD::SDIV:
3452     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3453   case ISD::SREM:
3454     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3455   case ISD::UDIV:
3456     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3457   case ISD::UREM:
3458     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3459   case ISD::SHL:
3460   case ISD::SRA:
3461   case ISD::SRL:
3462     if (Op.getSimpleValueType().isFixedLengthVector())
3463       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3464     // This can be called for an i32 shift amount that needs to be promoted.
3465     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3466            "Unexpected custom legalisation");
3467     return SDValue();
3468   case ISD::SADDSAT:
3469     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3470   case ISD::UADDSAT:
3471     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3472   case ISD::SSUBSAT:
3473     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3474   case ISD::USUBSAT:
3475     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3476   case ISD::FADD:
3477     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3478   case ISD::FSUB:
3479     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3480   case ISD::FMUL:
3481     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3482   case ISD::FDIV:
3483     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3484   case ISD::FNEG:
3485     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3486   case ISD::FABS:
3487     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3488   case ISD::FSQRT:
3489     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3490   case ISD::FMA:
3491     return lowerToScalableOp(Op, DAG, RISCVISD::VFMADD_VL);
3492   case ISD::SMIN:
3493     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3494   case ISD::SMAX:
3495     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3496   case ISD::UMIN:
3497     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3498   case ISD::UMAX:
3499     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3500   case ISD::FMINNUM:
3501     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3502   case ISD::FMAXNUM:
3503     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3504   case ISD::ABS:
3505     return lowerABS(Op, DAG);
3506   case ISD::CTLZ_ZERO_UNDEF:
3507   case ISD::CTTZ_ZERO_UNDEF:
3508     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3509   case ISD::VSELECT:
3510     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3511   case ISD::FCOPYSIGN:
3512     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3513   case ISD::MGATHER:
3514   case ISD::VP_GATHER:
3515     return lowerMaskedGather(Op, DAG);
3516   case ISD::MSCATTER:
3517   case ISD::VP_SCATTER:
3518     return lowerMaskedScatter(Op, DAG);
3519   case ISD::FLT_ROUNDS_:
3520     return lowerGET_ROUNDING(Op, DAG);
3521   case ISD::SET_ROUNDING:
3522     return lowerSET_ROUNDING(Op, DAG);
3523   case ISD::EH_DWARF_CFA:
3524     return lowerEH_DWARF_CFA(Op, DAG);
3525   case ISD::VP_SELECT:
3526     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3527   case ISD::VP_MERGE:
3528     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3529   case ISD::VP_ADD:
3530     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3531   case ISD::VP_SUB:
3532     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3533   case ISD::VP_MUL:
3534     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3535   case ISD::VP_SDIV:
3536     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3537   case ISD::VP_UDIV:
3538     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3539   case ISD::VP_SREM:
3540     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3541   case ISD::VP_UREM:
3542     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3543   case ISD::VP_AND:
3544     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3545   case ISD::VP_OR:
3546     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3547   case ISD::VP_XOR:
3548     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3549   case ISD::VP_ASHR:
3550     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3551   case ISD::VP_LSHR:
3552     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3553   case ISD::VP_SHL:
3554     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3555   case ISD::VP_FADD:
3556     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3557   case ISD::VP_FSUB:
3558     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3559   case ISD::VP_FMUL:
3560     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3561   case ISD::VP_FDIV:
3562     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3563   case ISD::VP_FNEG:
3564     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3565   case ISD::VP_FMA:
3566     return lowerVPOp(Op, DAG, RISCVISD::VFMADD_VL);
3567   case ISD::VP_SIGN_EXTEND:
3568   case ISD::VP_ZERO_EXTEND:
3569     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3570       return lowerVPExtMaskOp(Op, DAG);
3571     return lowerVPOp(Op, DAG,
3572                      Op.getOpcode() == ISD::VP_SIGN_EXTEND
3573                          ? RISCVISD::VSEXT_VL
3574                          : RISCVISD::VZEXT_VL);
3575   case ISD::VP_TRUNCATE:
3576     return lowerVectorTruncLike(Op, DAG);
3577   case ISD::VP_FP_EXTEND:
3578   case ISD::VP_FP_ROUND:
3579     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3580   case ISD::VP_FPTOSI:
3581     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL);
3582   case ISD::VP_FPTOUI:
3583     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL);
3584   case ISD::VP_SITOFP:
3585     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
3586   case ISD::VP_UITOFP:
3587     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL);
3588   case ISD::VP_SETCC:
3589     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3590       return lowerVPSetCCMaskOp(Op, DAG);
3591     return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL);
3592   }
3593 }
3594 
3595 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3596                              SelectionDAG &DAG, unsigned Flags) {
3597   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3598 }
3599 
3600 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3601                              SelectionDAG &DAG, unsigned Flags) {
3602   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3603                                    Flags);
3604 }
3605 
3606 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3607                              SelectionDAG &DAG, unsigned Flags) {
3608   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3609                                    N->getOffset(), Flags);
3610 }
3611 
3612 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3613                              SelectionDAG &DAG, unsigned Flags) {
3614   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3615 }
3616 
3617 template <class NodeTy>
3618 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3619                                      bool IsLocal) const {
3620   SDLoc DL(N);
3621   EVT Ty = getPointerTy(DAG.getDataLayout());
3622 
3623   if (isPositionIndependent()) {
3624     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3625     if (IsLocal)
3626       // Use PC-relative addressing to access the symbol. This generates the
3627       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3628       // %pcrel_lo(auipc)).
3629       return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
3630 
3631     // Use PC-relative addressing to access the GOT for this symbol, then load
3632     // the address from the GOT. This generates the pattern (PseudoLA sym),
3633     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3634     MachineFunction &MF = DAG.getMachineFunction();
3635     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3636         MachinePointerInfo::getGOT(MF),
3637         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3638             MachineMemOperand::MOInvariant,
3639         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3640     SDValue Load =
3641         DAG.getMemIntrinsicNode(RISCVISD::LA, DL, DAG.getVTList(Ty, MVT::Other),
3642                                 {DAG.getEntryNode(), Addr}, Ty, MemOp);
3643     return Load;
3644   }
3645 
3646   switch (getTargetMachine().getCodeModel()) {
3647   default:
3648     report_fatal_error("Unsupported code model for lowering");
3649   case CodeModel::Small: {
3650     // Generate a sequence for accessing addresses within the first 2 GiB of
3651     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3652     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3653     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3654     SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
3655     return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo);
3656   }
3657   case CodeModel::Medium: {
3658     // Generate a sequence for accessing addresses within any 2GiB range within
3659     // the address space. This generates the pattern (PseudoLLA sym), which
3660     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3661     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3662     return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
3663   }
3664   }
3665 }
3666 
3667 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3668                                                 SelectionDAG &DAG) const {
3669   SDLoc DL(Op);
3670   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3671   assert(N->getOffset() == 0 && "unexpected offset in global node");
3672 
3673   const GlobalValue *GV = N->getGlobal();
3674   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3675   return getAddr(N, DAG, IsLocal);
3676 }
3677 
3678 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3679                                                SelectionDAG &DAG) const {
3680   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3681 
3682   return getAddr(N, DAG);
3683 }
3684 
3685 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3686                                                SelectionDAG &DAG) const {
3687   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3688 
3689   return getAddr(N, DAG);
3690 }
3691 
3692 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3693                                             SelectionDAG &DAG) const {
3694   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3695 
3696   return getAddr(N, DAG);
3697 }
3698 
3699 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3700                                               SelectionDAG &DAG,
3701                                               bool UseGOT) const {
3702   SDLoc DL(N);
3703   EVT Ty = getPointerTy(DAG.getDataLayout());
3704   const GlobalValue *GV = N->getGlobal();
3705   MVT XLenVT = Subtarget.getXLenVT();
3706 
3707   if (UseGOT) {
3708     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3709     // load the address from the GOT and add the thread pointer. This generates
3710     // the pattern (PseudoLA_TLS_IE sym), which expands to
3711     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3712     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3713     MachineFunction &MF = DAG.getMachineFunction();
3714     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3715         MachinePointerInfo::getGOT(MF),
3716         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3717             MachineMemOperand::MOInvariant,
3718         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3719     SDValue Load = DAG.getMemIntrinsicNode(
3720         RISCVISD::LA_TLS_IE, DL, DAG.getVTList(Ty, MVT::Other),
3721         {DAG.getEntryNode(), Addr}, Ty, MemOp);
3722 
3723     // Add the thread pointer.
3724     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3725     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3726   }
3727 
3728   // Generate a sequence for accessing the address relative to the thread
3729   // pointer, with the appropriate adjustment for the thread pointer offset.
3730   // This generates the pattern
3731   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3732   SDValue AddrHi =
3733       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3734   SDValue AddrAdd =
3735       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3736   SDValue AddrLo =
3737       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3738 
3739   SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
3740   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3741   SDValue MNAdd =
3742       DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd);
3743   return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo);
3744 }
3745 
3746 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3747                                                SelectionDAG &DAG) const {
3748   SDLoc DL(N);
3749   EVT Ty = getPointerTy(DAG.getDataLayout());
3750   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3751   const GlobalValue *GV = N->getGlobal();
3752 
3753   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3754   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3755   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3756   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3757   SDValue Load = DAG.getNode(RISCVISD::LA_TLS_GD, DL, Ty, Addr);
3758 
3759   // Prepare argument list to generate call.
3760   ArgListTy Args;
3761   ArgListEntry Entry;
3762   Entry.Node = Load;
3763   Entry.Ty = CallTy;
3764   Args.push_back(Entry);
3765 
3766   // Setup call to __tls_get_addr.
3767   TargetLowering::CallLoweringInfo CLI(DAG);
3768   CLI.setDebugLoc(DL)
3769       .setChain(DAG.getEntryNode())
3770       .setLibCallee(CallingConv::C, CallTy,
3771                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3772                     std::move(Args));
3773 
3774   return LowerCallTo(CLI).first;
3775 }
3776 
3777 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3778                                                    SelectionDAG &DAG) const {
3779   SDLoc DL(Op);
3780   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3781   assert(N->getOffset() == 0 && "unexpected offset in global node");
3782 
3783   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3784 
3785   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3786       CallingConv::GHC)
3787     report_fatal_error("In GHC calling convention TLS is not supported");
3788 
3789   SDValue Addr;
3790   switch (Model) {
3791   case TLSModel::LocalExec:
3792     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3793     break;
3794   case TLSModel::InitialExec:
3795     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3796     break;
3797   case TLSModel::LocalDynamic:
3798   case TLSModel::GeneralDynamic:
3799     Addr = getDynamicTLSAddr(N, DAG);
3800     break;
3801   }
3802 
3803   return Addr;
3804 }
3805 
3806 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3807   SDValue CondV = Op.getOperand(0);
3808   SDValue TrueV = Op.getOperand(1);
3809   SDValue FalseV = Op.getOperand(2);
3810   SDLoc DL(Op);
3811   MVT VT = Op.getSimpleValueType();
3812   MVT XLenVT = Subtarget.getXLenVT();
3813 
3814   // Lower vector SELECTs to VSELECTs by splatting the condition.
3815   if (VT.isVector()) {
3816     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3817     SDValue CondSplat = VT.isScalableVector()
3818                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3819                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3820     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3821   }
3822 
3823   // If the result type is XLenVT and CondV is the output of a SETCC node
3824   // which also operated on XLenVT inputs, then merge the SETCC node into the
3825   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3826   // compare+branch instructions. i.e.:
3827   // (select (setcc lhs, rhs, cc), truev, falsev)
3828   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3829   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3830       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3831     SDValue LHS = CondV.getOperand(0);
3832     SDValue RHS = CondV.getOperand(1);
3833     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3834     ISD::CondCode CCVal = CC->get();
3835 
3836     // Special case for a select of 2 constants that have a diffence of 1.
3837     // Normally this is done by DAGCombine, but if the select is introduced by
3838     // type legalization or op legalization, we miss it. Restricting to SETLT
3839     // case for now because that is what signed saturating add/sub need.
3840     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3841     // but we would probably want to swap the true/false values if the condition
3842     // is SETGE/SETLE to avoid an XORI.
3843     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3844         CCVal == ISD::SETLT) {
3845       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3846       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3847       if (TrueVal - 1 == FalseVal)
3848         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3849       if (TrueVal + 1 == FalseVal)
3850         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3851     }
3852 
3853     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3854 
3855     SDValue TargetCC = DAG.getCondCode(CCVal);
3856     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3857     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3858   }
3859 
3860   // Otherwise:
3861   // (select condv, truev, falsev)
3862   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3863   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3864   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3865 
3866   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3867 
3868   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3869 }
3870 
3871 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3872   SDValue CondV = Op.getOperand(1);
3873   SDLoc DL(Op);
3874   MVT XLenVT = Subtarget.getXLenVT();
3875 
3876   if (CondV.getOpcode() == ISD::SETCC &&
3877       CondV.getOperand(0).getValueType() == XLenVT) {
3878     SDValue LHS = CondV.getOperand(0);
3879     SDValue RHS = CondV.getOperand(1);
3880     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3881 
3882     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3883 
3884     SDValue TargetCC = DAG.getCondCode(CCVal);
3885     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3886                        LHS, RHS, TargetCC, Op.getOperand(2));
3887   }
3888 
3889   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3890                      CondV, DAG.getConstant(0, DL, XLenVT),
3891                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3892 }
3893 
3894 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3895   MachineFunction &MF = DAG.getMachineFunction();
3896   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3897 
3898   SDLoc DL(Op);
3899   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3900                                  getPointerTy(MF.getDataLayout()));
3901 
3902   // vastart just stores the address of the VarArgsFrameIndex slot into the
3903   // memory location argument.
3904   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3905   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3906                       MachinePointerInfo(SV));
3907 }
3908 
3909 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3910                                             SelectionDAG &DAG) const {
3911   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3912   MachineFunction &MF = DAG.getMachineFunction();
3913   MachineFrameInfo &MFI = MF.getFrameInfo();
3914   MFI.setFrameAddressIsTaken(true);
3915   Register FrameReg = RI.getFrameRegister(MF);
3916   int XLenInBytes = Subtarget.getXLen() / 8;
3917 
3918   EVT VT = Op.getValueType();
3919   SDLoc DL(Op);
3920   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3921   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3922   while (Depth--) {
3923     int Offset = -(XLenInBytes * 2);
3924     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3925                               DAG.getIntPtrConstant(Offset, DL));
3926     FrameAddr =
3927         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3928   }
3929   return FrameAddr;
3930 }
3931 
3932 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3933                                              SelectionDAG &DAG) const {
3934   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3935   MachineFunction &MF = DAG.getMachineFunction();
3936   MachineFrameInfo &MFI = MF.getFrameInfo();
3937   MFI.setReturnAddressIsTaken(true);
3938   MVT XLenVT = Subtarget.getXLenVT();
3939   int XLenInBytes = Subtarget.getXLen() / 8;
3940 
3941   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3942     return SDValue();
3943 
3944   EVT VT = Op.getValueType();
3945   SDLoc DL(Op);
3946   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3947   if (Depth) {
3948     int Off = -XLenInBytes;
3949     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3950     SDValue Offset = DAG.getConstant(Off, DL, VT);
3951     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3952                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3953                        MachinePointerInfo());
3954   }
3955 
3956   // Return the value of the return address register, marking it an implicit
3957   // live-in.
3958   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3959   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3960 }
3961 
3962 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3963                                                  SelectionDAG &DAG) const {
3964   SDLoc DL(Op);
3965   SDValue Lo = Op.getOperand(0);
3966   SDValue Hi = Op.getOperand(1);
3967   SDValue Shamt = Op.getOperand(2);
3968   EVT VT = Lo.getValueType();
3969 
3970   // if Shamt-XLEN < 0: // Shamt < XLEN
3971   //   Lo = Lo << Shamt
3972   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
3973   // else:
3974   //   Lo = 0
3975   //   Hi = Lo << (Shamt-XLEN)
3976 
3977   SDValue Zero = DAG.getConstant(0, DL, VT);
3978   SDValue One = DAG.getConstant(1, DL, VT);
3979   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3980   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3981   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3982   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
3983 
3984   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3985   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3986   SDValue ShiftRightLo =
3987       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3988   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3989   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3990   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3991 
3992   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3993 
3994   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3995   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3996 
3997   SDValue Parts[2] = {Lo, Hi};
3998   return DAG.getMergeValues(Parts, DL);
3999 }
4000 
4001 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
4002                                                   bool IsSRA) const {
4003   SDLoc DL(Op);
4004   SDValue Lo = Op.getOperand(0);
4005   SDValue Hi = Op.getOperand(1);
4006   SDValue Shamt = Op.getOperand(2);
4007   EVT VT = Lo.getValueType();
4008 
4009   // SRA expansion:
4010   //   if Shamt-XLEN < 0: // Shamt < XLEN
4011   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4012   //     Hi = Hi >>s Shamt
4013   //   else:
4014   //     Lo = Hi >>s (Shamt-XLEN);
4015   //     Hi = Hi >>s (XLEN-1)
4016   //
4017   // SRL expansion:
4018   //   if Shamt-XLEN < 0: // Shamt < XLEN
4019   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4020   //     Hi = Hi >>u Shamt
4021   //   else:
4022   //     Lo = Hi >>u (Shamt-XLEN);
4023   //     Hi = 0;
4024 
4025   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4026 
4027   SDValue Zero = DAG.getConstant(0, DL, VT);
4028   SDValue One = DAG.getConstant(1, DL, VT);
4029   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4030   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4031   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4032   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4033 
4034   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4035   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4036   SDValue ShiftLeftHi =
4037       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4038   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4039   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4040   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4041   SDValue HiFalse =
4042       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4043 
4044   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4045 
4046   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4047   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4048 
4049   SDValue Parts[2] = {Lo, Hi};
4050   return DAG.getMergeValues(Parts, DL);
4051 }
4052 
4053 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4054 // legal equivalently-sized i8 type, so we can use that as a go-between.
4055 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4056                                                   SelectionDAG &DAG) const {
4057   SDLoc DL(Op);
4058   MVT VT = Op.getSimpleValueType();
4059   SDValue SplatVal = Op.getOperand(0);
4060   // All-zeros or all-ones splats are handled specially.
4061   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4062     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4063     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4064   }
4065   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4066     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4067     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4068   }
4069   MVT XLenVT = Subtarget.getXLenVT();
4070   assert(SplatVal.getValueType() == XLenVT &&
4071          "Unexpected type for i1 splat value");
4072   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4073   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4074                          DAG.getConstant(1, DL, XLenVT));
4075   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4076   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4077   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4078 }
4079 
4080 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4081 // illegal (currently only vXi64 RV32).
4082 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4083 // them to VMV_V_X_VL.
4084 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4085                                                      SelectionDAG &DAG) const {
4086   SDLoc DL(Op);
4087   MVT VecVT = Op.getSimpleValueType();
4088   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4089          "Unexpected SPLAT_VECTOR_PARTS lowering");
4090 
4091   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4092   SDValue Lo = Op.getOperand(0);
4093   SDValue Hi = Op.getOperand(1);
4094 
4095   if (VecVT.isFixedLengthVector()) {
4096     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4097     SDLoc DL(Op);
4098     SDValue Mask, VL;
4099     std::tie(Mask, VL) =
4100         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4101 
4102     SDValue Res =
4103         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4104     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4105   }
4106 
4107   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4108     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4109     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4110     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4111     // node in order to try and match RVV vector/scalar instructions.
4112     if ((LoC >> 31) == HiC)
4113       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4114                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4115   }
4116 
4117   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4118   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4119       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4120       Hi.getConstantOperandVal(1) == 31)
4121     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4122                        DAG.getRegister(RISCV::X0, MVT::i32));
4123 
4124   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4125   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4126                      DAG.getUNDEF(VecVT), Lo, Hi,
4127                      DAG.getRegister(RISCV::X0, MVT::i32));
4128 }
4129 
4130 // Custom-lower extensions from mask vectors by using a vselect either with 1
4131 // for zero/any-extension or -1 for sign-extension:
4132 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4133 // Note that any-extension is lowered identically to zero-extension.
4134 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4135                                                 int64_t ExtTrueVal) const {
4136   SDLoc DL(Op);
4137   MVT VecVT = Op.getSimpleValueType();
4138   SDValue Src = Op.getOperand(0);
4139   // Only custom-lower extensions from mask types
4140   assert(Src.getValueType().isVector() &&
4141          Src.getValueType().getVectorElementType() == MVT::i1);
4142 
4143   if (VecVT.isScalableVector()) {
4144     SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
4145     SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
4146     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4147   }
4148 
4149   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4150   MVT I1ContainerVT =
4151       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4152 
4153   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4154 
4155   SDValue Mask, VL;
4156   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4157 
4158   MVT XLenVT = Subtarget.getXLenVT();
4159   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4160   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4161 
4162   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4163                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4164   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4165                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4166   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4167                                SplatTrueVal, SplatZero, VL);
4168 
4169   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4170 }
4171 
4172 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4173     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4174   MVT ExtVT = Op.getSimpleValueType();
4175   // Only custom-lower extensions from fixed-length vector types.
4176   if (!ExtVT.isFixedLengthVector())
4177     return Op;
4178   MVT VT = Op.getOperand(0).getSimpleValueType();
4179   // Grab the canonical container type for the extended type. Infer the smaller
4180   // type from that to ensure the same number of vector elements, as we know
4181   // the LMUL will be sufficient to hold the smaller type.
4182   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4183   // Get the extended container type manually to ensure the same number of
4184   // vector elements between source and dest.
4185   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4186                                      ContainerExtVT.getVectorElementCount());
4187 
4188   SDValue Op1 =
4189       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4190 
4191   SDLoc DL(Op);
4192   SDValue Mask, VL;
4193   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4194 
4195   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4196 
4197   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4198 }
4199 
4200 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4201 // setcc operation:
4202 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4203 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op,
4204                                                       SelectionDAG &DAG) const {
4205   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4206   SDLoc DL(Op);
4207   EVT MaskVT = Op.getValueType();
4208   // Only expect to custom-lower truncations to mask types
4209   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4210          "Unexpected type for vector mask lowering");
4211   SDValue Src = Op.getOperand(0);
4212   MVT VecVT = Src.getSimpleValueType();
4213   SDValue Mask, VL;
4214   if (IsVPTrunc) {
4215     Mask = Op.getOperand(1);
4216     VL = Op.getOperand(2);
4217   }
4218   // If this is a fixed vector, we need to convert it to a scalable vector.
4219   MVT ContainerVT = VecVT;
4220 
4221   if (VecVT.isFixedLengthVector()) {
4222     ContainerVT = getContainerForFixedLengthVector(VecVT);
4223     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4224     if (IsVPTrunc) {
4225       MVT MaskContainerVT =
4226           getContainerForFixedLengthVector(Mask.getSimpleValueType());
4227       Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget);
4228     }
4229   }
4230 
4231   if (!IsVPTrunc) {
4232     std::tie(Mask, VL) =
4233         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4234   }
4235 
4236   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4237   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4238 
4239   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4240                          DAG.getUNDEF(ContainerVT), SplatOne, VL);
4241   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4242                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4243 
4244   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4245   SDValue Trunc =
4246       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4247   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4248                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4249   if (MaskVT.isFixedLengthVector())
4250     Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4251   return Trunc;
4252 }
4253 
4254 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op,
4255                                                   SelectionDAG &DAG) const {
4256   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4257   SDLoc DL(Op);
4258 
4259   MVT VT = Op.getSimpleValueType();
4260   // Only custom-lower vector truncates
4261   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4262 
4263   // Truncates to mask types are handled differently
4264   if (VT.getVectorElementType() == MVT::i1)
4265     return lowerVectorMaskTruncLike(Op, DAG);
4266 
4267   // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
4268   // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
4269   // truncate by one power of two at a time.
4270   MVT DstEltVT = VT.getVectorElementType();
4271 
4272   SDValue Src = Op.getOperand(0);
4273   MVT SrcVT = Src.getSimpleValueType();
4274   MVT SrcEltVT = SrcVT.getVectorElementType();
4275 
4276   assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) &&
4277          isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
4278          "Unexpected vector truncate lowering");
4279 
4280   MVT ContainerVT = SrcVT;
4281   SDValue Mask, VL;
4282   if (IsVPTrunc) {
4283     Mask = Op.getOperand(1);
4284     VL = Op.getOperand(2);
4285   }
4286   if (SrcVT.isFixedLengthVector()) {
4287     ContainerVT = getContainerForFixedLengthVector(SrcVT);
4288     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4289     if (IsVPTrunc) {
4290       MVT MaskVT = getMaskTypeFor(ContainerVT);
4291       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4292     }
4293   }
4294 
4295   SDValue Result = Src;
4296   if (!IsVPTrunc) {
4297     std::tie(Mask, VL) =
4298         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4299   }
4300 
4301   LLVMContext &Context = *DAG.getContext();
4302   const ElementCount Count = ContainerVT.getVectorElementCount();
4303   do {
4304     SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
4305     EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
4306     Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
4307                          Mask, VL);
4308   } while (SrcEltVT != DstEltVT);
4309 
4310   if (SrcVT.isFixedLengthVector())
4311     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4312 
4313   return Result;
4314 }
4315 
4316 SDValue
4317 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op,
4318                                                     SelectionDAG &DAG) const {
4319   bool IsVP =
4320       Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND;
4321   bool IsExtend =
4322       Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND;
4323   // RVV can only do truncate fp to types half the size as the source. We
4324   // custom-lower f64->f16 rounds via RVV's round-to-odd float
4325   // conversion instruction.
4326   SDLoc DL(Op);
4327   MVT VT = Op.getSimpleValueType();
4328 
4329   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4330 
4331   SDValue Src = Op.getOperand(0);
4332   MVT SrcVT = Src.getSimpleValueType();
4333 
4334   bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 ||
4335                                      SrcVT.getVectorElementType() != MVT::f16);
4336   bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 ||
4337                                      SrcVT.getVectorElementType() != MVT::f64);
4338 
4339   bool IsDirectConv = IsDirectExtend || IsDirectTrunc;
4340 
4341   // Prepare any fixed-length vector operands.
4342   MVT ContainerVT = VT;
4343   SDValue Mask, VL;
4344   if (IsVP) {
4345     Mask = Op.getOperand(1);
4346     VL = Op.getOperand(2);
4347   }
4348   if (VT.isFixedLengthVector()) {
4349     MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
4350     ContainerVT =
4351         SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
4352     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
4353     if (IsVP) {
4354       MVT MaskVT = getMaskTypeFor(ContainerVT);
4355       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4356     }
4357   }
4358 
4359   if (!IsVP)
4360     std::tie(Mask, VL) =
4361         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4362 
4363   unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL;
4364 
4365   if (IsDirectConv) {
4366     Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL);
4367     if (VT.isFixedLengthVector())
4368       Src = convertFromScalableVector(VT, Src, DAG, Subtarget);
4369     return Src;
4370   }
4371 
4372   unsigned InterConvOpc =
4373       IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL;
4374 
4375   MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
4376   SDValue IntermediateConv =
4377       DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL);
4378   SDValue Result =
4379       DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL);
4380   if (VT.isFixedLengthVector())
4381     return convertFromScalableVector(VT, Result, DAG, Subtarget);
4382   return Result;
4383 }
4384 
4385 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4386 // first position of a vector, and that vector is slid up to the insert index.
4387 // By limiting the active vector length to index+1 and merging with the
4388 // original vector (with an undisturbed tail policy for elements >= VL), we
4389 // achieve the desired result of leaving all elements untouched except the one
4390 // at VL-1, which is replaced with the desired value.
4391 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4392                                                     SelectionDAG &DAG) const {
4393   SDLoc DL(Op);
4394   MVT VecVT = Op.getSimpleValueType();
4395   SDValue Vec = Op.getOperand(0);
4396   SDValue Val = Op.getOperand(1);
4397   SDValue Idx = Op.getOperand(2);
4398 
4399   if (VecVT.getVectorElementType() == MVT::i1) {
4400     // FIXME: For now we just promote to an i8 vector and insert into that,
4401     // but this is probably not optimal.
4402     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4403     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4404     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4405     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4406   }
4407 
4408   MVT ContainerVT = VecVT;
4409   // If the operand is a fixed-length vector, convert to a scalable one.
4410   if (VecVT.isFixedLengthVector()) {
4411     ContainerVT = getContainerForFixedLengthVector(VecVT);
4412     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4413   }
4414 
4415   MVT XLenVT = Subtarget.getXLenVT();
4416 
4417   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4418   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4419   // Even i64-element vectors on RV32 can be lowered without scalar
4420   // legalization if the most-significant 32 bits of the value are not affected
4421   // by the sign-extension of the lower 32 bits.
4422   // TODO: We could also catch sign extensions of a 32-bit value.
4423   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4424     const auto *CVal = cast<ConstantSDNode>(Val);
4425     if (isInt<32>(CVal->getSExtValue())) {
4426       IsLegalInsert = true;
4427       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4428     }
4429   }
4430 
4431   SDValue Mask, VL;
4432   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4433 
4434   SDValue ValInVec;
4435 
4436   if (IsLegalInsert) {
4437     unsigned Opc =
4438         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4439     if (isNullConstant(Idx)) {
4440       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4441       if (!VecVT.isFixedLengthVector())
4442         return Vec;
4443       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4444     }
4445     ValInVec =
4446         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4447   } else {
4448     // On RV32, i64-element vectors must be specially handled to place the
4449     // value at element 0, by using two vslide1up instructions in sequence on
4450     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4451     // this.
4452     SDValue One = DAG.getConstant(1, DL, XLenVT);
4453     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4454     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4455     MVT I32ContainerVT =
4456         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4457     SDValue I32Mask =
4458         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4459     // Limit the active VL to two.
4460     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4461     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4462     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4463     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4464                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4465     // First slide in the hi value, then the lo in underneath it.
4466     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4467                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4468                            I32Mask, InsertI64VL);
4469     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4470                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4471                            I32Mask, InsertI64VL);
4472     // Bitcast back to the right container type.
4473     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4474   }
4475 
4476   // Now that the value is in a vector, slide it into position.
4477   SDValue InsertVL =
4478       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4479   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4480                                 ValInVec, Idx, Mask, InsertVL);
4481   if (!VecVT.isFixedLengthVector())
4482     return Slideup;
4483   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4484 }
4485 
4486 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4487 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4488 // types this is done using VMV_X_S to allow us to glean information about the
4489 // sign bits of the result.
4490 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4491                                                      SelectionDAG &DAG) const {
4492   SDLoc DL(Op);
4493   SDValue Idx = Op.getOperand(1);
4494   SDValue Vec = Op.getOperand(0);
4495   EVT EltVT = Op.getValueType();
4496   MVT VecVT = Vec.getSimpleValueType();
4497   MVT XLenVT = Subtarget.getXLenVT();
4498 
4499   if (VecVT.getVectorElementType() == MVT::i1) {
4500     if (VecVT.isFixedLengthVector()) {
4501       unsigned NumElts = VecVT.getVectorNumElements();
4502       if (NumElts >= 8) {
4503         MVT WideEltVT;
4504         unsigned WidenVecLen;
4505         SDValue ExtractElementIdx;
4506         SDValue ExtractBitIdx;
4507         unsigned MaxEEW = Subtarget.getELEN();
4508         MVT LargestEltVT = MVT::getIntegerVT(
4509             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4510         if (NumElts <= LargestEltVT.getSizeInBits()) {
4511           assert(isPowerOf2_32(NumElts) &&
4512                  "the number of elements should be power of 2");
4513           WideEltVT = MVT::getIntegerVT(NumElts);
4514           WidenVecLen = 1;
4515           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4516           ExtractBitIdx = Idx;
4517         } else {
4518           WideEltVT = LargestEltVT;
4519           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4520           // extract element index = index / element width
4521           ExtractElementIdx = DAG.getNode(
4522               ISD::SRL, DL, XLenVT, Idx,
4523               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4524           // mask bit index = index % element width
4525           ExtractBitIdx = DAG.getNode(
4526               ISD::AND, DL, XLenVT, Idx,
4527               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4528         }
4529         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4530         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4531         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4532                                          Vec, ExtractElementIdx);
4533         // Extract the bit from GPR.
4534         SDValue ShiftRight =
4535             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4536         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4537                            DAG.getConstant(1, DL, XLenVT));
4538       }
4539     }
4540     // Otherwise, promote to an i8 vector and extract from that.
4541     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4542     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4543     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4544   }
4545 
4546   // If this is a fixed vector, we need to convert it to a scalable vector.
4547   MVT ContainerVT = VecVT;
4548   if (VecVT.isFixedLengthVector()) {
4549     ContainerVT = getContainerForFixedLengthVector(VecVT);
4550     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4551   }
4552 
4553   // If the index is 0, the vector is already in the right position.
4554   if (!isNullConstant(Idx)) {
4555     // Use a VL of 1 to avoid processing more elements than we need.
4556     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4557     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
4558     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4559                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4560   }
4561 
4562   if (!EltVT.isInteger()) {
4563     // Floating-point extracts are handled in TableGen.
4564     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4565                        DAG.getConstant(0, DL, XLenVT));
4566   }
4567 
4568   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4569   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4570 }
4571 
4572 // Some RVV intrinsics may claim that they want an integer operand to be
4573 // promoted or expanded.
4574 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4575                                            const RISCVSubtarget &Subtarget) {
4576   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4577           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4578          "Unexpected opcode");
4579 
4580   if (!Subtarget.hasVInstructions())
4581     return SDValue();
4582 
4583   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4584   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4585   SDLoc DL(Op);
4586 
4587   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4588       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4589   if (!II || !II->hasScalarOperand())
4590     return SDValue();
4591 
4592   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4593   assert(SplatOp < Op.getNumOperands());
4594 
4595   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4596   SDValue &ScalarOp = Operands[SplatOp];
4597   MVT OpVT = ScalarOp.getSimpleValueType();
4598   MVT XLenVT = Subtarget.getXLenVT();
4599 
4600   // If this isn't a scalar, or its type is XLenVT we're done.
4601   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4602     return SDValue();
4603 
4604   // Simplest case is that the operand needs to be promoted to XLenVT.
4605   if (OpVT.bitsLT(XLenVT)) {
4606     // If the operand is a constant, sign extend to increase our chances
4607     // of being able to use a .vi instruction. ANY_EXTEND would become a
4608     // a zero extend and the simm5 check in isel would fail.
4609     // FIXME: Should we ignore the upper bits in isel instead?
4610     unsigned ExtOpc =
4611         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4612     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4613     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4614   }
4615 
4616   // Use the previous operand to get the vXi64 VT. The result might be a mask
4617   // VT for compares. Using the previous operand assumes that the previous
4618   // operand will never have a smaller element size than a scalar operand and
4619   // that a widening operation never uses SEW=64.
4620   // NOTE: If this fails the below assert, we can probably just find the
4621   // element count from any operand or result and use it to construct the VT.
4622   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4623   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4624 
4625   // The more complex case is when the scalar is larger than XLenVT.
4626   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4627          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4628 
4629   // If this is a sign-extended 32-bit value, we can truncate it and rely on the
4630   // instruction to sign-extend since SEW>XLEN.
4631   if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
4632     ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
4633     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4634   }
4635 
4636   switch (IntNo) {
4637   case Intrinsic::riscv_vslide1up:
4638   case Intrinsic::riscv_vslide1down:
4639   case Intrinsic::riscv_vslide1up_mask:
4640   case Intrinsic::riscv_vslide1down_mask: {
4641     // We need to special case these when the scalar is larger than XLen.
4642     unsigned NumOps = Op.getNumOperands();
4643     bool IsMasked = NumOps == 7;
4644 
4645     // Convert the vector source to the equivalent nxvXi32 vector.
4646     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4647     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4648 
4649     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4650                                    DAG.getConstant(0, DL, XLenVT));
4651     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4652                                    DAG.getConstant(1, DL, XLenVT));
4653 
4654     // Double the VL since we halved SEW.
4655     SDValue AVL = getVLOperand(Op);
4656     SDValue I32VL;
4657 
4658     // Optimize for constant AVL
4659     if (isa<ConstantSDNode>(AVL)) {
4660       unsigned EltSize = VT.getScalarSizeInBits();
4661       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4662 
4663       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4664       unsigned MaxVLMAX =
4665           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4666 
4667       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4668       unsigned MinVLMAX =
4669           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4670 
4671       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4672       if (AVLInt <= MinVLMAX) {
4673         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4674       } else if (AVLInt >= 2 * MaxVLMAX) {
4675         // Just set vl to VLMAX in this situation
4676         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4677         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4678         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4679         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4680         SDValue SETVLMAX = DAG.getTargetConstant(
4681             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4682         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4683                             LMUL);
4684       } else {
4685         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4686         // is related to the hardware implementation.
4687         // So let the following code handle
4688       }
4689     }
4690     if (!I32VL) {
4691       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4692       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4693       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4694       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4695       SDValue SETVL =
4696           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4697       // Using vsetvli instruction to get actually used length which related to
4698       // the hardware implementation
4699       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4700                                SEW, LMUL);
4701       I32VL =
4702           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4703     }
4704 
4705     SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG);
4706 
4707     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4708     // instructions.
4709     SDValue Passthru;
4710     if (IsMasked)
4711       Passthru = DAG.getUNDEF(I32VT);
4712     else
4713       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4714 
4715     if (IntNo == Intrinsic::riscv_vslide1up ||
4716         IntNo == Intrinsic::riscv_vslide1up_mask) {
4717       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4718                         ScalarHi, I32Mask, I32VL);
4719       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4720                         ScalarLo, I32Mask, I32VL);
4721     } else {
4722       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4723                         ScalarLo, I32Mask, I32VL);
4724       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4725                         ScalarHi, I32Mask, I32VL);
4726     }
4727 
4728     // Convert back to nxvXi64.
4729     Vec = DAG.getBitcast(VT, Vec);
4730 
4731     if (!IsMasked)
4732       return Vec;
4733     // Apply mask after the operation.
4734     SDValue Mask = Operands[NumOps - 3];
4735     SDValue MaskedOff = Operands[1];
4736     // Assume Policy operand is the last operand.
4737     uint64_t Policy =
4738         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4739     // We don't need to select maskedoff if it's undef.
4740     if (MaskedOff.isUndef())
4741       return Vec;
4742     // TAMU
4743     if (Policy == RISCVII::TAIL_AGNOSTIC)
4744       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4745                          AVL);
4746     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4747     // It's fine because vmerge does not care mask policy.
4748     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4749                        AVL);
4750   }
4751   }
4752 
4753   // We need to convert the scalar to a splat vector.
4754   SDValue VL = getVLOperand(Op);
4755   assert(VL.getValueType() == XLenVT);
4756   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4757   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4758 }
4759 
4760 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4761                                                      SelectionDAG &DAG) const {
4762   unsigned IntNo = Op.getConstantOperandVal(0);
4763   SDLoc DL(Op);
4764   MVT XLenVT = Subtarget.getXLenVT();
4765 
4766   switch (IntNo) {
4767   default:
4768     break; // Don't custom lower most intrinsics.
4769   case Intrinsic::thread_pointer: {
4770     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4771     return DAG.getRegister(RISCV::X4, PtrVT);
4772   }
4773   case Intrinsic::riscv_orc_b:
4774   case Intrinsic::riscv_brev8: {
4775     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4776     unsigned Opc =
4777         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4778     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4779                        DAG.getConstant(7, DL, XLenVT));
4780   }
4781   case Intrinsic::riscv_grev:
4782   case Intrinsic::riscv_gorc: {
4783     unsigned Opc =
4784         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4785     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4786   }
4787   case Intrinsic::riscv_zip:
4788   case Intrinsic::riscv_unzip: {
4789     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4790     // For i32 the immediate is 15. For i64 the immediate is 31.
4791     unsigned Opc =
4792         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4793     unsigned BitWidth = Op.getValueSizeInBits();
4794     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4795     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4796                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4797   }
4798   case Intrinsic::riscv_shfl:
4799   case Intrinsic::riscv_unshfl: {
4800     unsigned Opc =
4801         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4802     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4803   }
4804   case Intrinsic::riscv_bcompress:
4805   case Intrinsic::riscv_bdecompress: {
4806     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4807                                                        : RISCVISD::BDECOMPRESS;
4808     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4809   }
4810   case Intrinsic::riscv_bfp:
4811     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4812                        Op.getOperand(2));
4813   case Intrinsic::riscv_fsl:
4814     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4815                        Op.getOperand(2), Op.getOperand(3));
4816   case Intrinsic::riscv_fsr:
4817     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4818                        Op.getOperand(2), Op.getOperand(3));
4819   case Intrinsic::riscv_vmv_x_s:
4820     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4821     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4822                        Op.getOperand(1));
4823   case Intrinsic::riscv_vmv_v_x:
4824     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4825                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4826                             Subtarget);
4827   case Intrinsic::riscv_vfmv_v_f:
4828     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4829                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4830   case Intrinsic::riscv_vmv_s_x: {
4831     SDValue Scalar = Op.getOperand(2);
4832 
4833     if (Scalar.getValueType().bitsLE(XLenVT)) {
4834       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4835       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4836                          Op.getOperand(1), Scalar, Op.getOperand(3));
4837     }
4838 
4839     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4840 
4841     // This is an i64 value that lives in two scalar registers. We have to
4842     // insert this in a convoluted way. First we build vXi64 splat containing
4843     // the two values that we assemble using some bit math. Next we'll use
4844     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4845     // to merge element 0 from our splat into the source vector.
4846     // FIXME: This is probably not the best way to do this, but it is
4847     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4848     // point.
4849     //   sw lo, (a0)
4850     //   sw hi, 4(a0)
4851     //   vlse vX, (a0)
4852     //
4853     //   vid.v      vVid
4854     //   vmseq.vx   mMask, vVid, 0
4855     //   vmerge.vvm vDest, vSrc, vVal, mMask
4856     MVT VT = Op.getSimpleValueType();
4857     SDValue Vec = Op.getOperand(1);
4858     SDValue VL = getVLOperand(Op);
4859 
4860     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4861     if (Op.getOperand(1).isUndef())
4862       return SplattedVal;
4863     SDValue SplattedIdx =
4864         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4865                     DAG.getConstant(0, DL, MVT::i32), VL);
4866 
4867     MVT MaskVT = getMaskTypeFor(VT);
4868     SDValue Mask = getAllOnesMask(VT, VL, DL, DAG);
4869     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4870     SDValue SelectCond =
4871         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4872                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4873     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4874                        Vec, VL);
4875   }
4876   }
4877 
4878   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4879 }
4880 
4881 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4882                                                     SelectionDAG &DAG) const {
4883   unsigned IntNo = Op.getConstantOperandVal(1);
4884   switch (IntNo) {
4885   default:
4886     break;
4887   case Intrinsic::riscv_masked_strided_load: {
4888     SDLoc DL(Op);
4889     MVT XLenVT = Subtarget.getXLenVT();
4890 
4891     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4892     // the selection of the masked intrinsics doesn't do this for us.
4893     SDValue Mask = Op.getOperand(5);
4894     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4895 
4896     MVT VT = Op->getSimpleValueType(0);
4897     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4898 
4899     SDValue PassThru = Op.getOperand(2);
4900     if (!IsUnmasked) {
4901       MVT MaskVT = getMaskTypeFor(ContainerVT);
4902       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4903       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4904     }
4905 
4906     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4907 
4908     SDValue IntID = DAG.getTargetConstant(
4909         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4910         XLenVT);
4911 
4912     auto *Load = cast<MemIntrinsicSDNode>(Op);
4913     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4914     if (IsUnmasked)
4915       Ops.push_back(DAG.getUNDEF(ContainerVT));
4916     else
4917       Ops.push_back(PassThru);
4918     Ops.push_back(Op.getOperand(3)); // Ptr
4919     Ops.push_back(Op.getOperand(4)); // Stride
4920     if (!IsUnmasked)
4921       Ops.push_back(Mask);
4922     Ops.push_back(VL);
4923     if (!IsUnmasked) {
4924       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4925       Ops.push_back(Policy);
4926     }
4927 
4928     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4929     SDValue Result =
4930         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4931                                 Load->getMemoryVT(), Load->getMemOperand());
4932     SDValue Chain = Result.getValue(1);
4933     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4934     return DAG.getMergeValues({Result, Chain}, DL);
4935   }
4936   case Intrinsic::riscv_seg2_load:
4937   case Intrinsic::riscv_seg3_load:
4938   case Intrinsic::riscv_seg4_load:
4939   case Intrinsic::riscv_seg5_load:
4940   case Intrinsic::riscv_seg6_load:
4941   case Intrinsic::riscv_seg7_load:
4942   case Intrinsic::riscv_seg8_load: {
4943     SDLoc DL(Op);
4944     static const Intrinsic::ID VlsegInts[7] = {
4945         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
4946         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
4947         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
4948         Intrinsic::riscv_vlseg8};
4949     unsigned NF = Op->getNumValues() - 1;
4950     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
4951     MVT XLenVT = Subtarget.getXLenVT();
4952     MVT VT = Op->getSimpleValueType(0);
4953     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4954 
4955     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4956     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
4957     auto *Load = cast<MemIntrinsicSDNode>(Op);
4958     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
4959     ContainerVTs.push_back(MVT::Other);
4960     SDVTList VTs = DAG.getVTList(ContainerVTs);
4961     SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID};
4962     Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT));
4963     Ops.push_back(Op.getOperand(2));
4964     Ops.push_back(VL);
4965     SDValue Result =
4966         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4967                                 Load->getMemoryVT(), Load->getMemOperand());
4968     SmallVector<SDValue, 9> Results;
4969     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
4970       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
4971                                                   DAG, Subtarget));
4972     Results.push_back(Result.getValue(NF));
4973     return DAG.getMergeValues(Results, DL);
4974   }
4975   }
4976 
4977   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4978 }
4979 
4980 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4981                                                  SelectionDAG &DAG) const {
4982   unsigned IntNo = Op.getConstantOperandVal(1);
4983   switch (IntNo) {
4984   default:
4985     break;
4986   case Intrinsic::riscv_masked_strided_store: {
4987     SDLoc DL(Op);
4988     MVT XLenVT = Subtarget.getXLenVT();
4989 
4990     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4991     // the selection of the masked intrinsics doesn't do this for us.
4992     SDValue Mask = Op.getOperand(5);
4993     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4994 
4995     SDValue Val = Op.getOperand(2);
4996     MVT VT = Val.getSimpleValueType();
4997     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4998 
4999     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5000     if (!IsUnmasked) {
5001       MVT MaskVT = getMaskTypeFor(ContainerVT);
5002       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5003     }
5004 
5005     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5006 
5007     SDValue IntID = DAG.getTargetConstant(
5008         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
5009         XLenVT);
5010 
5011     auto *Store = cast<MemIntrinsicSDNode>(Op);
5012     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
5013     Ops.push_back(Val);
5014     Ops.push_back(Op.getOperand(3)); // Ptr
5015     Ops.push_back(Op.getOperand(4)); // Stride
5016     if (!IsUnmasked)
5017       Ops.push_back(Mask);
5018     Ops.push_back(VL);
5019 
5020     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
5021                                    Ops, Store->getMemoryVT(),
5022                                    Store->getMemOperand());
5023   }
5024   }
5025 
5026   return SDValue();
5027 }
5028 
5029 static MVT getLMUL1VT(MVT VT) {
5030   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
5031          "Unexpected vector MVT");
5032   return MVT::getScalableVectorVT(
5033       VT.getVectorElementType(),
5034       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
5035 }
5036 
5037 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
5038   switch (ISDOpcode) {
5039   default:
5040     llvm_unreachable("Unhandled reduction");
5041   case ISD::VECREDUCE_ADD:
5042     return RISCVISD::VECREDUCE_ADD_VL;
5043   case ISD::VECREDUCE_UMAX:
5044     return RISCVISD::VECREDUCE_UMAX_VL;
5045   case ISD::VECREDUCE_SMAX:
5046     return RISCVISD::VECREDUCE_SMAX_VL;
5047   case ISD::VECREDUCE_UMIN:
5048     return RISCVISD::VECREDUCE_UMIN_VL;
5049   case ISD::VECREDUCE_SMIN:
5050     return RISCVISD::VECREDUCE_SMIN_VL;
5051   case ISD::VECREDUCE_AND:
5052     return RISCVISD::VECREDUCE_AND_VL;
5053   case ISD::VECREDUCE_OR:
5054     return RISCVISD::VECREDUCE_OR_VL;
5055   case ISD::VECREDUCE_XOR:
5056     return RISCVISD::VECREDUCE_XOR_VL;
5057   }
5058 }
5059 
5060 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
5061                                                          SelectionDAG &DAG,
5062                                                          bool IsVP) const {
5063   SDLoc DL(Op);
5064   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5065   MVT VecVT = Vec.getSimpleValueType();
5066   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5067           Op.getOpcode() == ISD::VECREDUCE_OR ||
5068           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5069           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5070           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5071           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5072          "Unexpected reduction lowering");
5073 
5074   MVT XLenVT = Subtarget.getXLenVT();
5075   assert(Op.getValueType() == XLenVT &&
5076          "Expected reduction output to be legalized to XLenVT");
5077 
5078   MVT ContainerVT = VecVT;
5079   if (VecVT.isFixedLengthVector()) {
5080     ContainerVT = getContainerForFixedLengthVector(VecVT);
5081     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5082   }
5083 
5084   SDValue Mask, VL;
5085   if (IsVP) {
5086     Mask = Op.getOperand(2);
5087     VL = Op.getOperand(3);
5088   } else {
5089     std::tie(Mask, VL) =
5090         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5091   }
5092 
5093   unsigned BaseOpc;
5094   ISD::CondCode CC;
5095   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5096 
5097   switch (Op.getOpcode()) {
5098   default:
5099     llvm_unreachable("Unhandled reduction");
5100   case ISD::VECREDUCE_AND:
5101   case ISD::VP_REDUCE_AND: {
5102     // vcpop ~x == 0
5103     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5104     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5105     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5106     CC = ISD::SETEQ;
5107     BaseOpc = ISD::AND;
5108     break;
5109   }
5110   case ISD::VECREDUCE_OR:
5111   case ISD::VP_REDUCE_OR:
5112     // vcpop x != 0
5113     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5114     CC = ISD::SETNE;
5115     BaseOpc = ISD::OR;
5116     break;
5117   case ISD::VECREDUCE_XOR:
5118   case ISD::VP_REDUCE_XOR: {
5119     // ((vcpop x) & 1) != 0
5120     SDValue One = DAG.getConstant(1, DL, XLenVT);
5121     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5122     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5123     CC = ISD::SETNE;
5124     BaseOpc = ISD::XOR;
5125     break;
5126   }
5127   }
5128 
5129   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5130 
5131   if (!IsVP)
5132     return SetCC;
5133 
5134   // Now include the start value in the operation.
5135   // Note that we must return the start value when no elements are operated
5136   // upon. The vcpop instructions we've emitted in each case above will return
5137   // 0 for an inactive vector, and so we've already received the neutral value:
5138   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5139   // can simply include the start value.
5140   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5141 }
5142 
5143 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5144                                             SelectionDAG &DAG) const {
5145   SDLoc DL(Op);
5146   SDValue Vec = Op.getOperand(0);
5147   EVT VecEVT = Vec.getValueType();
5148 
5149   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5150 
5151   // Due to ordering in legalize types we may have a vector type that needs to
5152   // be split. Do that manually so we can get down to a legal type.
5153   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5154          TargetLowering::TypeSplitVector) {
5155     SDValue Lo, Hi;
5156     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5157     VecEVT = Lo.getValueType();
5158     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5159   }
5160 
5161   // TODO: The type may need to be widened rather than split. Or widened before
5162   // it can be split.
5163   if (!isTypeLegal(VecEVT))
5164     return SDValue();
5165 
5166   MVT VecVT = VecEVT.getSimpleVT();
5167   MVT VecEltVT = VecVT.getVectorElementType();
5168   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5169 
5170   MVT ContainerVT = VecVT;
5171   if (VecVT.isFixedLengthVector()) {
5172     ContainerVT = getContainerForFixedLengthVector(VecVT);
5173     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5174   }
5175 
5176   MVT M1VT = getLMUL1VT(ContainerVT);
5177   MVT XLenVT = Subtarget.getXLenVT();
5178 
5179   SDValue Mask, VL;
5180   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5181 
5182   SDValue NeutralElem =
5183       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5184   SDValue IdentitySplat =
5185       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5186                        M1VT, DL, DAG, Subtarget);
5187   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5188                                   IdentitySplat, Mask, VL);
5189   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5190                              DAG.getConstant(0, DL, XLenVT));
5191   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5192 }
5193 
5194 // Given a reduction op, this function returns the matching reduction opcode,
5195 // the vector SDValue and the scalar SDValue required to lower this to a
5196 // RISCVISD node.
5197 static std::tuple<unsigned, SDValue, SDValue>
5198 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5199   SDLoc DL(Op);
5200   auto Flags = Op->getFlags();
5201   unsigned Opcode = Op.getOpcode();
5202   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5203   switch (Opcode) {
5204   default:
5205     llvm_unreachable("Unhandled reduction");
5206   case ISD::VECREDUCE_FADD: {
5207     // Use positive zero if we can. It is cheaper to materialize.
5208     SDValue Zero =
5209         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5210     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5211   }
5212   case ISD::VECREDUCE_SEQ_FADD:
5213     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5214                            Op.getOperand(0));
5215   case ISD::VECREDUCE_FMIN:
5216     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5217                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5218   case ISD::VECREDUCE_FMAX:
5219     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5220                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5221   }
5222 }
5223 
5224 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5225                                               SelectionDAG &DAG) const {
5226   SDLoc DL(Op);
5227   MVT VecEltVT = Op.getSimpleValueType();
5228 
5229   unsigned RVVOpcode;
5230   SDValue VectorVal, ScalarVal;
5231   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5232       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5233   MVT VecVT = VectorVal.getSimpleValueType();
5234 
5235   MVT ContainerVT = VecVT;
5236   if (VecVT.isFixedLengthVector()) {
5237     ContainerVT = getContainerForFixedLengthVector(VecVT);
5238     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5239   }
5240 
5241   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5242   MVT XLenVT = Subtarget.getXLenVT();
5243 
5244   SDValue Mask, VL;
5245   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5246 
5247   SDValue ScalarSplat =
5248       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5249                        M1VT, DL, DAG, Subtarget);
5250   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5251                                   VectorVal, ScalarSplat, Mask, VL);
5252   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5253                      DAG.getConstant(0, DL, XLenVT));
5254 }
5255 
5256 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5257   switch (ISDOpcode) {
5258   default:
5259     llvm_unreachable("Unhandled reduction");
5260   case ISD::VP_REDUCE_ADD:
5261     return RISCVISD::VECREDUCE_ADD_VL;
5262   case ISD::VP_REDUCE_UMAX:
5263     return RISCVISD::VECREDUCE_UMAX_VL;
5264   case ISD::VP_REDUCE_SMAX:
5265     return RISCVISD::VECREDUCE_SMAX_VL;
5266   case ISD::VP_REDUCE_UMIN:
5267     return RISCVISD::VECREDUCE_UMIN_VL;
5268   case ISD::VP_REDUCE_SMIN:
5269     return RISCVISD::VECREDUCE_SMIN_VL;
5270   case ISD::VP_REDUCE_AND:
5271     return RISCVISD::VECREDUCE_AND_VL;
5272   case ISD::VP_REDUCE_OR:
5273     return RISCVISD::VECREDUCE_OR_VL;
5274   case ISD::VP_REDUCE_XOR:
5275     return RISCVISD::VECREDUCE_XOR_VL;
5276   case ISD::VP_REDUCE_FADD:
5277     return RISCVISD::VECREDUCE_FADD_VL;
5278   case ISD::VP_REDUCE_SEQ_FADD:
5279     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5280   case ISD::VP_REDUCE_FMAX:
5281     return RISCVISD::VECREDUCE_FMAX_VL;
5282   case ISD::VP_REDUCE_FMIN:
5283     return RISCVISD::VECREDUCE_FMIN_VL;
5284   }
5285 }
5286 
5287 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5288                                            SelectionDAG &DAG) const {
5289   SDLoc DL(Op);
5290   SDValue Vec = Op.getOperand(1);
5291   EVT VecEVT = Vec.getValueType();
5292 
5293   // TODO: The type may need to be widened rather than split. Or widened before
5294   // it can be split.
5295   if (!isTypeLegal(VecEVT))
5296     return SDValue();
5297 
5298   MVT VecVT = VecEVT.getSimpleVT();
5299   MVT VecEltVT = VecVT.getVectorElementType();
5300   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5301 
5302   MVT ContainerVT = VecVT;
5303   if (VecVT.isFixedLengthVector()) {
5304     ContainerVT = getContainerForFixedLengthVector(VecVT);
5305     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5306   }
5307 
5308   SDValue VL = Op.getOperand(3);
5309   SDValue Mask = Op.getOperand(2);
5310 
5311   MVT M1VT = getLMUL1VT(ContainerVT);
5312   MVT XLenVT = Subtarget.getXLenVT();
5313   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5314 
5315   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5316                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5317                                         DL, DAG, Subtarget);
5318   SDValue Reduction =
5319       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5320   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5321                              DAG.getConstant(0, DL, XLenVT));
5322   if (!VecVT.isInteger())
5323     return Elt0;
5324   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5325 }
5326 
5327 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5328                                                    SelectionDAG &DAG) const {
5329   SDValue Vec = Op.getOperand(0);
5330   SDValue SubVec = Op.getOperand(1);
5331   MVT VecVT = Vec.getSimpleValueType();
5332   MVT SubVecVT = SubVec.getSimpleValueType();
5333 
5334   SDLoc DL(Op);
5335   MVT XLenVT = Subtarget.getXLenVT();
5336   unsigned OrigIdx = Op.getConstantOperandVal(2);
5337   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5338 
5339   // We don't have the ability to slide mask vectors up indexed by their i1
5340   // elements; the smallest we can do is i8. Often we are able to bitcast to
5341   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5342   // into a scalable one, we might not necessarily have enough scalable
5343   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5344   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5345       (OrigIdx != 0 || !Vec.isUndef())) {
5346     if (VecVT.getVectorMinNumElements() >= 8 &&
5347         SubVecVT.getVectorMinNumElements() >= 8) {
5348       assert(OrigIdx % 8 == 0 && "Invalid index");
5349       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5350              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5351              "Unexpected mask vector lowering");
5352       OrigIdx /= 8;
5353       SubVecVT =
5354           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5355                            SubVecVT.isScalableVector());
5356       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5357                                VecVT.isScalableVector());
5358       Vec = DAG.getBitcast(VecVT, Vec);
5359       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5360     } else {
5361       // We can't slide this mask vector up indexed by its i1 elements.
5362       // This poses a problem when we wish to insert a scalable vector which
5363       // can't be re-expressed as a larger type. Just choose the slow path and
5364       // extend to a larger type, then truncate back down.
5365       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5366       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5367       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5368       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5369       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5370                         Op.getOperand(2));
5371       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5372       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5373     }
5374   }
5375 
5376   // If the subvector vector is a fixed-length type, we cannot use subregister
5377   // manipulation to simplify the codegen; we don't know which register of a
5378   // LMUL group contains the specific subvector as we only know the minimum
5379   // register size. Therefore we must slide the vector group up the full
5380   // amount.
5381   if (SubVecVT.isFixedLengthVector()) {
5382     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5383       return Op;
5384     MVT ContainerVT = VecVT;
5385     if (VecVT.isFixedLengthVector()) {
5386       ContainerVT = getContainerForFixedLengthVector(VecVT);
5387       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5388     }
5389     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5390                          DAG.getUNDEF(ContainerVT), SubVec,
5391                          DAG.getConstant(0, DL, XLenVT));
5392     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5393       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5394       return DAG.getBitcast(Op.getValueType(), SubVec);
5395     }
5396     SDValue Mask =
5397         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5398     // Set the vector length to only the number of elements we care about. Note
5399     // that for slideup this includes the offset.
5400     SDValue VL =
5401         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5402     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5403     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5404                                   SubVec, SlideupAmt, Mask, VL);
5405     if (VecVT.isFixedLengthVector())
5406       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5407     return DAG.getBitcast(Op.getValueType(), Slideup);
5408   }
5409 
5410   unsigned SubRegIdx, RemIdx;
5411   std::tie(SubRegIdx, RemIdx) =
5412       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5413           VecVT, SubVecVT, OrigIdx, TRI);
5414 
5415   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5416   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5417                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5418                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5419 
5420   // 1. If the Idx has been completely eliminated and this subvector's size is
5421   // a vector register or a multiple thereof, or the surrounding elements are
5422   // undef, then this is a subvector insert which naturally aligns to a vector
5423   // register. These can easily be handled using subregister manipulation.
5424   // 2. If the subvector is smaller than a vector register, then the insertion
5425   // must preserve the undisturbed elements of the register. We do this by
5426   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5427   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5428   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5429   // LMUL=1 type back into the larger vector (resolving to another subregister
5430   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5431   // to avoid allocating a large register group to hold our subvector.
5432   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5433     return Op;
5434 
5435   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5436   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5437   // (in our case undisturbed). This means we can set up a subvector insertion
5438   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5439   // size of the subvector.
5440   MVT InterSubVT = VecVT;
5441   SDValue AlignedExtract = Vec;
5442   unsigned AlignedIdx = OrigIdx - RemIdx;
5443   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5444     InterSubVT = getLMUL1VT(VecVT);
5445     // Extract a subvector equal to the nearest full vector register type. This
5446     // should resolve to a EXTRACT_SUBREG instruction.
5447     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5448                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5449   }
5450 
5451   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5452   // For scalable vectors this must be further multiplied by vscale.
5453   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5454 
5455   SDValue Mask, VL;
5456   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5457 
5458   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5459   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5460   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5461   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5462 
5463   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5464                        DAG.getUNDEF(InterSubVT), SubVec,
5465                        DAG.getConstant(0, DL, XLenVT));
5466 
5467   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5468                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5469 
5470   // If required, insert this subvector back into the correct vector register.
5471   // This should resolve to an INSERT_SUBREG instruction.
5472   if (VecVT.bitsGT(InterSubVT))
5473     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5474                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5475 
5476   // We might have bitcast from a mask type: cast back to the original type if
5477   // required.
5478   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5479 }
5480 
5481 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5482                                                     SelectionDAG &DAG) const {
5483   SDValue Vec = Op.getOperand(0);
5484   MVT SubVecVT = Op.getSimpleValueType();
5485   MVT VecVT = Vec.getSimpleValueType();
5486 
5487   SDLoc DL(Op);
5488   MVT XLenVT = Subtarget.getXLenVT();
5489   unsigned OrigIdx = Op.getConstantOperandVal(1);
5490   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5491 
5492   // We don't have the ability to slide mask vectors down indexed by their i1
5493   // elements; the smallest we can do is i8. Often we are able to bitcast to
5494   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5495   // from a scalable one, we might not necessarily have enough scalable
5496   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5497   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5498     if (VecVT.getVectorMinNumElements() >= 8 &&
5499         SubVecVT.getVectorMinNumElements() >= 8) {
5500       assert(OrigIdx % 8 == 0 && "Invalid index");
5501       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5502              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5503              "Unexpected mask vector lowering");
5504       OrigIdx /= 8;
5505       SubVecVT =
5506           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5507                            SubVecVT.isScalableVector());
5508       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5509                                VecVT.isScalableVector());
5510       Vec = DAG.getBitcast(VecVT, Vec);
5511     } else {
5512       // We can't slide this mask vector down, indexed by its i1 elements.
5513       // This poses a problem when we wish to extract a scalable vector which
5514       // can't be re-expressed as a larger type. Just choose the slow path and
5515       // extend to a larger type, then truncate back down.
5516       // TODO: We could probably improve this when extracting certain fixed
5517       // from fixed, where we can extract as i8 and shift the correct element
5518       // right to reach the desired subvector?
5519       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5520       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5521       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5522       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5523                         Op.getOperand(1));
5524       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5525       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5526     }
5527   }
5528 
5529   // If the subvector vector is a fixed-length type, we cannot use subregister
5530   // manipulation to simplify the codegen; we don't know which register of a
5531   // LMUL group contains the specific subvector as we only know the minimum
5532   // register size. Therefore we must slide the vector group down the full
5533   // amount.
5534   if (SubVecVT.isFixedLengthVector()) {
5535     // With an index of 0 this is a cast-like subvector, which can be performed
5536     // with subregister operations.
5537     if (OrigIdx == 0)
5538       return Op;
5539     MVT ContainerVT = VecVT;
5540     if (VecVT.isFixedLengthVector()) {
5541       ContainerVT = getContainerForFixedLengthVector(VecVT);
5542       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5543     }
5544     SDValue Mask =
5545         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5546     // Set the vector length to only the number of elements we care about. This
5547     // avoids sliding down elements we're going to discard straight away.
5548     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5549     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5550     SDValue Slidedown =
5551         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5552                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5553     // Now we can use a cast-like subvector extract to get the result.
5554     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5555                             DAG.getConstant(0, DL, XLenVT));
5556     return DAG.getBitcast(Op.getValueType(), Slidedown);
5557   }
5558 
5559   unsigned SubRegIdx, RemIdx;
5560   std::tie(SubRegIdx, RemIdx) =
5561       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5562           VecVT, SubVecVT, OrigIdx, TRI);
5563 
5564   // If the Idx has been completely eliminated then this is a subvector extract
5565   // which naturally aligns to a vector register. These can easily be handled
5566   // using subregister manipulation.
5567   if (RemIdx == 0)
5568     return Op;
5569 
5570   // Else we must shift our vector register directly to extract the subvector.
5571   // Do this using VSLIDEDOWN.
5572 
5573   // If the vector type is an LMUL-group type, extract a subvector equal to the
5574   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5575   // instruction.
5576   MVT InterSubVT = VecVT;
5577   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5578     InterSubVT = getLMUL1VT(VecVT);
5579     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5580                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5581   }
5582 
5583   // Slide this vector register down by the desired number of elements in order
5584   // to place the desired subvector starting at element 0.
5585   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5586   // For scalable vectors this must be further multiplied by vscale.
5587   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5588 
5589   SDValue Mask, VL;
5590   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5591   SDValue Slidedown =
5592       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5593                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5594 
5595   // Now the vector is in the right position, extract our final subvector. This
5596   // should resolve to a COPY.
5597   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5598                           DAG.getConstant(0, DL, XLenVT));
5599 
5600   // We might have bitcast from a mask type: cast back to the original type if
5601   // required.
5602   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5603 }
5604 
5605 // Lower step_vector to the vid instruction. Any non-identity step value must
5606 // be accounted for my manual expansion.
5607 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5608                                               SelectionDAG &DAG) const {
5609   SDLoc DL(Op);
5610   MVT VT = Op.getSimpleValueType();
5611   MVT XLenVT = Subtarget.getXLenVT();
5612   SDValue Mask, VL;
5613   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5614   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5615   uint64_t StepValImm = Op.getConstantOperandVal(0);
5616   if (StepValImm != 1) {
5617     if (isPowerOf2_64(StepValImm)) {
5618       SDValue StepVal =
5619           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5620                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5621       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5622     } else {
5623       SDValue StepVal = lowerScalarSplat(
5624           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5625           VL, VT, DL, DAG, Subtarget);
5626       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5627     }
5628   }
5629   return StepVec;
5630 }
5631 
5632 // Implement vector_reverse using vrgather.vv with indices determined by
5633 // subtracting the id of each element from (VLMAX-1). This will convert
5634 // the indices like so:
5635 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5636 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5637 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5638                                                  SelectionDAG &DAG) const {
5639   SDLoc DL(Op);
5640   MVT VecVT = Op.getSimpleValueType();
5641   unsigned EltSize = VecVT.getScalarSizeInBits();
5642   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5643   unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
5644   unsigned MaxVLMAX =
5645     RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5646 
5647   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5648   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5649 
5650   // If this is SEW=8 and VLMAX is potentially more than 256, we need
5651   // to use vrgatherei16.vv.
5652   // TODO: It's also possible to use vrgatherei16.vv for other types to
5653   // decrease register width for the index calculation.
5654   if (MaxVLMAX > 256 && EltSize == 8) {
5655     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5656     // Reverse each half, then reassemble them in reverse order.
5657     // NOTE: It's also possible that after splitting that VLMAX no longer
5658     // requires vrgatherei16.vv.
5659     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5660       SDValue Lo, Hi;
5661       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5662       EVT LoVT, HiVT;
5663       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5664       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5665       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5666       // Reassemble the low and high pieces reversed.
5667       // FIXME: This is a CONCAT_VECTORS.
5668       SDValue Res =
5669           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5670                       DAG.getIntPtrConstant(0, DL));
5671       return DAG.getNode(
5672           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5673           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5674     }
5675 
5676     // Just promote the int type to i16 which will double the LMUL.
5677     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5678     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5679   }
5680 
5681   MVT XLenVT = Subtarget.getXLenVT();
5682   SDValue Mask, VL;
5683   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5684 
5685   // Calculate VLMAX-1 for the desired SEW.
5686   unsigned MinElts = VecVT.getVectorMinNumElements();
5687   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5688                               DAG.getConstant(MinElts, DL, XLenVT));
5689   SDValue VLMinus1 =
5690       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5691 
5692   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5693   bool IsRV32E64 =
5694       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5695   SDValue SplatVL;
5696   if (!IsRV32E64)
5697     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5698   else
5699     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5700                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5701 
5702   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5703   SDValue Indices =
5704       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5705 
5706   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask,
5707                      DAG.getUNDEF(VecVT), VL);
5708 }
5709 
5710 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5711                                                 SelectionDAG &DAG) const {
5712   SDLoc DL(Op);
5713   SDValue V1 = Op.getOperand(0);
5714   SDValue V2 = Op.getOperand(1);
5715   MVT XLenVT = Subtarget.getXLenVT();
5716   MVT VecVT = Op.getSimpleValueType();
5717 
5718   unsigned MinElts = VecVT.getVectorMinNumElements();
5719   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5720                               DAG.getConstant(MinElts, DL, XLenVT));
5721 
5722   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5723   SDValue DownOffset, UpOffset;
5724   if (ImmValue >= 0) {
5725     // The operand is a TargetConstant, we need to rebuild it as a regular
5726     // constant.
5727     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5728     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5729   } else {
5730     // The operand is a TargetConstant, we need to rebuild it as a regular
5731     // constant rather than negating the original operand.
5732     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5733     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5734   }
5735 
5736   SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG);
5737 
5738   SDValue SlideDown =
5739       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5740                   DownOffset, TrueMask, UpOffset);
5741   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5742                      TrueMask,
5743                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5744 }
5745 
5746 SDValue
5747 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5748                                                      SelectionDAG &DAG) const {
5749   SDLoc DL(Op);
5750   auto *Load = cast<LoadSDNode>(Op);
5751 
5752   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5753                                         Load->getMemoryVT(),
5754                                         *Load->getMemOperand()) &&
5755          "Expecting a correctly-aligned load");
5756 
5757   MVT VT = Op.getSimpleValueType();
5758   MVT XLenVT = Subtarget.getXLenVT();
5759   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5760 
5761   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5762 
5763   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5764   SDValue IntID = DAG.getTargetConstant(
5765       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5766   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5767   if (!IsMaskOp)
5768     Ops.push_back(DAG.getUNDEF(ContainerVT));
5769   Ops.push_back(Load->getBasePtr());
5770   Ops.push_back(VL);
5771   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5772   SDValue NewLoad =
5773       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5774                               Load->getMemoryVT(), Load->getMemOperand());
5775 
5776   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5777   return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL);
5778 }
5779 
5780 SDValue
5781 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5782                                                       SelectionDAG &DAG) const {
5783   SDLoc DL(Op);
5784   auto *Store = cast<StoreSDNode>(Op);
5785 
5786   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5787                                         Store->getMemoryVT(),
5788                                         *Store->getMemOperand()) &&
5789          "Expecting a correctly-aligned store");
5790 
5791   SDValue StoreVal = Store->getValue();
5792   MVT VT = StoreVal.getSimpleValueType();
5793   MVT XLenVT = Subtarget.getXLenVT();
5794 
5795   // If the size less than a byte, we need to pad with zeros to make a byte.
5796   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5797     VT = MVT::v8i1;
5798     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5799                            DAG.getConstant(0, DL, VT), StoreVal,
5800                            DAG.getIntPtrConstant(0, DL));
5801   }
5802 
5803   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5804 
5805   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5806 
5807   SDValue NewValue =
5808       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5809 
5810   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5811   SDValue IntID = DAG.getTargetConstant(
5812       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5813   return DAG.getMemIntrinsicNode(
5814       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5815       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5816       Store->getMemoryVT(), Store->getMemOperand());
5817 }
5818 
5819 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5820                                              SelectionDAG &DAG) const {
5821   SDLoc DL(Op);
5822   MVT VT = Op.getSimpleValueType();
5823 
5824   const auto *MemSD = cast<MemSDNode>(Op);
5825   EVT MemVT = MemSD->getMemoryVT();
5826   MachineMemOperand *MMO = MemSD->getMemOperand();
5827   SDValue Chain = MemSD->getChain();
5828   SDValue BasePtr = MemSD->getBasePtr();
5829 
5830   SDValue Mask, PassThru, VL;
5831   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5832     Mask = VPLoad->getMask();
5833     PassThru = DAG.getUNDEF(VT);
5834     VL = VPLoad->getVectorLength();
5835   } else {
5836     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5837     Mask = MLoad->getMask();
5838     PassThru = MLoad->getPassThru();
5839   }
5840 
5841   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5842 
5843   MVT XLenVT = Subtarget.getXLenVT();
5844 
5845   MVT ContainerVT = VT;
5846   if (VT.isFixedLengthVector()) {
5847     ContainerVT = getContainerForFixedLengthVector(VT);
5848     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5849     if (!IsUnmasked) {
5850       MVT MaskVT = getMaskTypeFor(ContainerVT);
5851       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5852     }
5853   }
5854 
5855   if (!VL)
5856     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5857 
5858   unsigned IntID =
5859       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5860   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5861   if (IsUnmasked)
5862     Ops.push_back(DAG.getUNDEF(ContainerVT));
5863   else
5864     Ops.push_back(PassThru);
5865   Ops.push_back(BasePtr);
5866   if (!IsUnmasked)
5867     Ops.push_back(Mask);
5868   Ops.push_back(VL);
5869   if (!IsUnmasked)
5870     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5871 
5872   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5873 
5874   SDValue Result =
5875       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5876   Chain = Result.getValue(1);
5877 
5878   if (VT.isFixedLengthVector())
5879     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5880 
5881   return DAG.getMergeValues({Result, Chain}, DL);
5882 }
5883 
5884 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5885                                               SelectionDAG &DAG) const {
5886   SDLoc DL(Op);
5887 
5888   const auto *MemSD = cast<MemSDNode>(Op);
5889   EVT MemVT = MemSD->getMemoryVT();
5890   MachineMemOperand *MMO = MemSD->getMemOperand();
5891   SDValue Chain = MemSD->getChain();
5892   SDValue BasePtr = MemSD->getBasePtr();
5893   SDValue Val, Mask, VL;
5894 
5895   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5896     Val = VPStore->getValue();
5897     Mask = VPStore->getMask();
5898     VL = VPStore->getVectorLength();
5899   } else {
5900     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5901     Val = MStore->getValue();
5902     Mask = MStore->getMask();
5903   }
5904 
5905   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5906 
5907   MVT VT = Val.getSimpleValueType();
5908   MVT XLenVT = Subtarget.getXLenVT();
5909 
5910   MVT ContainerVT = VT;
5911   if (VT.isFixedLengthVector()) {
5912     ContainerVT = getContainerForFixedLengthVector(VT);
5913 
5914     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5915     if (!IsUnmasked) {
5916       MVT MaskVT = getMaskTypeFor(ContainerVT);
5917       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5918     }
5919   }
5920 
5921   if (!VL)
5922     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5923 
5924   unsigned IntID =
5925       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5926   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5927   Ops.push_back(Val);
5928   Ops.push_back(BasePtr);
5929   if (!IsUnmasked)
5930     Ops.push_back(Mask);
5931   Ops.push_back(VL);
5932 
5933   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5934                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5935 }
5936 
5937 SDValue
5938 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5939                                                       SelectionDAG &DAG) const {
5940   MVT InVT = Op.getOperand(0).getSimpleValueType();
5941   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5942 
5943   MVT VT = Op.getSimpleValueType();
5944 
5945   SDValue Op1 =
5946       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5947   SDValue Op2 =
5948       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5949 
5950   SDLoc DL(Op);
5951   SDValue VL =
5952       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5953 
5954   MVT MaskVT = getMaskTypeFor(ContainerVT);
5955   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
5956 
5957   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5958                             Op.getOperand(2), Mask, VL);
5959 
5960   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5961 }
5962 
5963 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5964     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5965   MVT VT = Op.getSimpleValueType();
5966 
5967   if (VT.getVectorElementType() == MVT::i1)
5968     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5969 
5970   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5971 }
5972 
5973 SDValue
5974 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5975                                                       SelectionDAG &DAG) const {
5976   unsigned Opc;
5977   switch (Op.getOpcode()) {
5978   default: llvm_unreachable("Unexpected opcode!");
5979   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5980   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5981   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5982   }
5983 
5984   return lowerToScalableOp(Op, DAG, Opc);
5985 }
5986 
5987 // Lower vector ABS to smax(X, sub(0, X)).
5988 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5989   SDLoc DL(Op);
5990   MVT VT = Op.getSimpleValueType();
5991   SDValue X = Op.getOperand(0);
5992 
5993   assert(VT.isFixedLengthVector() && "Unexpected type");
5994 
5995   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5996   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5997 
5998   SDValue Mask, VL;
5999   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6000 
6001   SDValue SplatZero = DAG.getNode(
6002       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
6003       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
6004   SDValue NegX =
6005       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
6006   SDValue Max =
6007       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
6008 
6009   return convertFromScalableVector(VT, Max, DAG, Subtarget);
6010 }
6011 
6012 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
6013     SDValue Op, SelectionDAG &DAG) const {
6014   SDLoc DL(Op);
6015   MVT VT = Op.getSimpleValueType();
6016   SDValue Mag = Op.getOperand(0);
6017   SDValue Sign = Op.getOperand(1);
6018   assert(Mag.getValueType() == Sign.getValueType() &&
6019          "Can only handle COPYSIGN with matching types.");
6020 
6021   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6022   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
6023   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
6024 
6025   SDValue Mask, VL;
6026   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6027 
6028   SDValue CopySign =
6029       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
6030 
6031   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
6032 }
6033 
6034 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
6035     SDValue Op, SelectionDAG &DAG) const {
6036   MVT VT = Op.getSimpleValueType();
6037   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6038 
6039   MVT I1ContainerVT =
6040       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6041 
6042   SDValue CC =
6043       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
6044   SDValue Op1 =
6045       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6046   SDValue Op2 =
6047       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
6048 
6049   SDLoc DL(Op);
6050   SDValue Mask, VL;
6051   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6052 
6053   SDValue Select =
6054       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
6055 
6056   return convertFromScalableVector(VT, Select, DAG, Subtarget);
6057 }
6058 
6059 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
6060                                                unsigned NewOpc,
6061                                                bool HasMask) const {
6062   MVT VT = Op.getSimpleValueType();
6063   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6064 
6065   // Create list of operands by converting existing ones to scalable types.
6066   SmallVector<SDValue, 6> Ops;
6067   for (const SDValue &V : Op->op_values()) {
6068     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6069 
6070     // Pass through non-vector operands.
6071     if (!V.getValueType().isVector()) {
6072       Ops.push_back(V);
6073       continue;
6074     }
6075 
6076     // "cast" fixed length vector to a scalable vector.
6077     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6078            "Only fixed length vectors are supported!");
6079     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6080   }
6081 
6082   SDLoc DL(Op);
6083   SDValue Mask, VL;
6084   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6085   if (HasMask)
6086     Ops.push_back(Mask);
6087   Ops.push_back(VL);
6088 
6089   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6090   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6091 }
6092 
6093 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6094 // * Operands of each node are assumed to be in the same order.
6095 // * The EVL operand is promoted from i32 to i64 on RV64.
6096 // * Fixed-length vectors are converted to their scalable-vector container
6097 //   types.
6098 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6099                                        unsigned RISCVISDOpc) const {
6100   SDLoc DL(Op);
6101   MVT VT = Op.getSimpleValueType();
6102   SmallVector<SDValue, 4> Ops;
6103 
6104   for (const auto &OpIdx : enumerate(Op->ops())) {
6105     SDValue V = OpIdx.value();
6106     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6107     // Pass through operands which aren't fixed-length vectors.
6108     if (!V.getValueType().isFixedLengthVector()) {
6109       Ops.push_back(V);
6110       continue;
6111     }
6112     // "cast" fixed length vector to a scalable vector.
6113     MVT OpVT = V.getSimpleValueType();
6114     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6115     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6116            "Only fixed length vectors are supported!");
6117     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6118   }
6119 
6120   if (!VT.isFixedLengthVector())
6121     return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags());
6122 
6123   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6124 
6125   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags());
6126 
6127   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6128 }
6129 
6130 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op,
6131                                               SelectionDAG &DAG) const {
6132   SDLoc DL(Op);
6133   MVT VT = Op.getSimpleValueType();
6134 
6135   SDValue Src = Op.getOperand(0);
6136   // NOTE: Mask is dropped.
6137   SDValue VL = Op.getOperand(2);
6138 
6139   MVT ContainerVT = VT;
6140   if (VT.isFixedLengthVector()) {
6141     ContainerVT = getContainerForFixedLengthVector(VT);
6142     MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6143     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6144   }
6145 
6146   MVT XLenVT = Subtarget.getXLenVT();
6147   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6148   SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6149                                   DAG.getUNDEF(ContainerVT), Zero, VL);
6150 
6151   SDValue SplatValue = DAG.getConstant(
6152       Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT);
6153   SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6154                               DAG.getUNDEF(ContainerVT), SplatValue, VL);
6155 
6156   SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src,
6157                                Splat, ZeroSplat, VL);
6158   if (!VT.isFixedLengthVector())
6159     return Result;
6160   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6161 }
6162 
6163 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op,
6164                                                 SelectionDAG &DAG) const {
6165   SDLoc DL(Op);
6166   MVT VT = Op.getSimpleValueType();
6167 
6168   SDValue Op1 = Op.getOperand(0);
6169   SDValue Op2 = Op.getOperand(1);
6170   ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6171   // NOTE: Mask is dropped.
6172   SDValue VL = Op.getOperand(4);
6173 
6174   MVT ContainerVT = VT;
6175   if (VT.isFixedLengthVector()) {
6176     ContainerVT = getContainerForFixedLengthVector(VT);
6177     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6178     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6179   }
6180 
6181   SDValue Result;
6182   SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
6183 
6184   switch (Condition) {
6185   default:
6186     break;
6187   // X != Y  --> (X^Y)
6188   case ISD::SETNE:
6189     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6190     break;
6191   // X == Y  --> ~(X^Y)
6192   case ISD::SETEQ: {
6193     SDValue Temp =
6194         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6195     Result =
6196         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL);
6197     break;
6198   }
6199   // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
6200   // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
6201   case ISD::SETGT:
6202   case ISD::SETULT: {
6203     SDValue Temp =
6204         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6205     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL);
6206     break;
6207   }
6208   // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
6209   // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
6210   case ISD::SETLT:
6211   case ISD::SETUGT: {
6212     SDValue Temp =
6213         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6214     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL);
6215     break;
6216   }
6217   // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
6218   // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
6219   case ISD::SETGE:
6220   case ISD::SETULE: {
6221     SDValue Temp =
6222         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6223     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL);
6224     break;
6225   }
6226   // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
6227   // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
6228   case ISD::SETLE:
6229   case ISD::SETUGE: {
6230     SDValue Temp =
6231         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6232     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL);
6233     break;
6234   }
6235   }
6236 
6237   if (!VT.isFixedLengthVector())
6238     return Result;
6239   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6240 }
6241 
6242 // Lower Floating-Point/Integer Type-Convert VP SDNodes
6243 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
6244                                                 unsigned RISCVISDOpc) const {
6245   SDLoc DL(Op);
6246 
6247   SDValue Src = Op.getOperand(0);
6248   SDValue Mask = Op.getOperand(1);
6249   SDValue VL = Op.getOperand(2);
6250 
6251   MVT DstVT = Op.getSimpleValueType();
6252   MVT SrcVT = Src.getSimpleValueType();
6253   if (DstVT.isFixedLengthVector()) {
6254     DstVT = getContainerForFixedLengthVector(DstVT);
6255     SrcVT = getContainerForFixedLengthVector(SrcVT);
6256     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6257     MVT MaskVT = getMaskTypeFor(DstVT);
6258     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6259   }
6260 
6261   unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL ||
6262                              RISCVISDOpc == RISCVISD::FP_TO_SINT_VL)
6263                                 ? RISCVISD::VSEXT_VL
6264                                 : RISCVISD::VZEXT_VL;
6265 
6266   unsigned DstEltSize = DstVT.getScalarSizeInBits();
6267   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
6268 
6269   SDValue Result;
6270   if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
6271     if (SrcVT.isInteger()) {
6272       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6273 
6274       // Do we need to do any pre-widening before converting?
6275       if (SrcEltSize == 1) {
6276         MVT IntVT = DstVT.changeVectorElementTypeToInteger();
6277         MVT XLenVT = Subtarget.getXLenVT();
6278         SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6279         SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6280                                         DAG.getUNDEF(IntVT), Zero, VL);
6281         SDValue One = DAG.getConstant(
6282             RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
6283         SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6284                                        DAG.getUNDEF(IntVT), One, VL);
6285         Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
6286                           ZeroSplat, VL);
6287       } else if (DstEltSize > (2 * SrcEltSize)) {
6288         // Widen before converting.
6289         MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
6290                                      DstVT.getVectorElementCount());
6291         Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL);
6292       }
6293 
6294       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6295     } else {
6296       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6297              "Wrong input/output vector types");
6298 
6299       // Convert f16 to f32 then convert f32 to i64.
6300       if (DstEltSize > (2 * SrcEltSize)) {
6301         assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6302         MVT InterimFVT =
6303             MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6304         Src =
6305             DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL);
6306       }
6307 
6308       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6309     }
6310   } else { // Narrowing + Conversion
6311     if (SrcVT.isInteger()) {
6312       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6313       // First do a narrowing convert to an FP type half the size, then round
6314       // the FP type to a small FP type if needed.
6315 
6316       MVT InterimFVT = DstVT;
6317       if (SrcEltSize > (2 * DstEltSize)) {
6318         assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
6319         assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6320         InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6321       }
6322 
6323       Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL);
6324 
6325       if (InterimFVT != DstVT) {
6326         Src = Result;
6327         Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL);
6328       }
6329     } else {
6330       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6331              "Wrong input/output vector types");
6332       // First do a narrowing conversion to an integer half the size, then
6333       // truncate if needed.
6334 
6335       if (DstEltSize == 1) {
6336         // First convert to the same size integer, then convert to mask using
6337         // setcc.
6338         assert(SrcEltSize >= 16 && "Unexpected FP type!");
6339         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize),
6340                                           DstVT.getVectorElementCount());
6341         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6342 
6343         // Compare the integer result to 0. The integer should be 0 or 1/-1,
6344         // otherwise the conversion was undefined.
6345         MVT XLenVT = Subtarget.getXLenVT();
6346         SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
6347         SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT,
6348                                 DAG.getUNDEF(InterimIVT), SplatZero);
6349         Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero,
6350                              DAG.getCondCode(ISD::SETNE), Mask, VL);
6351       } else {
6352         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6353                                           DstVT.getVectorElementCount());
6354 
6355         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6356 
6357         while (InterimIVT != DstVT) {
6358           SrcEltSize /= 2;
6359           Src = Result;
6360           InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6361                                         DstVT.getVectorElementCount());
6362           Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
6363                                Src, Mask, VL);
6364         }
6365       }
6366     }
6367   }
6368 
6369   MVT VT = Op.getSimpleValueType();
6370   if (!VT.isFixedLengthVector())
6371     return Result;
6372   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6373 }
6374 
6375 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6376                                             unsigned MaskOpc,
6377                                             unsigned VecOpc) const {
6378   MVT VT = Op.getSimpleValueType();
6379   if (VT.getVectorElementType() != MVT::i1)
6380     return lowerVPOp(Op, DAG, VecOpc);
6381 
6382   // It is safe to drop mask parameter as masked-off elements are undef.
6383   SDValue Op1 = Op->getOperand(0);
6384   SDValue Op2 = Op->getOperand(1);
6385   SDValue VL = Op->getOperand(3);
6386 
6387   MVT ContainerVT = VT;
6388   const bool IsFixed = VT.isFixedLengthVector();
6389   if (IsFixed) {
6390     ContainerVT = getContainerForFixedLengthVector(VT);
6391     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6392     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6393   }
6394 
6395   SDLoc DL(Op);
6396   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6397   if (!IsFixed)
6398     return Val;
6399   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6400 }
6401 
6402 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6403 // matched to a RVV indexed load. The RVV indexed load instructions only
6404 // support the "unsigned unscaled" addressing mode; indices are implicitly
6405 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6406 // signed or scaled indexing is extended to the XLEN value type and scaled
6407 // accordingly.
6408 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6409                                                SelectionDAG &DAG) const {
6410   SDLoc DL(Op);
6411   MVT VT = Op.getSimpleValueType();
6412 
6413   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6414   EVT MemVT = MemSD->getMemoryVT();
6415   MachineMemOperand *MMO = MemSD->getMemOperand();
6416   SDValue Chain = MemSD->getChain();
6417   SDValue BasePtr = MemSD->getBasePtr();
6418 
6419   ISD::LoadExtType LoadExtType;
6420   SDValue Index, Mask, PassThru, VL;
6421 
6422   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6423     Index = VPGN->getIndex();
6424     Mask = VPGN->getMask();
6425     PassThru = DAG.getUNDEF(VT);
6426     VL = VPGN->getVectorLength();
6427     // VP doesn't support extending loads.
6428     LoadExtType = ISD::NON_EXTLOAD;
6429   } else {
6430     // Else it must be a MGATHER.
6431     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6432     Index = MGN->getIndex();
6433     Mask = MGN->getMask();
6434     PassThru = MGN->getPassThru();
6435     LoadExtType = MGN->getExtensionType();
6436   }
6437 
6438   MVT IndexVT = Index.getSimpleValueType();
6439   MVT XLenVT = Subtarget.getXLenVT();
6440 
6441   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6442          "Unexpected VTs!");
6443   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6444   // Targets have to explicitly opt-in for extending vector loads.
6445   assert(LoadExtType == ISD::NON_EXTLOAD &&
6446          "Unexpected extending MGATHER/VP_GATHER");
6447   (void)LoadExtType;
6448 
6449   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6450   // the selection of the masked intrinsics doesn't do this for us.
6451   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6452 
6453   MVT ContainerVT = VT;
6454   if (VT.isFixedLengthVector()) {
6455     ContainerVT = getContainerForFixedLengthVector(VT);
6456     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6457                                ContainerVT.getVectorElementCount());
6458 
6459     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6460 
6461     if (!IsUnmasked) {
6462       MVT MaskVT = getMaskTypeFor(ContainerVT);
6463       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6464       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6465     }
6466   }
6467 
6468   if (!VL)
6469     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6470 
6471   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6472     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6473     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6474                                    VL);
6475     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6476                         TrueMask, VL);
6477   }
6478 
6479   unsigned IntID =
6480       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6481   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6482   if (IsUnmasked)
6483     Ops.push_back(DAG.getUNDEF(ContainerVT));
6484   else
6485     Ops.push_back(PassThru);
6486   Ops.push_back(BasePtr);
6487   Ops.push_back(Index);
6488   if (!IsUnmasked)
6489     Ops.push_back(Mask);
6490   Ops.push_back(VL);
6491   if (!IsUnmasked)
6492     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6493 
6494   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6495   SDValue Result =
6496       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6497   Chain = Result.getValue(1);
6498 
6499   if (VT.isFixedLengthVector())
6500     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6501 
6502   return DAG.getMergeValues({Result, Chain}, DL);
6503 }
6504 
6505 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6506 // matched to a RVV indexed store. The RVV indexed store instructions only
6507 // support the "unsigned unscaled" addressing mode; indices are implicitly
6508 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6509 // signed or scaled indexing is extended to the XLEN value type and scaled
6510 // accordingly.
6511 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6512                                                 SelectionDAG &DAG) const {
6513   SDLoc DL(Op);
6514   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6515   EVT MemVT = MemSD->getMemoryVT();
6516   MachineMemOperand *MMO = MemSD->getMemOperand();
6517   SDValue Chain = MemSD->getChain();
6518   SDValue BasePtr = MemSD->getBasePtr();
6519 
6520   bool IsTruncatingStore = false;
6521   SDValue Index, Mask, Val, VL;
6522 
6523   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6524     Index = VPSN->getIndex();
6525     Mask = VPSN->getMask();
6526     Val = VPSN->getValue();
6527     VL = VPSN->getVectorLength();
6528     // VP doesn't support truncating stores.
6529     IsTruncatingStore = false;
6530   } else {
6531     // Else it must be a MSCATTER.
6532     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6533     Index = MSN->getIndex();
6534     Mask = MSN->getMask();
6535     Val = MSN->getValue();
6536     IsTruncatingStore = MSN->isTruncatingStore();
6537   }
6538 
6539   MVT VT = Val.getSimpleValueType();
6540   MVT IndexVT = Index.getSimpleValueType();
6541   MVT XLenVT = Subtarget.getXLenVT();
6542 
6543   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6544          "Unexpected VTs!");
6545   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6546   // Targets have to explicitly opt-in for extending vector loads and
6547   // truncating vector stores.
6548   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6549   (void)IsTruncatingStore;
6550 
6551   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6552   // the selection of the masked intrinsics doesn't do this for us.
6553   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6554 
6555   MVT ContainerVT = VT;
6556   if (VT.isFixedLengthVector()) {
6557     ContainerVT = getContainerForFixedLengthVector(VT);
6558     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6559                                ContainerVT.getVectorElementCount());
6560 
6561     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6562     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6563 
6564     if (!IsUnmasked) {
6565       MVT MaskVT = getMaskTypeFor(ContainerVT);
6566       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6567     }
6568   }
6569 
6570   if (!VL)
6571     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6572 
6573   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6574     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6575     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6576                                    VL);
6577     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6578                         TrueMask, VL);
6579   }
6580 
6581   unsigned IntID =
6582       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6583   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6584   Ops.push_back(Val);
6585   Ops.push_back(BasePtr);
6586   Ops.push_back(Index);
6587   if (!IsUnmasked)
6588     Ops.push_back(Mask);
6589   Ops.push_back(VL);
6590 
6591   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6592                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6593 }
6594 
6595 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6596                                                SelectionDAG &DAG) const {
6597   const MVT XLenVT = Subtarget.getXLenVT();
6598   SDLoc DL(Op);
6599   SDValue Chain = Op->getOperand(0);
6600   SDValue SysRegNo = DAG.getTargetConstant(
6601       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6602   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6603   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6604 
6605   // Encoding used for rounding mode in RISCV differs from that used in
6606   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6607   // table, which consists of a sequence of 4-bit fields, each representing
6608   // corresponding FLT_ROUNDS mode.
6609   static const int Table =
6610       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6611       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6612       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6613       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6614       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6615 
6616   SDValue Shift =
6617       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6618   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6619                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6620   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6621                                DAG.getConstant(7, DL, XLenVT));
6622 
6623   return DAG.getMergeValues({Masked, Chain}, DL);
6624 }
6625 
6626 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6627                                                SelectionDAG &DAG) const {
6628   const MVT XLenVT = Subtarget.getXLenVT();
6629   SDLoc DL(Op);
6630   SDValue Chain = Op->getOperand(0);
6631   SDValue RMValue = Op->getOperand(1);
6632   SDValue SysRegNo = DAG.getTargetConstant(
6633       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6634 
6635   // Encoding used for rounding mode in RISCV differs from that used in
6636   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6637   // a table, which consists of a sequence of 4-bit fields, each representing
6638   // corresponding RISCV mode.
6639   static const unsigned Table =
6640       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6641       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6642       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6643       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6644       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6645 
6646   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6647                               DAG.getConstant(2, DL, XLenVT));
6648   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6649                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6650   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6651                         DAG.getConstant(0x7, DL, XLenVT));
6652   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6653                      RMValue);
6654 }
6655 
6656 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
6657                                                SelectionDAG &DAG) const {
6658   MachineFunction &MF = DAG.getMachineFunction();
6659 
6660   bool isRISCV64 = Subtarget.is64Bit();
6661   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6662 
6663   int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false);
6664   return DAG.getFrameIndex(FI, PtrVT);
6665 }
6666 
6667 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6668   switch (IntNo) {
6669   default:
6670     llvm_unreachable("Unexpected Intrinsic");
6671   case Intrinsic::riscv_bcompress:
6672     return RISCVISD::BCOMPRESSW;
6673   case Intrinsic::riscv_bdecompress:
6674     return RISCVISD::BDECOMPRESSW;
6675   case Intrinsic::riscv_bfp:
6676     return RISCVISD::BFPW;
6677   case Intrinsic::riscv_fsl:
6678     return RISCVISD::FSLW;
6679   case Intrinsic::riscv_fsr:
6680     return RISCVISD::FSRW;
6681   }
6682 }
6683 
6684 // Converts the given intrinsic to a i64 operation with any extension.
6685 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6686                                          unsigned IntNo) {
6687   SDLoc DL(N);
6688   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6689   // Deal with the Instruction Operands
6690   SmallVector<SDValue, 3> NewOps;
6691   for (SDValue Op : drop_begin(N->ops()))
6692     // Promote the operand to i64 type
6693     NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op));
6694   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps);
6695   // ReplaceNodeResults requires we maintain the same type for the return value.
6696   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6697 }
6698 
6699 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6700 // form of the given Opcode.
6701 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6702   switch (Opcode) {
6703   default:
6704     llvm_unreachable("Unexpected opcode");
6705   case ISD::SHL:
6706     return RISCVISD::SLLW;
6707   case ISD::SRA:
6708     return RISCVISD::SRAW;
6709   case ISD::SRL:
6710     return RISCVISD::SRLW;
6711   case ISD::SDIV:
6712     return RISCVISD::DIVW;
6713   case ISD::UDIV:
6714     return RISCVISD::DIVUW;
6715   case ISD::UREM:
6716     return RISCVISD::REMUW;
6717   case ISD::ROTL:
6718     return RISCVISD::ROLW;
6719   case ISD::ROTR:
6720     return RISCVISD::RORW;
6721   }
6722 }
6723 
6724 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6725 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6726 // otherwise be promoted to i64, making it difficult to select the
6727 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6728 // type i8/i16/i32 is lost.
6729 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6730                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6731   SDLoc DL(N);
6732   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6733   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6734   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6735   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6736   // ReplaceNodeResults requires we maintain the same type for the return value.
6737   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6738 }
6739 
6740 // Converts the given 32-bit operation to a i64 operation with signed extension
6741 // semantic to reduce the signed extension instructions.
6742 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6743   SDLoc DL(N);
6744   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6745   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6746   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6747   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6748                                DAG.getValueType(MVT::i32));
6749   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6750 }
6751 
6752 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6753                                              SmallVectorImpl<SDValue> &Results,
6754                                              SelectionDAG &DAG) const {
6755   SDLoc DL(N);
6756   switch (N->getOpcode()) {
6757   default:
6758     llvm_unreachable("Don't know how to custom type legalize this operation!");
6759   case ISD::STRICT_FP_TO_SINT:
6760   case ISD::STRICT_FP_TO_UINT:
6761   case ISD::FP_TO_SINT:
6762   case ISD::FP_TO_UINT: {
6763     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6764            "Unexpected custom legalisation");
6765     bool IsStrict = N->isStrictFPOpcode();
6766     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6767                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6768     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6769     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6770         TargetLowering::TypeSoftenFloat) {
6771       if (!isTypeLegal(Op0.getValueType()))
6772         return;
6773       if (IsStrict) {
6774         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6775                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6776         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6777         SDValue Res = DAG.getNode(
6778             Opc, DL, VTs, N->getOperand(0), Op0,
6779             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6780         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6781         Results.push_back(Res.getValue(1));
6782         return;
6783       }
6784       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6785       SDValue Res =
6786           DAG.getNode(Opc, DL, MVT::i64, Op0,
6787                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6788       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6789       return;
6790     }
6791     // If the FP type needs to be softened, emit a library call using the 'si'
6792     // version. If we left it to default legalization we'd end up with 'di'. If
6793     // the FP type doesn't need to be softened just let generic type
6794     // legalization promote the result type.
6795     RTLIB::Libcall LC;
6796     if (IsSigned)
6797       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6798     else
6799       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6800     MakeLibCallOptions CallOptions;
6801     EVT OpVT = Op0.getValueType();
6802     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6803     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6804     SDValue Result;
6805     std::tie(Result, Chain) =
6806         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6807     Results.push_back(Result);
6808     if (IsStrict)
6809       Results.push_back(Chain);
6810     break;
6811   }
6812   case ISD::READCYCLECOUNTER: {
6813     assert(!Subtarget.is64Bit() &&
6814            "READCYCLECOUNTER only has custom type legalization on riscv32");
6815 
6816     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6817     SDValue RCW =
6818         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6819 
6820     Results.push_back(
6821         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6822     Results.push_back(RCW.getValue(2));
6823     break;
6824   }
6825   case ISD::MUL: {
6826     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6827     unsigned XLen = Subtarget.getXLen();
6828     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6829     if (Size > XLen) {
6830       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6831       SDValue LHS = N->getOperand(0);
6832       SDValue RHS = N->getOperand(1);
6833       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6834 
6835       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6836       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6837       // We need exactly one side to be unsigned.
6838       if (LHSIsU == RHSIsU)
6839         return;
6840 
6841       auto MakeMULPair = [&](SDValue S, SDValue U) {
6842         MVT XLenVT = Subtarget.getXLenVT();
6843         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6844         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6845         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6846         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6847         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6848       };
6849 
6850       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6851       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6852 
6853       // The other operand should be signed, but still prefer MULH when
6854       // possible.
6855       if (RHSIsU && LHSIsS && !RHSIsS)
6856         Results.push_back(MakeMULPair(LHS, RHS));
6857       else if (LHSIsU && RHSIsS && !LHSIsS)
6858         Results.push_back(MakeMULPair(RHS, LHS));
6859 
6860       return;
6861     }
6862     LLVM_FALLTHROUGH;
6863   }
6864   case ISD::ADD:
6865   case ISD::SUB:
6866     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6867            "Unexpected custom legalisation");
6868     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6869     break;
6870   case ISD::SHL:
6871   case ISD::SRA:
6872   case ISD::SRL:
6873     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6874            "Unexpected custom legalisation");
6875     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6876       // If we can use a BSET instruction, allow default promotion to apply.
6877       if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() &&
6878           isOneConstant(N->getOperand(0)))
6879         break;
6880       Results.push_back(customLegalizeToWOp(N, DAG));
6881       break;
6882     }
6883 
6884     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6885     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6886     // shift amount.
6887     if (N->getOpcode() == ISD::SHL) {
6888       SDLoc DL(N);
6889       SDValue NewOp0 =
6890           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6891       SDValue NewOp1 =
6892           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6893       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6894       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6895                                    DAG.getValueType(MVT::i32));
6896       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6897     }
6898 
6899     break;
6900   case ISD::ROTL:
6901   case ISD::ROTR:
6902     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6903            "Unexpected custom legalisation");
6904     Results.push_back(customLegalizeToWOp(N, DAG));
6905     break;
6906   case ISD::CTTZ:
6907   case ISD::CTTZ_ZERO_UNDEF:
6908   case ISD::CTLZ:
6909   case ISD::CTLZ_ZERO_UNDEF: {
6910     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6911            "Unexpected custom legalisation");
6912 
6913     SDValue NewOp0 =
6914         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6915     bool IsCTZ =
6916         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6917     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6918     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6919     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6920     return;
6921   }
6922   case ISD::SDIV:
6923   case ISD::UDIV:
6924   case ISD::UREM: {
6925     MVT VT = N->getSimpleValueType(0);
6926     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6927            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6928            "Unexpected custom legalisation");
6929     // Don't promote division/remainder by constant since we should expand those
6930     // to multiply by magic constant.
6931     // FIXME: What if the expansion is disabled for minsize.
6932     if (N->getOperand(1).getOpcode() == ISD::Constant)
6933       return;
6934 
6935     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6936     // the upper 32 bits. For other types we need to sign or zero extend
6937     // based on the opcode.
6938     unsigned ExtOpc = ISD::ANY_EXTEND;
6939     if (VT != MVT::i32)
6940       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6941                                            : ISD::ZERO_EXTEND;
6942 
6943     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6944     break;
6945   }
6946   case ISD::UADDO:
6947   case ISD::USUBO: {
6948     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6949            "Unexpected custom legalisation");
6950     bool IsAdd = N->getOpcode() == ISD::UADDO;
6951     // Create an ADDW or SUBW.
6952     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6953     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6954     SDValue Res =
6955         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6956     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6957                       DAG.getValueType(MVT::i32));
6958 
6959     SDValue Overflow;
6960     if (IsAdd && isOneConstant(RHS)) {
6961       // Special case uaddo X, 1 overflowed if the addition result is 0.
6962       // The general case (X + C) < C is not necessarily beneficial. Although we
6963       // reduce the live range of X, we may introduce the materialization of
6964       // constant C, especially when the setcc result is used by branch. We have
6965       // no compare with constant and branch instructions.
6966       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res,
6967                               DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ);
6968     } else {
6969       // Sign extend the LHS and perform an unsigned compare with the ADDW
6970       // result. Since the inputs are sign extended from i32, this is equivalent
6971       // to comparing the lower 32 bits.
6972       LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6973       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6974                               IsAdd ? ISD::SETULT : ISD::SETUGT);
6975     }
6976 
6977     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6978     Results.push_back(Overflow);
6979     return;
6980   }
6981   case ISD::UADDSAT:
6982   case ISD::USUBSAT: {
6983     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6984            "Unexpected custom legalisation");
6985     if (Subtarget.hasStdExtZbb()) {
6986       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6987       // sign extend allows overflow of the lower 32 bits to be detected on
6988       // the promoted size.
6989       SDValue LHS =
6990           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6991       SDValue RHS =
6992           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6993       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6994       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6995       return;
6996     }
6997 
6998     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6999     // promotion for UADDO/USUBO.
7000     Results.push_back(expandAddSubSat(N, DAG));
7001     return;
7002   }
7003   case ISD::ABS: {
7004     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7005            "Unexpected custom legalisation");
7006           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
7007 
7008     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
7009 
7010     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7011 
7012     // Freeze the source so we can increase it's use count.
7013     Src = DAG.getFreeze(Src);
7014 
7015     // Copy sign bit to all bits using the sraiw pattern.
7016     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
7017                                    DAG.getValueType(MVT::i32));
7018     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
7019                            DAG.getConstant(31, DL, MVT::i64));
7020 
7021     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
7022     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
7023 
7024     // NOTE: The result is only required to be anyextended, but sext is
7025     // consistent with type legalization of sub.
7026     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
7027                          DAG.getValueType(MVT::i32));
7028     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
7029     return;
7030   }
7031   case ISD::BITCAST: {
7032     EVT VT = N->getValueType(0);
7033     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
7034     SDValue Op0 = N->getOperand(0);
7035     EVT Op0VT = Op0.getValueType();
7036     MVT XLenVT = Subtarget.getXLenVT();
7037     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
7038       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
7039       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
7040     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
7041                Subtarget.hasStdExtF()) {
7042       SDValue FPConv =
7043           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
7044       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
7045     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
7046                isTypeLegal(Op0VT)) {
7047       // Custom-legalize bitcasts from fixed-length vector types to illegal
7048       // scalar types in order to improve codegen. Bitcast the vector to a
7049       // one-element vector type whose element type is the same as the result
7050       // type, and extract the first element.
7051       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
7052       if (isTypeLegal(BVT)) {
7053         SDValue BVec = DAG.getBitcast(BVT, Op0);
7054         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
7055                                       DAG.getConstant(0, DL, XLenVT)));
7056       }
7057     }
7058     break;
7059   }
7060   case RISCVISD::GREV:
7061   case RISCVISD::GORC:
7062   case RISCVISD::SHFL: {
7063     MVT VT = N->getSimpleValueType(0);
7064     MVT XLenVT = Subtarget.getXLenVT();
7065     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
7066            "Unexpected custom legalisation");
7067     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
7068     assert((Subtarget.hasStdExtZbp() ||
7069             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
7070              N->getConstantOperandVal(1) == 7)) &&
7071            "Unexpected extension");
7072     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7073     SDValue NewOp1 =
7074         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
7075     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
7076     // ReplaceNodeResults requires we maintain the same type for the return
7077     // value.
7078     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
7079     break;
7080   }
7081   case ISD::BSWAP:
7082   case ISD::BITREVERSE: {
7083     MVT VT = N->getSimpleValueType(0);
7084     MVT XLenVT = Subtarget.getXLenVT();
7085     assert((VT == MVT::i8 || VT == MVT::i16 ||
7086             (VT == MVT::i32 && Subtarget.is64Bit())) &&
7087            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
7088     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7089     unsigned Imm = VT.getSizeInBits() - 1;
7090     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
7091     if (N->getOpcode() == ISD::BSWAP)
7092       Imm &= ~0x7U;
7093     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
7094                                 DAG.getConstant(Imm, DL, XLenVT));
7095     // ReplaceNodeResults requires we maintain the same type for the return
7096     // value.
7097     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
7098     break;
7099   }
7100   case ISD::FSHL:
7101   case ISD::FSHR: {
7102     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7103            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
7104     SDValue NewOp0 =
7105         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7106     SDValue NewOp1 =
7107         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7108     SDValue NewShAmt =
7109         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7110     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
7111     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
7112     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
7113                            DAG.getConstant(0x1f, DL, MVT::i64));
7114     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
7115     // instruction use different orders. fshl will return its first operand for
7116     // shift of zero, fshr will return its second operand. fsl and fsr both
7117     // return rs1 so the ISD nodes need to have different operand orders.
7118     // Shift amount is in rs2.
7119     unsigned Opc = RISCVISD::FSLW;
7120     if (N->getOpcode() == ISD::FSHR) {
7121       std::swap(NewOp0, NewOp1);
7122       Opc = RISCVISD::FSRW;
7123     }
7124     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
7125     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
7126     break;
7127   }
7128   case ISD::EXTRACT_VECTOR_ELT: {
7129     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
7130     // type is illegal (currently only vXi64 RV32).
7131     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
7132     // transferred to the destination register. We issue two of these from the
7133     // upper- and lower- halves of the SEW-bit vector element, slid down to the
7134     // first element.
7135     SDValue Vec = N->getOperand(0);
7136     SDValue Idx = N->getOperand(1);
7137 
7138     // The vector type hasn't been legalized yet so we can't issue target
7139     // specific nodes if it needs legalization.
7140     // FIXME: We would manually legalize if it's important.
7141     if (!isTypeLegal(Vec.getValueType()))
7142       return;
7143 
7144     MVT VecVT = Vec.getSimpleValueType();
7145 
7146     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7147            VecVT.getVectorElementType() == MVT::i64 &&
7148            "Unexpected EXTRACT_VECTOR_ELT legalization");
7149 
7150     // If this is a fixed vector, we need to convert it to a scalable vector.
7151     MVT ContainerVT = VecVT;
7152     if (VecVT.isFixedLengthVector()) {
7153       ContainerVT = getContainerForFixedLengthVector(VecVT);
7154       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7155     }
7156 
7157     MVT XLenVT = Subtarget.getXLenVT();
7158 
7159     // Use a VL of 1 to avoid processing more elements than we need.
7160     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7161     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
7162 
7163     // Unless the index is known to be 0, we must slide the vector down to get
7164     // the desired element into index 0.
7165     if (!isNullConstant(Idx)) {
7166       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7167                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7168     }
7169 
7170     // Extract the lower XLEN bits of the correct vector element.
7171     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7172 
7173     // To extract the upper XLEN bits of the vector element, shift the first
7174     // element right by 32 bits and re-extract the lower XLEN bits.
7175     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7176                                      DAG.getUNDEF(ContainerVT),
7177                                      DAG.getConstant(32, DL, XLenVT), VL);
7178     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7179                                  ThirtyTwoV, Mask, VL);
7180 
7181     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7182 
7183     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7184     break;
7185   }
7186   case ISD::INTRINSIC_WO_CHAIN: {
7187     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7188     switch (IntNo) {
7189     default:
7190       llvm_unreachable(
7191           "Don't know how to custom type legalize this intrinsic!");
7192     case Intrinsic::riscv_grev:
7193     case Intrinsic::riscv_gorc: {
7194       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7195              "Unexpected custom legalisation");
7196       SDValue NewOp1 =
7197           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7198       SDValue NewOp2 =
7199           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7200       unsigned Opc =
7201           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7202       // If the control is a constant, promote the node by clearing any extra
7203       // bits bits in the control. isel will form greviw/gorciw if the result is
7204       // sign extended.
7205       if (isa<ConstantSDNode>(NewOp2)) {
7206         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7207                              DAG.getConstant(0x1f, DL, MVT::i64));
7208         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7209       }
7210       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7211       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7212       break;
7213     }
7214     case Intrinsic::riscv_bcompress:
7215     case Intrinsic::riscv_bdecompress:
7216     case Intrinsic::riscv_bfp:
7217     case Intrinsic::riscv_fsl:
7218     case Intrinsic::riscv_fsr: {
7219       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7220              "Unexpected custom legalisation");
7221       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7222       break;
7223     }
7224     case Intrinsic::riscv_orc_b: {
7225       // Lower to the GORCI encoding for orc.b with the operand extended.
7226       SDValue NewOp =
7227           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7228       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7229                                 DAG.getConstant(7, DL, MVT::i64));
7230       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7231       return;
7232     }
7233     case Intrinsic::riscv_shfl:
7234     case Intrinsic::riscv_unshfl: {
7235       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7236              "Unexpected custom legalisation");
7237       SDValue NewOp1 =
7238           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7239       SDValue NewOp2 =
7240           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7241       unsigned Opc =
7242           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7243       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7244       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7245       // will be shuffled the same way as the lower 32 bit half, but the two
7246       // halves won't cross.
7247       if (isa<ConstantSDNode>(NewOp2)) {
7248         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7249                              DAG.getConstant(0xf, DL, MVT::i64));
7250         Opc =
7251             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7252       }
7253       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7254       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7255       break;
7256     }
7257     case Intrinsic::riscv_vmv_x_s: {
7258       EVT VT = N->getValueType(0);
7259       MVT XLenVT = Subtarget.getXLenVT();
7260       if (VT.bitsLT(XLenVT)) {
7261         // Simple case just extract using vmv.x.s and truncate.
7262         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7263                                       Subtarget.getXLenVT(), N->getOperand(1));
7264         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7265         return;
7266       }
7267 
7268       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7269              "Unexpected custom legalization");
7270 
7271       // We need to do the move in two steps.
7272       SDValue Vec = N->getOperand(1);
7273       MVT VecVT = Vec.getSimpleValueType();
7274 
7275       // First extract the lower XLEN bits of the element.
7276       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7277 
7278       // To extract the upper XLEN bits of the vector element, shift the first
7279       // element right by 32 bits and re-extract the lower XLEN bits.
7280       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7281       SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG);
7282 
7283       SDValue ThirtyTwoV =
7284           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7285                       DAG.getConstant(32, DL, XLenVT), VL);
7286       SDValue LShr32 =
7287           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7288       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7289 
7290       Results.push_back(
7291           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7292       break;
7293     }
7294     }
7295     break;
7296   }
7297   case ISD::VECREDUCE_ADD:
7298   case ISD::VECREDUCE_AND:
7299   case ISD::VECREDUCE_OR:
7300   case ISD::VECREDUCE_XOR:
7301   case ISD::VECREDUCE_SMAX:
7302   case ISD::VECREDUCE_UMAX:
7303   case ISD::VECREDUCE_SMIN:
7304   case ISD::VECREDUCE_UMIN:
7305     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7306       Results.push_back(V);
7307     break;
7308   case ISD::VP_REDUCE_ADD:
7309   case ISD::VP_REDUCE_AND:
7310   case ISD::VP_REDUCE_OR:
7311   case ISD::VP_REDUCE_XOR:
7312   case ISD::VP_REDUCE_SMAX:
7313   case ISD::VP_REDUCE_UMAX:
7314   case ISD::VP_REDUCE_SMIN:
7315   case ISD::VP_REDUCE_UMIN:
7316     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7317       Results.push_back(V);
7318     break;
7319   case ISD::FLT_ROUNDS_: {
7320     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7321     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7322     Results.push_back(Res.getValue(0));
7323     Results.push_back(Res.getValue(1));
7324     break;
7325   }
7326   }
7327 }
7328 
7329 // A structure to hold one of the bit-manipulation patterns below. Together, a
7330 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7331 //   (or (and (shl x, 1), 0xAAAAAAAA),
7332 //       (and (srl x, 1), 0x55555555))
7333 struct RISCVBitmanipPat {
7334   SDValue Op;
7335   unsigned ShAmt;
7336   bool IsSHL;
7337 
7338   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7339     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7340   }
7341 };
7342 
7343 // Matches patterns of the form
7344 //   (and (shl x, C2), (C1 << C2))
7345 //   (and (srl x, C2), C1)
7346 //   (shl (and x, C1), C2)
7347 //   (srl (and x, (C1 << C2)), C2)
7348 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7349 // The expected masks for each shift amount are specified in BitmanipMasks where
7350 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7351 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7352 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7353 // XLen is 64.
7354 static Optional<RISCVBitmanipPat>
7355 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7356   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7357          "Unexpected number of masks");
7358   Optional<uint64_t> Mask;
7359   // Optionally consume a mask around the shift operation.
7360   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7361     Mask = Op.getConstantOperandVal(1);
7362     Op = Op.getOperand(0);
7363   }
7364   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7365     return None;
7366   bool IsSHL = Op.getOpcode() == ISD::SHL;
7367 
7368   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7369     return None;
7370   uint64_t ShAmt = Op.getConstantOperandVal(1);
7371 
7372   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7373   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7374     return None;
7375   // If we don't have enough masks for 64 bit, then we must be trying to
7376   // match SHFL so we're only allowed to shift 1/4 of the width.
7377   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7378     return None;
7379 
7380   SDValue Src = Op.getOperand(0);
7381 
7382   // The expected mask is shifted left when the AND is found around SHL
7383   // patterns.
7384   //   ((x >> 1) & 0x55555555)
7385   //   ((x << 1) & 0xAAAAAAAA)
7386   bool SHLExpMask = IsSHL;
7387 
7388   if (!Mask) {
7389     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7390     // the mask is all ones: consume that now.
7391     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7392       Mask = Src.getConstantOperandVal(1);
7393       Src = Src.getOperand(0);
7394       // The expected mask is now in fact shifted left for SRL, so reverse the
7395       // decision.
7396       //   ((x & 0xAAAAAAAA) >> 1)
7397       //   ((x & 0x55555555) << 1)
7398       SHLExpMask = !SHLExpMask;
7399     } else {
7400       // Use a default shifted mask of all-ones if there's no AND, truncated
7401       // down to the expected width. This simplifies the logic later on.
7402       Mask = maskTrailingOnes<uint64_t>(Width);
7403       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7404     }
7405   }
7406 
7407   unsigned MaskIdx = Log2_32(ShAmt);
7408   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7409 
7410   if (SHLExpMask)
7411     ExpMask <<= ShAmt;
7412 
7413   if (Mask != ExpMask)
7414     return None;
7415 
7416   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7417 }
7418 
7419 // Matches any of the following bit-manipulation patterns:
7420 //   (and (shl x, 1), (0x55555555 << 1))
7421 //   (and (srl x, 1), 0x55555555)
7422 //   (shl (and x, 0x55555555), 1)
7423 //   (srl (and x, (0x55555555 << 1)), 1)
7424 // where the shift amount and mask may vary thus:
7425 //   [1]  = 0x55555555 / 0xAAAAAAAA
7426 //   [2]  = 0x33333333 / 0xCCCCCCCC
7427 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7428 //   [8]  = 0x00FF00FF / 0xFF00FF00
7429 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7430 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7431 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7432   // These are the unshifted masks which we use to match bit-manipulation
7433   // patterns. They may be shifted left in certain circumstances.
7434   static const uint64_t BitmanipMasks[] = {
7435       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7436       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7437 
7438   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7439 }
7440 
7441 // Try to fold (<bop> x, (reduction.<bop> vec, start))
7442 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) {
7443   auto BinOpToRVVReduce = [](unsigned Opc) {
7444     switch (Opc) {
7445     default:
7446       llvm_unreachable("Unhandled binary to transfrom reduction");
7447     case ISD::ADD:
7448       return RISCVISD::VECREDUCE_ADD_VL;
7449     case ISD::UMAX:
7450       return RISCVISD::VECREDUCE_UMAX_VL;
7451     case ISD::SMAX:
7452       return RISCVISD::VECREDUCE_SMAX_VL;
7453     case ISD::UMIN:
7454       return RISCVISD::VECREDUCE_UMIN_VL;
7455     case ISD::SMIN:
7456       return RISCVISD::VECREDUCE_SMIN_VL;
7457     case ISD::AND:
7458       return RISCVISD::VECREDUCE_AND_VL;
7459     case ISD::OR:
7460       return RISCVISD::VECREDUCE_OR_VL;
7461     case ISD::XOR:
7462       return RISCVISD::VECREDUCE_XOR_VL;
7463     case ISD::FADD:
7464       return RISCVISD::VECREDUCE_FADD_VL;
7465     case ISD::FMAXNUM:
7466       return RISCVISD::VECREDUCE_FMAX_VL;
7467     case ISD::FMINNUM:
7468       return RISCVISD::VECREDUCE_FMIN_VL;
7469     }
7470   };
7471 
7472   auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) {
7473     return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7474            isNullConstant(V.getOperand(1)) &&
7475            V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc);
7476   };
7477 
7478   unsigned Opc = N->getOpcode();
7479   unsigned ReduceIdx;
7480   if (IsReduction(N->getOperand(0), Opc))
7481     ReduceIdx = 0;
7482   else if (IsReduction(N->getOperand(1), Opc))
7483     ReduceIdx = 1;
7484   else
7485     return SDValue();
7486 
7487   // Skip if FADD disallows reassociation but the combiner needs.
7488   if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation())
7489     return SDValue();
7490 
7491   SDValue Extract = N->getOperand(ReduceIdx);
7492   SDValue Reduce = Extract.getOperand(0);
7493   if (!Reduce.hasOneUse())
7494     return SDValue();
7495 
7496   SDValue ScalarV = Reduce.getOperand(2);
7497 
7498   // Make sure that ScalarV is a splat with VL=1.
7499   if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL &&
7500       ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL &&
7501       ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL)
7502     return SDValue();
7503 
7504   if (!isOneConstant(ScalarV.getOperand(2)))
7505     return SDValue();
7506 
7507   // TODO: Deal with value other than neutral element.
7508   auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) {
7509     if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() &&
7510         isNullFPConstant(V))
7511       return true;
7512     return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(),
7513                                  N->getFlags()) == V;
7514   };
7515 
7516   // Check the scalar of ScalarV is neutral element
7517   if (!IsRVVNeutralElement(N, ScalarV.getOperand(1)))
7518     return SDValue();
7519 
7520   if (!ScalarV.hasOneUse())
7521     return SDValue();
7522 
7523   EVT SplatVT = ScalarV.getValueType();
7524   SDValue NewStart = N->getOperand(1 - ReduceIdx);
7525   unsigned SplatOpc = RISCVISD::VFMV_S_F_VL;
7526   if (SplatVT.isInteger()) {
7527     auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode());
7528     if (!C || C->isZero() || !isInt<5>(C->getSExtValue()))
7529       SplatOpc = RISCVISD::VMV_S_X_VL;
7530     else
7531       SplatOpc = RISCVISD::VMV_V_X_VL;
7532   }
7533 
7534   SDValue NewScalarV =
7535       DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart,
7536                   ScalarV.getOperand(2));
7537   SDValue NewReduce =
7538       DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(),
7539                   Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV,
7540                   Reduce.getOperand(3), Reduce.getOperand(4));
7541   return DAG.getNode(Extract.getOpcode(), SDLoc(Extract),
7542                      Extract.getValueType(), NewReduce, Extract.getOperand(1));
7543 }
7544 
7545 // Match the following pattern as a GREVI(W) operation
7546 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7547 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7548                                const RISCVSubtarget &Subtarget) {
7549   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7550   EVT VT = Op.getValueType();
7551 
7552   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7553     auto LHS = matchGREVIPat(Op.getOperand(0));
7554     auto RHS = matchGREVIPat(Op.getOperand(1));
7555     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7556       SDLoc DL(Op);
7557       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7558                          DAG.getConstant(LHS->ShAmt, DL, VT));
7559     }
7560   }
7561   return SDValue();
7562 }
7563 
7564 // Matches any the following pattern as a GORCI(W) operation
7565 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7566 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7567 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7568 // Note that with the variant of 3.,
7569 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7570 // the inner pattern will first be matched as GREVI and then the outer
7571 // pattern will be matched to GORC via the first rule above.
7572 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7573 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7574                                const RISCVSubtarget &Subtarget) {
7575   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7576   EVT VT = Op.getValueType();
7577 
7578   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7579     SDLoc DL(Op);
7580     SDValue Op0 = Op.getOperand(0);
7581     SDValue Op1 = Op.getOperand(1);
7582 
7583     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7584       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7585           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7586           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7587         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7588       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7589       if ((Reverse.getOpcode() == ISD::ROTL ||
7590            Reverse.getOpcode() == ISD::ROTR) &&
7591           Reverse.getOperand(0) == X &&
7592           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7593         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7594         if (RotAmt == (VT.getSizeInBits() / 2))
7595           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7596                              DAG.getConstant(RotAmt, DL, VT));
7597       }
7598       return SDValue();
7599     };
7600 
7601     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7602     if (SDValue V = MatchOROfReverse(Op0, Op1))
7603       return V;
7604     if (SDValue V = MatchOROfReverse(Op1, Op0))
7605       return V;
7606 
7607     // OR is commutable so canonicalize its OR operand to the left
7608     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7609       std::swap(Op0, Op1);
7610     if (Op0.getOpcode() != ISD::OR)
7611       return SDValue();
7612     SDValue OrOp0 = Op0.getOperand(0);
7613     SDValue OrOp1 = Op0.getOperand(1);
7614     auto LHS = matchGREVIPat(OrOp0);
7615     // OR is commutable so swap the operands and try again: x might have been
7616     // on the left
7617     if (!LHS) {
7618       std::swap(OrOp0, OrOp1);
7619       LHS = matchGREVIPat(OrOp0);
7620     }
7621     auto RHS = matchGREVIPat(Op1);
7622     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7623       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7624                          DAG.getConstant(LHS->ShAmt, DL, VT));
7625     }
7626   }
7627   return SDValue();
7628 }
7629 
7630 // Matches any of the following bit-manipulation patterns:
7631 //   (and (shl x, 1), (0x22222222 << 1))
7632 //   (and (srl x, 1), 0x22222222)
7633 //   (shl (and x, 0x22222222), 1)
7634 //   (srl (and x, (0x22222222 << 1)), 1)
7635 // where the shift amount and mask may vary thus:
7636 //   [1]  = 0x22222222 / 0x44444444
7637 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7638 //   [4]  = 0x00F000F0 / 0x0F000F00
7639 //   [8]  = 0x0000FF00 / 0x00FF0000
7640 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7641 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7642   // These are the unshifted masks which we use to match bit-manipulation
7643   // patterns. They may be shifted left in certain circumstances.
7644   static const uint64_t BitmanipMasks[] = {
7645       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7646       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7647 
7648   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7649 }
7650 
7651 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7652 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7653                                const RISCVSubtarget &Subtarget) {
7654   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7655   EVT VT = Op.getValueType();
7656 
7657   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7658     return SDValue();
7659 
7660   SDValue Op0 = Op.getOperand(0);
7661   SDValue Op1 = Op.getOperand(1);
7662 
7663   // Or is commutable so canonicalize the second OR to the LHS.
7664   if (Op0.getOpcode() != ISD::OR)
7665     std::swap(Op0, Op1);
7666   if (Op0.getOpcode() != ISD::OR)
7667     return SDValue();
7668 
7669   // We found an inner OR, so our operands are the operands of the inner OR
7670   // and the other operand of the outer OR.
7671   SDValue A = Op0.getOperand(0);
7672   SDValue B = Op0.getOperand(1);
7673   SDValue C = Op1;
7674 
7675   auto Match1 = matchSHFLPat(A);
7676   auto Match2 = matchSHFLPat(B);
7677 
7678   // If neither matched, we failed.
7679   if (!Match1 && !Match2)
7680     return SDValue();
7681 
7682   // We had at least one match. if one failed, try the remaining C operand.
7683   if (!Match1) {
7684     std::swap(A, C);
7685     Match1 = matchSHFLPat(A);
7686     if (!Match1)
7687       return SDValue();
7688   } else if (!Match2) {
7689     std::swap(B, C);
7690     Match2 = matchSHFLPat(B);
7691     if (!Match2)
7692       return SDValue();
7693   }
7694   assert(Match1 && Match2);
7695 
7696   // Make sure our matches pair up.
7697   if (!Match1->formsPairWith(*Match2))
7698     return SDValue();
7699 
7700   // All the remains is to make sure C is an AND with the same input, that masks
7701   // out the bits that are being shuffled.
7702   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7703       C.getOperand(0) != Match1->Op)
7704     return SDValue();
7705 
7706   uint64_t Mask = C.getConstantOperandVal(1);
7707 
7708   static const uint64_t BitmanipMasks[] = {
7709       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7710       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7711   };
7712 
7713   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7714   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7715   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7716 
7717   if (Mask != ExpMask)
7718     return SDValue();
7719 
7720   SDLoc DL(Op);
7721   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7722                      DAG.getConstant(Match1->ShAmt, DL, VT));
7723 }
7724 
7725 // Optimize (add (shl x, c0), (shl y, c1)) ->
7726 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7727 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7728                                   const RISCVSubtarget &Subtarget) {
7729   // Perform this optimization only in the zba extension.
7730   if (!Subtarget.hasStdExtZba())
7731     return SDValue();
7732 
7733   // Skip for vector types and larger types.
7734   EVT VT = N->getValueType(0);
7735   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7736     return SDValue();
7737 
7738   // The two operand nodes must be SHL and have no other use.
7739   SDValue N0 = N->getOperand(0);
7740   SDValue N1 = N->getOperand(1);
7741   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7742       !N0->hasOneUse() || !N1->hasOneUse())
7743     return SDValue();
7744 
7745   // Check c0 and c1.
7746   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7747   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7748   if (!N0C || !N1C)
7749     return SDValue();
7750   int64_t C0 = N0C->getSExtValue();
7751   int64_t C1 = N1C->getSExtValue();
7752   if (C0 <= 0 || C1 <= 0)
7753     return SDValue();
7754 
7755   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7756   int64_t Bits = std::min(C0, C1);
7757   int64_t Diff = std::abs(C0 - C1);
7758   if (Diff != 1 && Diff != 2 && Diff != 3)
7759     return SDValue();
7760 
7761   // Build nodes.
7762   SDLoc DL(N);
7763   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7764   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7765   SDValue NA0 =
7766       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7767   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7768   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7769 }
7770 
7771 // Combine
7772 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7773 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7774 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7775 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7776 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7777 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7778 // The grev patterns represents BSWAP.
7779 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7780 // off the grev.
7781 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7782                                           const RISCVSubtarget &Subtarget) {
7783   bool IsWInstruction =
7784       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7785   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7786           IsWInstruction) &&
7787          "Unexpected opcode!");
7788   SDValue Src = N->getOperand(0);
7789   EVT VT = N->getValueType(0);
7790   SDLoc DL(N);
7791 
7792   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7793     return SDValue();
7794 
7795   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7796       !isa<ConstantSDNode>(Src.getOperand(1)))
7797     return SDValue();
7798 
7799   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7800   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7801 
7802   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7803   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7804   unsigned ShAmt1 = N->getConstantOperandVal(1);
7805   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7806   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7807     return SDValue();
7808 
7809   Src = Src.getOperand(0);
7810 
7811   // Toggle bit the MSB of the shift.
7812   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7813   if (CombinedShAmt == 0)
7814     return Src;
7815 
7816   SDValue Res = DAG.getNode(
7817       RISCVISD::GREV, DL, VT, Src,
7818       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7819   if (!IsWInstruction)
7820     return Res;
7821 
7822   // Sign extend the result to match the behavior of the rotate. This will be
7823   // selected to GREVIW in isel.
7824   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7825                      DAG.getValueType(MVT::i32));
7826 }
7827 
7828 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7829 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7830 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7831 // not undo itself, but they are redundant.
7832 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7833   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7834   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7835   SDValue Src = N->getOperand(0);
7836 
7837   if (Src.getOpcode() != N->getOpcode())
7838     return SDValue();
7839 
7840   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7841       !isa<ConstantSDNode>(Src.getOperand(1)))
7842     return SDValue();
7843 
7844   unsigned ShAmt1 = N->getConstantOperandVal(1);
7845   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7846   Src = Src.getOperand(0);
7847 
7848   unsigned CombinedShAmt;
7849   if (IsGORC)
7850     CombinedShAmt = ShAmt1 | ShAmt2;
7851   else
7852     CombinedShAmt = ShAmt1 ^ ShAmt2;
7853 
7854   if (CombinedShAmt == 0)
7855     return Src;
7856 
7857   SDLoc DL(N);
7858   return DAG.getNode(
7859       N->getOpcode(), DL, N->getValueType(0), Src,
7860       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7861 }
7862 
7863 // Combine a constant select operand into its use:
7864 //
7865 // (and (select cond, -1, c), x)
7866 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7867 // (or  (select cond, 0, c), x)
7868 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7869 // (xor (select cond, 0, c), x)
7870 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7871 // (add (select cond, 0, c), x)
7872 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7873 // (sub x, (select cond, 0, c))
7874 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7875 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7876                                    SelectionDAG &DAG, bool AllOnes) {
7877   EVT VT = N->getValueType(0);
7878 
7879   // Skip vectors.
7880   if (VT.isVector())
7881     return SDValue();
7882 
7883   if ((Slct.getOpcode() != ISD::SELECT &&
7884        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7885       !Slct.hasOneUse())
7886     return SDValue();
7887 
7888   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7889     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7890   };
7891 
7892   bool SwapSelectOps;
7893   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7894   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7895   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7896   SDValue NonConstantVal;
7897   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7898     SwapSelectOps = false;
7899     NonConstantVal = FalseVal;
7900   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7901     SwapSelectOps = true;
7902     NonConstantVal = TrueVal;
7903   } else
7904     return SDValue();
7905 
7906   // Slct is now know to be the desired identity constant when CC is true.
7907   TrueVal = OtherOp;
7908   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7909   // Unless SwapSelectOps says the condition should be false.
7910   if (SwapSelectOps)
7911     std::swap(TrueVal, FalseVal);
7912 
7913   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7914     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7915                        {Slct.getOperand(0), Slct.getOperand(1),
7916                         Slct.getOperand(2), TrueVal, FalseVal});
7917 
7918   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7919                      {Slct.getOperand(0), TrueVal, FalseVal});
7920 }
7921 
7922 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7923 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7924                                               bool AllOnes) {
7925   SDValue N0 = N->getOperand(0);
7926   SDValue N1 = N->getOperand(1);
7927   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7928     return Result;
7929   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7930     return Result;
7931   return SDValue();
7932 }
7933 
7934 // Transform (add (mul x, c0), c1) ->
7935 //           (add (mul (add x, c1/c0), c0), c1%c0).
7936 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7937 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7938 // to an infinite loop in DAGCombine if transformed.
7939 // Or transform (add (mul x, c0), c1) ->
7940 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7941 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7942 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7943 // lead to an infinite loop in DAGCombine if transformed.
7944 // Or transform (add (mul x, c0), c1) ->
7945 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7946 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7947 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7948 // lead to an infinite loop in DAGCombine if transformed.
7949 // Or transform (add (mul x, c0), c1) ->
7950 //              (mul (add x, c1/c0), c0).
7951 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7952 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7953                                      const RISCVSubtarget &Subtarget) {
7954   // Skip for vector types and larger types.
7955   EVT VT = N->getValueType(0);
7956   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7957     return SDValue();
7958   // The first operand node must be a MUL and has no other use.
7959   SDValue N0 = N->getOperand(0);
7960   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7961     return SDValue();
7962   // Check if c0 and c1 match above conditions.
7963   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7964   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7965   if (!N0C || !N1C)
7966     return SDValue();
7967   // If N0C has multiple uses it's possible one of the cases in
7968   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7969   // in an infinite loop.
7970   if (!N0C->hasOneUse())
7971     return SDValue();
7972   int64_t C0 = N0C->getSExtValue();
7973   int64_t C1 = N1C->getSExtValue();
7974   int64_t CA, CB;
7975   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7976     return SDValue();
7977   // Search for proper CA (non-zero) and CB that both are simm12.
7978   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7979       !isInt<12>(C0 * (C1 / C0))) {
7980     CA = C1 / C0;
7981     CB = C1 % C0;
7982   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7983              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7984     CA = C1 / C0 + 1;
7985     CB = C1 % C0 - C0;
7986   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7987              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7988     CA = C1 / C0 - 1;
7989     CB = C1 % C0 + C0;
7990   } else
7991     return SDValue();
7992   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7993   SDLoc DL(N);
7994   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7995                              DAG.getConstant(CA, DL, VT));
7996   SDValue New1 =
7997       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7998   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7999 }
8000 
8001 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
8002                                  const RISCVSubtarget &Subtarget) {
8003   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
8004     return V;
8005   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
8006     return V;
8007   if (SDValue V = combineBinOpToReduce(N, DAG))
8008     return V;
8009   // fold (add (select lhs, rhs, cc, 0, y), x) ->
8010   //      (select lhs, rhs, cc, x, (add x, y))
8011   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8012 }
8013 
8014 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
8015   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
8016   //      (select lhs, rhs, cc, x, (sub x, y))
8017   SDValue N0 = N->getOperand(0);
8018   SDValue N1 = N->getOperand(1);
8019   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
8020 }
8021 
8022 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
8023                                  const RISCVSubtarget &Subtarget) {
8024   SDValue N0 = N->getOperand(0);
8025   // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero
8026   // extending X. This is safe since we only need the LSB after the shift and
8027   // shift amounts larger than 31 would produce poison. If we wait until
8028   // type legalization, we'll create RISCVISD::SRLW and we can't recover it
8029   // to use a BEXT instruction.
8030   if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() &&
8031       N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) &&
8032       N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) &&
8033       N0.hasOneUse()) {
8034     SDLoc DL(N);
8035     SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0));
8036     SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1));
8037     SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1);
8038     SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl,
8039                               DAG.getConstant(1, DL, MVT::i64));
8040     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And);
8041   }
8042 
8043   if (SDValue V = combineBinOpToReduce(N, DAG))
8044     return V;
8045 
8046   // fold (and (select lhs, rhs, cc, -1, y), x) ->
8047   //      (select lhs, rhs, cc, x, (and x, y))
8048   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
8049 }
8050 
8051 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
8052                                 const RISCVSubtarget &Subtarget) {
8053   if (Subtarget.hasStdExtZbp()) {
8054     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
8055       return GREV;
8056     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
8057       return GORC;
8058     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
8059       return SHFL;
8060   }
8061 
8062   if (SDValue V = combineBinOpToReduce(N, DAG))
8063     return V;
8064   // fold (or (select cond, 0, y), x) ->
8065   //      (select cond, x, (or x, y))
8066   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8067 }
8068 
8069 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
8070   SDValue N0 = N->getOperand(0);
8071   SDValue N1 = N->getOperand(1);
8072 
8073   // fold (xor (sllw 1, x), -1) -> (rolw ~1, x)
8074   // NOTE: Assumes ROL being legal means ROLW is legal.
8075   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8076   if (N0.getOpcode() == RISCVISD::SLLW &&
8077       isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) &&
8078       TLI.isOperationLegal(ISD::ROTL, MVT::i64)) {
8079     SDLoc DL(N);
8080     return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64,
8081                        DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1));
8082   }
8083 
8084   if (SDValue V = combineBinOpToReduce(N, DAG))
8085     return V;
8086   // fold (xor (select cond, 0, y), x) ->
8087   //      (select cond, x, (xor x, y))
8088   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8089 }
8090 
8091 static SDValue
8092 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
8093                                 const RISCVSubtarget &Subtarget) {
8094   SDValue Src = N->getOperand(0);
8095   EVT VT = N->getValueType(0);
8096 
8097   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
8098   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8099       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
8100     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
8101                        Src.getOperand(0));
8102 
8103   // Fold (i64 (sext_inreg (abs X), i32)) ->
8104   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
8105   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
8106   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
8107   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
8108   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
8109   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
8110   // may get combined into an earlier operation so we need to use
8111   // ComputeNumSignBits.
8112   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
8113   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
8114   // we can't assume that X has 33 sign bits. We must check.
8115   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
8116       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
8117       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
8118       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
8119     SDLoc DL(N);
8120     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
8121     SDValue Neg =
8122         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
8123     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
8124                       DAG.getValueType(MVT::i32));
8125     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
8126   }
8127 
8128   return SDValue();
8129 }
8130 
8131 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
8132 // vwadd(u).vv/vx or vwsub(u).vv/vx.
8133 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
8134                                              bool Commute = false) {
8135   assert((N->getOpcode() == RISCVISD::ADD_VL ||
8136           N->getOpcode() == RISCVISD::SUB_VL) &&
8137          "Unexpected opcode");
8138   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
8139   SDValue Op0 = N->getOperand(0);
8140   SDValue Op1 = N->getOperand(1);
8141   if (Commute)
8142     std::swap(Op0, Op1);
8143 
8144   MVT VT = N->getSimpleValueType(0);
8145 
8146   // Determine the narrow size for a widening add/sub.
8147   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8148   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8149                                   VT.getVectorElementCount());
8150 
8151   SDValue Mask = N->getOperand(2);
8152   SDValue VL = N->getOperand(3);
8153 
8154   SDLoc DL(N);
8155 
8156   // If the RHS is a sext or zext, we can form a widening op.
8157   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
8158        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
8159       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
8160     unsigned ExtOpc = Op1.getOpcode();
8161     Op1 = Op1.getOperand(0);
8162     // Re-introduce narrower extends if needed.
8163     if (Op1.getValueType() != NarrowVT)
8164       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8165 
8166     unsigned WOpc;
8167     if (ExtOpc == RISCVISD::VSEXT_VL)
8168       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
8169     else
8170       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
8171 
8172     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
8173   }
8174 
8175   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
8176   // sext/zext?
8177 
8178   return SDValue();
8179 }
8180 
8181 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
8182 // vwsub(u).vv/vx.
8183 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
8184   SDValue Op0 = N->getOperand(0);
8185   SDValue Op1 = N->getOperand(1);
8186   SDValue Mask = N->getOperand(2);
8187   SDValue VL = N->getOperand(3);
8188 
8189   MVT VT = N->getSimpleValueType(0);
8190   MVT NarrowVT = Op1.getSimpleValueType();
8191   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
8192 
8193   unsigned VOpc;
8194   switch (N->getOpcode()) {
8195   default: llvm_unreachable("Unexpected opcode");
8196   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
8197   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
8198   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
8199   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
8200   }
8201 
8202   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8203                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
8204 
8205   SDLoc DL(N);
8206 
8207   // If the LHS is a sext or zext, we can narrow this op to the same size as
8208   // the RHS.
8209   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
8210        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
8211       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
8212     unsigned ExtOpc = Op0.getOpcode();
8213     Op0 = Op0.getOperand(0);
8214     // Re-introduce narrower extends if needed.
8215     if (Op0.getValueType() != NarrowVT)
8216       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8217     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
8218   }
8219 
8220   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8221                N->getOpcode() == RISCVISD::VWADDU_W_VL;
8222 
8223   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
8224   // to commute and use a vwadd(u).vx instead.
8225   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
8226       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
8227     Op0 = Op0.getOperand(1);
8228 
8229     // See if have enough sign bits or zero bits in the scalar to use a
8230     // widening add/sub by splatting to smaller element size.
8231     unsigned EltBits = VT.getScalarSizeInBits();
8232     unsigned ScalarBits = Op0.getValueSizeInBits();
8233     // Make sure we're getting all element bits from the scalar register.
8234     // FIXME: Support implicit sign extension of vmv.v.x?
8235     if (ScalarBits < EltBits)
8236       return SDValue();
8237 
8238     if (IsSigned) {
8239       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
8240         return SDValue();
8241     } else {
8242       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8243       if (!DAG.MaskedValueIsZero(Op0, Mask))
8244         return SDValue();
8245     }
8246 
8247     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8248                       DAG.getUNDEF(NarrowVT), Op0, VL);
8249     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
8250   }
8251 
8252   return SDValue();
8253 }
8254 
8255 // Try to form VWMUL, VWMULU or VWMULSU.
8256 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
8257 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
8258                                        bool Commute) {
8259   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
8260   SDValue Op0 = N->getOperand(0);
8261   SDValue Op1 = N->getOperand(1);
8262   if (Commute)
8263     std::swap(Op0, Op1);
8264 
8265   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
8266   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
8267   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
8268   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
8269     return SDValue();
8270 
8271   SDValue Mask = N->getOperand(2);
8272   SDValue VL = N->getOperand(3);
8273 
8274   // Make sure the mask and VL match.
8275   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8276     return SDValue();
8277 
8278   MVT VT = N->getSimpleValueType(0);
8279 
8280   // Determine the narrow size for a widening multiply.
8281   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8282   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8283                                   VT.getVectorElementCount());
8284 
8285   SDLoc DL(N);
8286 
8287   // See if the other operand is the same opcode.
8288   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8289     if (!Op1.hasOneUse())
8290       return SDValue();
8291 
8292     // Make sure the mask and VL match.
8293     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8294       return SDValue();
8295 
8296     Op1 = Op1.getOperand(0);
8297   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8298     // The operand is a splat of a scalar.
8299 
8300     // The pasthru must be undef for tail agnostic
8301     if (!Op1.getOperand(0).isUndef())
8302       return SDValue();
8303     // The VL must be the same.
8304     if (Op1.getOperand(2) != VL)
8305       return SDValue();
8306 
8307     // Get the scalar value.
8308     Op1 = Op1.getOperand(1);
8309 
8310     // See if have enough sign bits or zero bits in the scalar to use a
8311     // widening multiply by splatting to smaller element size.
8312     unsigned EltBits = VT.getScalarSizeInBits();
8313     unsigned ScalarBits = Op1.getValueSizeInBits();
8314     // Make sure we're getting all element bits from the scalar register.
8315     // FIXME: Support implicit sign extension of vmv.v.x?
8316     if (ScalarBits < EltBits)
8317       return SDValue();
8318 
8319     // If the LHS is a sign extend, try to use vwmul.
8320     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8321       // Can use vwmul.
8322     } else {
8323       // Otherwise try to use vwmulu or vwmulsu.
8324       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8325       if (DAG.MaskedValueIsZero(Op1, Mask))
8326         IsVWMULSU = IsSignExt;
8327       else
8328         return SDValue();
8329     }
8330 
8331     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8332                       DAG.getUNDEF(NarrowVT), Op1, VL);
8333   } else
8334     return SDValue();
8335 
8336   Op0 = Op0.getOperand(0);
8337 
8338   // Re-introduce narrower extends if needed.
8339   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8340   if (Op0.getValueType() != NarrowVT)
8341     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8342   // vwmulsu requires second operand to be zero extended.
8343   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8344   if (Op1.getValueType() != NarrowVT)
8345     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8346 
8347   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8348   if (!IsVWMULSU)
8349     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8350   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8351 }
8352 
8353 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8354   switch (Op.getOpcode()) {
8355   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8356   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8357   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8358   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8359   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8360   }
8361 
8362   return RISCVFPRndMode::Invalid;
8363 }
8364 
8365 // Fold
8366 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8367 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8368 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8369 //   (fp_to_int (fceil X))      -> fcvt X, rup
8370 //   (fp_to_int (fround X))     -> fcvt X, rmm
8371 static SDValue performFP_TO_INTCombine(SDNode *N,
8372                                        TargetLowering::DAGCombinerInfo &DCI,
8373                                        const RISCVSubtarget &Subtarget) {
8374   SelectionDAG &DAG = DCI.DAG;
8375   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8376   MVT XLenVT = Subtarget.getXLenVT();
8377 
8378   // Only handle XLen or i32 types. Other types narrower than XLen will
8379   // eventually be legalized to XLenVT.
8380   EVT VT = N->getValueType(0);
8381   if (VT != MVT::i32 && VT != XLenVT)
8382     return SDValue();
8383 
8384   SDValue Src = N->getOperand(0);
8385 
8386   // Ensure the FP type is also legal.
8387   if (!TLI.isTypeLegal(Src.getValueType()))
8388     return SDValue();
8389 
8390   // Don't do this for f16 with Zfhmin and not Zfh.
8391   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8392     return SDValue();
8393 
8394   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8395   if (FRM == RISCVFPRndMode::Invalid)
8396     return SDValue();
8397 
8398   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8399 
8400   unsigned Opc;
8401   if (VT == XLenVT)
8402     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8403   else
8404     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8405 
8406   SDLoc DL(N);
8407   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8408                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8409   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8410 }
8411 
8412 // Fold
8413 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8414 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8415 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8416 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8417 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8418 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8419                                        TargetLowering::DAGCombinerInfo &DCI,
8420                                        const RISCVSubtarget &Subtarget) {
8421   SelectionDAG &DAG = DCI.DAG;
8422   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8423   MVT XLenVT = Subtarget.getXLenVT();
8424 
8425   // Only handle XLen types. Other types narrower than XLen will eventually be
8426   // legalized to XLenVT.
8427   EVT DstVT = N->getValueType(0);
8428   if (DstVT != XLenVT)
8429     return SDValue();
8430 
8431   SDValue Src = N->getOperand(0);
8432 
8433   // Ensure the FP type is also legal.
8434   if (!TLI.isTypeLegal(Src.getValueType()))
8435     return SDValue();
8436 
8437   // Don't do this for f16 with Zfhmin and not Zfh.
8438   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8439     return SDValue();
8440 
8441   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8442 
8443   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8444   if (FRM == RISCVFPRndMode::Invalid)
8445     return SDValue();
8446 
8447   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8448 
8449   unsigned Opc;
8450   if (SatVT == DstVT)
8451     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8452   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8453     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8454   else
8455     return SDValue();
8456   // FIXME: Support other SatVTs by clamping before or after the conversion.
8457 
8458   Src = Src.getOperand(0);
8459 
8460   SDLoc DL(N);
8461   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8462                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8463 
8464   // RISCV FP-to-int conversions saturate to the destination register size, but
8465   // don't produce 0 for nan.
8466   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8467   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8468 }
8469 
8470 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8471 // smaller than XLenVT.
8472 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8473                                         const RISCVSubtarget &Subtarget) {
8474   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8475 
8476   SDValue Src = N->getOperand(0);
8477   if (Src.getOpcode() != ISD::BSWAP)
8478     return SDValue();
8479 
8480   EVT VT = N->getValueType(0);
8481   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8482       !isPowerOf2_32(VT.getSizeInBits()))
8483     return SDValue();
8484 
8485   SDLoc DL(N);
8486   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8487                      DAG.getConstant(7, DL, VT));
8488 }
8489 
8490 // Convert from one FMA opcode to another based on whether we are negating the
8491 // multiply result and/or the accumulator.
8492 // NOTE: Only supports RVV operations with VL.
8493 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) {
8494   assert((NegMul || NegAcc) && "Not negating anything?");
8495 
8496   // Negating the multiply result changes ADD<->SUB and toggles 'N'.
8497   if (NegMul) {
8498     // clang-format off
8499     switch (Opcode) {
8500     default: llvm_unreachable("Unexpected opcode");
8501     case RISCVISD::VFMADD_VL:  Opcode = RISCVISD::VFNMSUB_VL; break;
8502     case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFMADD_VL;  break;
8503     case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFMSUB_VL;  break;
8504     case RISCVISD::VFMSUB_VL:  Opcode = RISCVISD::VFNMADD_VL; break;
8505     }
8506     // clang-format on
8507   }
8508 
8509   // Negating the accumulator changes ADD<->SUB.
8510   if (NegAcc) {
8511     // clang-format off
8512     switch (Opcode) {
8513     default: llvm_unreachable("Unexpected opcode");
8514     case RISCVISD::VFMADD_VL:  Opcode = RISCVISD::VFMSUB_VL;  break;
8515     case RISCVISD::VFMSUB_VL:  Opcode = RISCVISD::VFMADD_VL;  break;
8516     case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break;
8517     case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break;
8518     }
8519     // clang-format on
8520   }
8521 
8522   return Opcode;
8523 }
8524 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8525                                                DAGCombinerInfo &DCI) const {
8526   SelectionDAG &DAG = DCI.DAG;
8527 
8528   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8529   // bits are demanded. N will be added to the Worklist if it was not deleted.
8530   // Caller should return SDValue(N, 0) if this returns true.
8531   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8532     SDValue Op = N->getOperand(OpNo);
8533     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8534     if (!SimplifyDemandedBits(Op, Mask, DCI))
8535       return false;
8536 
8537     if (N->getOpcode() != ISD::DELETED_NODE)
8538       DCI.AddToWorklist(N);
8539     return true;
8540   };
8541 
8542   switch (N->getOpcode()) {
8543   default:
8544     break;
8545   case RISCVISD::SplitF64: {
8546     SDValue Op0 = N->getOperand(0);
8547     // If the input to SplitF64 is just BuildPairF64 then the operation is
8548     // redundant. Instead, use BuildPairF64's operands directly.
8549     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8550       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8551 
8552     if (Op0->isUndef()) {
8553       SDValue Lo = DAG.getUNDEF(MVT::i32);
8554       SDValue Hi = DAG.getUNDEF(MVT::i32);
8555       return DCI.CombineTo(N, Lo, Hi);
8556     }
8557 
8558     SDLoc DL(N);
8559 
8560     // It's cheaper to materialise two 32-bit integers than to load a double
8561     // from the constant pool and transfer it to integer registers through the
8562     // stack.
8563     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8564       APInt V = C->getValueAPF().bitcastToAPInt();
8565       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8566       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8567       return DCI.CombineTo(N, Lo, Hi);
8568     }
8569 
8570     // This is a target-specific version of a DAGCombine performed in
8571     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8572     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8573     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8574     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8575         !Op0.getNode()->hasOneUse())
8576       break;
8577     SDValue NewSplitF64 =
8578         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8579                     Op0.getOperand(0));
8580     SDValue Lo = NewSplitF64.getValue(0);
8581     SDValue Hi = NewSplitF64.getValue(1);
8582     APInt SignBit = APInt::getSignMask(32);
8583     if (Op0.getOpcode() == ISD::FNEG) {
8584       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8585                                   DAG.getConstant(SignBit, DL, MVT::i32));
8586       return DCI.CombineTo(N, Lo, NewHi);
8587     }
8588     assert(Op0.getOpcode() == ISD::FABS);
8589     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8590                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8591     return DCI.CombineTo(N, Lo, NewHi);
8592   }
8593   case RISCVISD::SLLW:
8594   case RISCVISD::SRAW:
8595   case RISCVISD::SRLW: {
8596     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8597     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8598         SimplifyDemandedLowBitsHelper(1, 5))
8599       return SDValue(N, 0);
8600 
8601     break;
8602   }
8603   case ISD::ROTR:
8604   case ISD::ROTL:
8605   case RISCVISD::RORW:
8606   case RISCVISD::ROLW: {
8607     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8608       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8609       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8610           SimplifyDemandedLowBitsHelper(1, 5))
8611         return SDValue(N, 0);
8612     }
8613 
8614     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8615   }
8616   case RISCVISD::CLZW:
8617   case RISCVISD::CTZW: {
8618     // Only the lower 32 bits of the first operand are read
8619     if (SimplifyDemandedLowBitsHelper(0, 32))
8620       return SDValue(N, 0);
8621     break;
8622   }
8623   case RISCVISD::GREV:
8624   case RISCVISD::GORC: {
8625     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8626     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8627     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8628     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8629       return SDValue(N, 0);
8630 
8631     return combineGREVI_GORCI(N, DAG);
8632   }
8633   case RISCVISD::GREVW:
8634   case RISCVISD::GORCW: {
8635     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8636     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8637         SimplifyDemandedLowBitsHelper(1, 5))
8638       return SDValue(N, 0);
8639 
8640     break;
8641   }
8642   case RISCVISD::SHFL:
8643   case RISCVISD::UNSHFL: {
8644     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8645     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8646     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8647     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8648       return SDValue(N, 0);
8649 
8650     break;
8651   }
8652   case RISCVISD::SHFLW:
8653   case RISCVISD::UNSHFLW: {
8654     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8655     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8656         SimplifyDemandedLowBitsHelper(1, 4))
8657       return SDValue(N, 0);
8658 
8659     break;
8660   }
8661   case RISCVISD::BCOMPRESSW:
8662   case RISCVISD::BDECOMPRESSW: {
8663     // Only the lower 32 bits of LHS and RHS are read.
8664     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8665         SimplifyDemandedLowBitsHelper(1, 32))
8666       return SDValue(N, 0);
8667 
8668     break;
8669   }
8670   case RISCVISD::FSR:
8671   case RISCVISD::FSL:
8672   case RISCVISD::FSRW:
8673   case RISCVISD::FSLW: {
8674     bool IsWInstruction =
8675         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8676     unsigned BitWidth =
8677         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8678     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8679     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8680     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8681       return SDValue(N, 0);
8682 
8683     break;
8684   }
8685   case RISCVISD::FMV_X_ANYEXTH:
8686   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8687     SDLoc DL(N);
8688     SDValue Op0 = N->getOperand(0);
8689     MVT VT = N->getSimpleValueType(0);
8690     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8691     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8692     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8693     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8694          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8695         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8696          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8697       assert(Op0.getOperand(0).getValueType() == VT &&
8698              "Unexpected value type!");
8699       return Op0.getOperand(0);
8700     }
8701 
8702     // This is a target-specific version of a DAGCombine performed in
8703     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8704     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8705     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8706     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8707         !Op0.getNode()->hasOneUse())
8708       break;
8709     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8710     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8711     APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits());
8712     if (Op0.getOpcode() == ISD::FNEG)
8713       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8714                          DAG.getConstant(SignBit, DL, VT));
8715 
8716     assert(Op0.getOpcode() == ISD::FABS);
8717     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8718                        DAG.getConstant(~SignBit, DL, VT));
8719   }
8720   case ISD::ADD:
8721     return performADDCombine(N, DAG, Subtarget);
8722   case ISD::SUB:
8723     return performSUBCombine(N, DAG);
8724   case ISD::AND:
8725     return performANDCombine(N, DAG, Subtarget);
8726   case ISD::OR:
8727     return performORCombine(N, DAG, Subtarget);
8728   case ISD::XOR:
8729     return performXORCombine(N, DAG);
8730   case ISD::FADD:
8731   case ISD::UMAX:
8732   case ISD::UMIN:
8733   case ISD::SMAX:
8734   case ISD::SMIN:
8735   case ISD::FMAXNUM:
8736   case ISD::FMINNUM:
8737     return combineBinOpToReduce(N, DAG);
8738   case ISD::SIGN_EXTEND_INREG:
8739     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8740   case ISD::ZERO_EXTEND:
8741     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8742     // type legalization. This is safe because fp_to_uint produces poison if
8743     // it overflows.
8744     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8745       SDValue Src = N->getOperand(0);
8746       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8747           isTypeLegal(Src.getOperand(0).getValueType()))
8748         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8749                            Src.getOperand(0));
8750       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8751           isTypeLegal(Src.getOperand(1).getValueType())) {
8752         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8753         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8754                                   Src.getOperand(0), Src.getOperand(1));
8755         DCI.CombineTo(N, Res);
8756         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8757         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8758         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8759       }
8760     }
8761     return SDValue();
8762   case RISCVISD::SELECT_CC: {
8763     // Transform
8764     SDValue LHS = N->getOperand(0);
8765     SDValue RHS = N->getOperand(1);
8766     SDValue TrueV = N->getOperand(3);
8767     SDValue FalseV = N->getOperand(4);
8768 
8769     // If the True and False values are the same, we don't need a select_cc.
8770     if (TrueV == FalseV)
8771       return TrueV;
8772 
8773     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8774     if (!ISD::isIntEqualitySetCC(CCVal))
8775       break;
8776 
8777     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8778     //      (select_cc X, Y, lt, trueV, falseV)
8779     // Sometimes the setcc is introduced after select_cc has been formed.
8780     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8781         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8782       // If we're looking for eq 0 instead of ne 0, we need to invert the
8783       // condition.
8784       bool Invert = CCVal == ISD::SETEQ;
8785       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8786       if (Invert)
8787         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8788 
8789       SDLoc DL(N);
8790       RHS = LHS.getOperand(1);
8791       LHS = LHS.getOperand(0);
8792       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8793 
8794       SDValue TargetCC = DAG.getCondCode(CCVal);
8795       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8796                          {LHS, RHS, TargetCC, TrueV, FalseV});
8797     }
8798 
8799     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8800     //      (select_cc X, Y, eq/ne, trueV, falseV)
8801     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8802       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8803                          {LHS.getOperand(0), LHS.getOperand(1),
8804                           N->getOperand(2), TrueV, FalseV});
8805     // (select_cc X, 1, setne, trueV, falseV) ->
8806     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8807     // This can occur when legalizing some floating point comparisons.
8808     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8809     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8810       SDLoc DL(N);
8811       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8812       SDValue TargetCC = DAG.getCondCode(CCVal);
8813       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8814       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8815                          {LHS, RHS, TargetCC, TrueV, FalseV});
8816     }
8817 
8818     break;
8819   }
8820   case RISCVISD::BR_CC: {
8821     SDValue LHS = N->getOperand(1);
8822     SDValue RHS = N->getOperand(2);
8823     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8824     if (!ISD::isIntEqualitySetCC(CCVal))
8825       break;
8826 
8827     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8828     //      (br_cc X, Y, lt, dest)
8829     // Sometimes the setcc is introduced after br_cc has been formed.
8830     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8831         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8832       // If we're looking for eq 0 instead of ne 0, we need to invert the
8833       // condition.
8834       bool Invert = CCVal == ISD::SETEQ;
8835       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8836       if (Invert)
8837         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8838 
8839       SDLoc DL(N);
8840       RHS = LHS.getOperand(1);
8841       LHS = LHS.getOperand(0);
8842       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8843 
8844       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8845                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8846                          N->getOperand(4));
8847     }
8848 
8849     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8850     //      (br_cc X, Y, eq/ne, trueV, falseV)
8851     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8852       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8853                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8854                          N->getOperand(3), N->getOperand(4));
8855 
8856     // (br_cc X, 1, setne, br_cc) ->
8857     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8858     // This can occur when legalizing some floating point comparisons.
8859     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8860     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8861       SDLoc DL(N);
8862       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8863       SDValue TargetCC = DAG.getCondCode(CCVal);
8864       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8865       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8866                          N->getOperand(0), LHS, RHS, TargetCC,
8867                          N->getOperand(4));
8868     }
8869     break;
8870   }
8871   case ISD::BITREVERSE:
8872     return performBITREVERSECombine(N, DAG, Subtarget);
8873   case ISD::FP_TO_SINT:
8874   case ISD::FP_TO_UINT:
8875     return performFP_TO_INTCombine(N, DCI, Subtarget);
8876   case ISD::FP_TO_SINT_SAT:
8877   case ISD::FP_TO_UINT_SAT:
8878     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8879   case ISD::FCOPYSIGN: {
8880     EVT VT = N->getValueType(0);
8881     if (!VT.isVector())
8882       break;
8883     // There is a form of VFSGNJ which injects the negated sign of its second
8884     // operand. Try and bubble any FNEG up after the extend/round to produce
8885     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8886     // TRUNC=1.
8887     SDValue In2 = N->getOperand(1);
8888     // Avoid cases where the extend/round has multiple uses, as duplicating
8889     // those is typically more expensive than removing a fneg.
8890     if (!In2.hasOneUse())
8891       break;
8892     if (In2.getOpcode() != ISD::FP_EXTEND &&
8893         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8894       break;
8895     In2 = In2.getOperand(0);
8896     if (In2.getOpcode() != ISD::FNEG)
8897       break;
8898     SDLoc DL(N);
8899     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8900     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8901                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8902   }
8903   case ISD::MGATHER:
8904   case ISD::MSCATTER:
8905   case ISD::VP_GATHER:
8906   case ISD::VP_SCATTER: {
8907     if (!DCI.isBeforeLegalize())
8908       break;
8909     SDValue Index, ScaleOp;
8910     bool IsIndexScaled = false;
8911     bool IsIndexSigned = false;
8912     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8913       Index = VPGSN->getIndex();
8914       ScaleOp = VPGSN->getScale();
8915       IsIndexScaled = VPGSN->isIndexScaled();
8916       IsIndexSigned = VPGSN->isIndexSigned();
8917     } else {
8918       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8919       Index = MGSN->getIndex();
8920       ScaleOp = MGSN->getScale();
8921       IsIndexScaled = MGSN->isIndexScaled();
8922       IsIndexSigned = MGSN->isIndexSigned();
8923     }
8924     EVT IndexVT = Index.getValueType();
8925     MVT XLenVT = Subtarget.getXLenVT();
8926     // RISCV indexed loads only support the "unsigned unscaled" addressing
8927     // mode, so anything else must be manually legalized.
8928     bool NeedsIdxLegalization =
8929         IsIndexScaled ||
8930         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8931     if (!NeedsIdxLegalization)
8932       break;
8933 
8934     SDLoc DL(N);
8935 
8936     // Any index legalization should first promote to XLenVT, so we don't lose
8937     // bits when scaling. This may create an illegal index type so we let
8938     // LLVM's legalization take care of the splitting.
8939     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8940     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8941       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8942       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8943                           DL, IndexVT, Index);
8944     }
8945 
8946     if (IsIndexScaled) {
8947       // Manually scale the indices.
8948       // TODO: Sanitize the scale operand here?
8949       // TODO: For VP nodes, should we use VP_SHL here?
8950       unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8951       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8952       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8953       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8954       ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType());
8955     }
8956 
8957     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED;
8958     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8959       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8960                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8961                               ScaleOp, VPGN->getMask(),
8962                               VPGN->getVectorLength()},
8963                              VPGN->getMemOperand(), NewIndexTy);
8964     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8965       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8966                               {VPSN->getChain(), VPSN->getValue(),
8967                                VPSN->getBasePtr(), Index, ScaleOp,
8968                                VPSN->getMask(), VPSN->getVectorLength()},
8969                               VPSN->getMemOperand(), NewIndexTy);
8970     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8971       return DAG.getMaskedGather(
8972           N->getVTList(), MGN->getMemoryVT(), DL,
8973           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8974            MGN->getBasePtr(), Index, ScaleOp},
8975           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8976     const auto *MSN = cast<MaskedScatterSDNode>(N);
8977     return DAG.getMaskedScatter(
8978         N->getVTList(), MSN->getMemoryVT(), DL,
8979         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8980          Index, ScaleOp},
8981         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8982   }
8983   case RISCVISD::SRA_VL:
8984   case RISCVISD::SRL_VL:
8985   case RISCVISD::SHL_VL: {
8986     SDValue ShAmt = N->getOperand(1);
8987     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8988       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8989       SDLoc DL(N);
8990       SDValue VL = N->getOperand(3);
8991       EVT VT = N->getValueType(0);
8992       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8993                           ShAmt.getOperand(1), VL);
8994       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8995                          N->getOperand(2), N->getOperand(3));
8996     }
8997     break;
8998   }
8999   case ISD::SRA:
9000   case ISD::SRL:
9001   case ISD::SHL: {
9002     SDValue ShAmt = N->getOperand(1);
9003     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
9004       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
9005       SDLoc DL(N);
9006       EVT VT = N->getValueType(0);
9007       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
9008                           ShAmt.getOperand(1),
9009                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
9010       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
9011     }
9012     break;
9013   }
9014   case RISCVISD::ADD_VL:
9015     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
9016       return V;
9017     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
9018   case RISCVISD::SUB_VL:
9019     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
9020   case RISCVISD::VWADD_W_VL:
9021   case RISCVISD::VWADDU_W_VL:
9022   case RISCVISD::VWSUB_W_VL:
9023   case RISCVISD::VWSUBU_W_VL:
9024     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
9025   case RISCVISD::MUL_VL:
9026     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
9027       return V;
9028     // Mul is commutative.
9029     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
9030   case RISCVISD::VFMADD_VL:
9031   case RISCVISD::VFNMADD_VL:
9032   case RISCVISD::VFMSUB_VL:
9033   case RISCVISD::VFNMSUB_VL: {
9034     // Fold FNEG_VL into FMA opcodes.
9035     SDValue A = N->getOperand(0);
9036     SDValue B = N->getOperand(1);
9037     SDValue C = N->getOperand(2);
9038     SDValue Mask = N->getOperand(3);
9039     SDValue VL = N->getOperand(4);
9040 
9041     auto invertIfNegative = [&Mask, &VL](SDValue &V) {
9042       if (V.getOpcode() == RISCVISD::FNEG_VL && V.getOperand(1) == Mask &&
9043           V.getOperand(2) == VL) {
9044         // Return the negated input.
9045         V = V.getOperand(0);
9046         return true;
9047       }
9048 
9049       return false;
9050     };
9051 
9052     bool NegA = invertIfNegative(A);
9053     bool NegB = invertIfNegative(B);
9054     bool NegC = invertIfNegative(C);
9055 
9056     // If no operands are negated, we're done.
9057     if (!NegA && !NegB && !NegC)
9058       return SDValue();
9059 
9060     unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC);
9061     return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), A, B, C, Mask,
9062                        VL);
9063   }
9064   case ISD::STORE: {
9065     auto *Store = cast<StoreSDNode>(N);
9066     SDValue Val = Store->getValue();
9067     // Combine store of vmv.x.s to vse with VL of 1.
9068     // FIXME: Support FP.
9069     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
9070       SDValue Src = Val.getOperand(0);
9071       EVT VecVT = Src.getValueType();
9072       EVT MemVT = Store->getMemoryVT();
9073       // The memory VT and the element type must match.
9074       if (VecVT.getVectorElementType() == MemVT) {
9075         SDLoc DL(N);
9076         MVT MaskVT = getMaskTypeFor(VecVT);
9077         return DAG.getStoreVP(
9078             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
9079             DAG.getConstant(1, DL, MaskVT),
9080             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
9081             Store->getMemOperand(), Store->getAddressingMode(),
9082             Store->isTruncatingStore(), /*IsCompress*/ false);
9083       }
9084     }
9085 
9086     break;
9087   }
9088   case ISD::SPLAT_VECTOR: {
9089     EVT VT = N->getValueType(0);
9090     // Only perform this combine on legal MVT types.
9091     if (!isTypeLegal(VT))
9092       break;
9093     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
9094                                          DAG, Subtarget))
9095       return Gather;
9096     break;
9097   }
9098   case RISCVISD::VMV_V_X_VL: {
9099     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
9100     // scalar input.
9101     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
9102     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
9103     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
9104       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
9105         return SDValue(N, 0);
9106 
9107     break;
9108   }
9109   case ISD::INTRINSIC_WO_CHAIN: {
9110     unsigned IntNo = N->getConstantOperandVal(0);
9111     switch (IntNo) {
9112       // By default we do not combine any intrinsic.
9113     default:
9114       return SDValue();
9115     case Intrinsic::riscv_vcpop:
9116     case Intrinsic::riscv_vcpop_mask:
9117     case Intrinsic::riscv_vfirst:
9118     case Intrinsic::riscv_vfirst_mask: {
9119       SDValue VL = N->getOperand(2);
9120       if (IntNo == Intrinsic::riscv_vcpop_mask ||
9121           IntNo == Intrinsic::riscv_vfirst_mask)
9122         VL = N->getOperand(3);
9123       if (!isNullConstant(VL))
9124         return SDValue();
9125       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
9126       SDLoc DL(N);
9127       EVT VT = N->getValueType(0);
9128       if (IntNo == Intrinsic::riscv_vfirst ||
9129           IntNo == Intrinsic::riscv_vfirst_mask)
9130         return DAG.getConstant(-1, DL, VT);
9131       return DAG.getConstant(0, DL, VT);
9132     }
9133     }
9134   }
9135   case ISD::BITCAST: {
9136     assert(Subtarget.useRVVForFixedLengthVectors());
9137     SDValue N0 = N->getOperand(0);
9138     EVT VT = N->getValueType(0);
9139     EVT SrcVT = N0.getValueType();
9140     // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer
9141     // type, widen both sides to avoid a trip through memory.
9142     if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) &&
9143         VT.isScalarInteger()) {
9144       unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
9145       SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
9146       Ops[0] = N0;
9147       SDLoc DL(N);
9148       N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops);
9149       N0 = DAG.getBitcast(MVT::i8, N0);
9150       return DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
9151     }
9152 
9153     return SDValue();
9154   }
9155   }
9156 
9157   return SDValue();
9158 }
9159 
9160 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
9161     const SDNode *N, CombineLevel Level) const {
9162   // The following folds are only desirable if `(OP _, c1 << c2)` can be
9163   // materialised in fewer instructions than `(OP _, c1)`:
9164   //
9165   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
9166   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
9167   SDValue N0 = N->getOperand(0);
9168   EVT Ty = N0.getValueType();
9169   if (Ty.isScalarInteger() &&
9170       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
9171     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9172     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
9173     if (C1 && C2) {
9174       const APInt &C1Int = C1->getAPIntValue();
9175       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
9176 
9177       // We can materialise `c1 << c2` into an add immediate, so it's "free",
9178       // and the combine should happen, to potentially allow further combines
9179       // later.
9180       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
9181           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
9182         return true;
9183 
9184       // We can materialise `c1` in an add immediate, so it's "free", and the
9185       // combine should be prevented.
9186       if (C1Int.getMinSignedBits() <= 64 &&
9187           isLegalAddImmediate(C1Int.getSExtValue()))
9188         return false;
9189 
9190       // Neither constant will fit into an immediate, so find materialisation
9191       // costs.
9192       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
9193                                               Subtarget.getFeatureBits(),
9194                                               /*CompressionCost*/true);
9195       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
9196           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
9197           /*CompressionCost*/true);
9198 
9199       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
9200       // combine should be prevented.
9201       if (C1Cost < ShiftedC1Cost)
9202         return false;
9203     }
9204   }
9205   return true;
9206 }
9207 
9208 bool RISCVTargetLowering::targetShrinkDemandedConstant(
9209     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
9210     TargetLoweringOpt &TLO) const {
9211   // Delay this optimization as late as possible.
9212   if (!TLO.LegalOps)
9213     return false;
9214 
9215   EVT VT = Op.getValueType();
9216   if (VT.isVector())
9217     return false;
9218 
9219   // Only handle AND for now.
9220   if (Op.getOpcode() != ISD::AND)
9221     return false;
9222 
9223   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9224   if (!C)
9225     return false;
9226 
9227   const APInt &Mask = C->getAPIntValue();
9228 
9229   // Clear all non-demanded bits initially.
9230   APInt ShrunkMask = Mask & DemandedBits;
9231 
9232   // Try to make a smaller immediate by setting undemanded bits.
9233 
9234   APInt ExpandedMask = Mask | ~DemandedBits;
9235 
9236   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
9237     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
9238   };
9239   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
9240     if (NewMask == Mask)
9241       return true;
9242     SDLoc DL(Op);
9243     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
9244     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
9245     return TLO.CombineTo(Op, NewOp);
9246   };
9247 
9248   // If the shrunk mask fits in sign extended 12 bits, let the target
9249   // independent code apply it.
9250   if (ShrunkMask.isSignedIntN(12))
9251     return false;
9252 
9253   // Preserve (and X, 0xffff) when zext.h is supported.
9254   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
9255     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
9256     if (IsLegalMask(NewMask))
9257       return UseMask(NewMask);
9258   }
9259 
9260   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
9261   if (VT == MVT::i64) {
9262     APInt NewMask = APInt(64, 0xffffffff);
9263     if (IsLegalMask(NewMask))
9264       return UseMask(NewMask);
9265   }
9266 
9267   // For the remaining optimizations, we need to be able to make a negative
9268   // number through a combination of mask and undemanded bits.
9269   if (!ExpandedMask.isNegative())
9270     return false;
9271 
9272   // What is the fewest number of bits we need to represent the negative number.
9273   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
9274 
9275   // Try to make a 12 bit negative immediate. If that fails try to make a 32
9276   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
9277   APInt NewMask = ShrunkMask;
9278   if (MinSignedBits <= 12)
9279     NewMask.setBitsFrom(11);
9280   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
9281     NewMask.setBitsFrom(31);
9282   else
9283     return false;
9284 
9285   // Check that our new mask is a subset of the demanded mask.
9286   assert(IsLegalMask(NewMask));
9287   return UseMask(NewMask);
9288 }
9289 
9290 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
9291   static const uint64_t GREVMasks[] = {
9292       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
9293       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
9294 
9295   for (unsigned Stage = 0; Stage != 6; ++Stage) {
9296     unsigned Shift = 1 << Stage;
9297     if (ShAmt & Shift) {
9298       uint64_t Mask = GREVMasks[Stage];
9299       uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
9300       if (IsGORC)
9301         Res |= x;
9302       x = Res;
9303     }
9304   }
9305 
9306   return x;
9307 }
9308 
9309 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9310                                                         KnownBits &Known,
9311                                                         const APInt &DemandedElts,
9312                                                         const SelectionDAG &DAG,
9313                                                         unsigned Depth) const {
9314   unsigned BitWidth = Known.getBitWidth();
9315   unsigned Opc = Op.getOpcode();
9316   assert((Opc >= ISD::BUILTIN_OP_END ||
9317           Opc == ISD::INTRINSIC_WO_CHAIN ||
9318           Opc == ISD::INTRINSIC_W_CHAIN ||
9319           Opc == ISD::INTRINSIC_VOID) &&
9320          "Should use MaskedValueIsZero if you don't know whether Op"
9321          " is a target node!");
9322 
9323   Known.resetAll();
9324   switch (Opc) {
9325   default: break;
9326   case RISCVISD::SELECT_CC: {
9327     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
9328     // If we don't know any bits, early out.
9329     if (Known.isUnknown())
9330       break;
9331     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
9332 
9333     // Only known if known in both the LHS and RHS.
9334     Known = KnownBits::commonBits(Known, Known2);
9335     break;
9336   }
9337   case RISCVISD::REMUW: {
9338     KnownBits Known2;
9339     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9340     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9341     // We only care about the lower 32 bits.
9342     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
9343     // Restore the original width by sign extending.
9344     Known = Known.sext(BitWidth);
9345     break;
9346   }
9347   case RISCVISD::DIVUW: {
9348     KnownBits Known2;
9349     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9350     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9351     // We only care about the lower 32 bits.
9352     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
9353     // Restore the original width by sign extending.
9354     Known = Known.sext(BitWidth);
9355     break;
9356   }
9357   case RISCVISD::CTZW: {
9358     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9359     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
9360     unsigned LowBits = Log2_32(PossibleTZ) + 1;
9361     Known.Zero.setBitsFrom(LowBits);
9362     break;
9363   }
9364   case RISCVISD::CLZW: {
9365     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9366     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
9367     unsigned LowBits = Log2_32(PossibleLZ) + 1;
9368     Known.Zero.setBitsFrom(LowBits);
9369     break;
9370   }
9371   case RISCVISD::GREV:
9372   case RISCVISD::GORC: {
9373     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9374       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9375       unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1);
9376       bool IsGORC = Op.getOpcode() == RISCVISD::GORC;
9377       // To compute zeros, we need to invert the value and invert it back after.
9378       Known.Zero =
9379           ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC);
9380       Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC);
9381     }
9382     break;
9383   }
9384   case RISCVISD::READ_VLENB: {
9385     // If we know the minimum VLen from Zvl extensions, we can use that to
9386     // determine the trailing zeros of VLENB.
9387     // FIXME: Limit to 128 bit vectors until we have more testing.
9388     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
9389     if (MinVLenB > 0)
9390       Known.Zero.setLowBits(Log2_32(MinVLenB));
9391     // We assume VLENB is no more than 65536 / 8 bytes.
9392     Known.Zero.setBitsFrom(14);
9393     break;
9394   }
9395   case ISD::INTRINSIC_W_CHAIN:
9396   case ISD::INTRINSIC_WO_CHAIN: {
9397     unsigned IntNo =
9398         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9399     switch (IntNo) {
9400     default:
9401       // We can't do anything for most intrinsics.
9402       break;
9403     case Intrinsic::riscv_vsetvli:
9404     case Intrinsic::riscv_vsetvlimax:
9405     case Intrinsic::riscv_vsetvli_opt:
9406     case Intrinsic::riscv_vsetvlimax_opt:
9407       // Assume that VL output is positive and would fit in an int32_t.
9408       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9409       if (BitWidth >= 32)
9410         Known.Zero.setBitsFrom(31);
9411       break;
9412     }
9413     break;
9414   }
9415   }
9416 }
9417 
9418 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9419     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9420     unsigned Depth) const {
9421   switch (Op.getOpcode()) {
9422   default:
9423     break;
9424   case RISCVISD::SELECT_CC: {
9425     unsigned Tmp =
9426         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9427     if (Tmp == 1) return 1;  // Early out.
9428     unsigned Tmp2 =
9429         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9430     return std::min(Tmp, Tmp2);
9431   }
9432   case RISCVISD::SLLW:
9433   case RISCVISD::SRAW:
9434   case RISCVISD::SRLW:
9435   case RISCVISD::DIVW:
9436   case RISCVISD::DIVUW:
9437   case RISCVISD::REMUW:
9438   case RISCVISD::ROLW:
9439   case RISCVISD::RORW:
9440   case RISCVISD::GREVW:
9441   case RISCVISD::GORCW:
9442   case RISCVISD::FSLW:
9443   case RISCVISD::FSRW:
9444   case RISCVISD::SHFLW:
9445   case RISCVISD::UNSHFLW:
9446   case RISCVISD::BCOMPRESSW:
9447   case RISCVISD::BDECOMPRESSW:
9448   case RISCVISD::BFPW:
9449   case RISCVISD::FCVT_W_RV64:
9450   case RISCVISD::FCVT_WU_RV64:
9451   case RISCVISD::STRICT_FCVT_W_RV64:
9452   case RISCVISD::STRICT_FCVT_WU_RV64:
9453     // TODO: As the result is sign-extended, this is conservatively correct. A
9454     // more precise answer could be calculated for SRAW depending on known
9455     // bits in the shift amount.
9456     return 33;
9457   case RISCVISD::SHFL:
9458   case RISCVISD::UNSHFL: {
9459     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9460     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9461     // will stay within the upper 32 bits. If there were more than 32 sign bits
9462     // before there will be at least 33 sign bits after.
9463     if (Op.getValueType() == MVT::i64 &&
9464         isa<ConstantSDNode>(Op.getOperand(1)) &&
9465         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9466       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9467       if (Tmp > 32)
9468         return 33;
9469     }
9470     break;
9471   }
9472   case RISCVISD::VMV_X_S: {
9473     // The number of sign bits of the scalar result is computed by obtaining the
9474     // element type of the input vector operand, subtracting its width from the
9475     // XLEN, and then adding one (sign bit within the element type). If the
9476     // element type is wider than XLen, the least-significant XLEN bits are
9477     // taken.
9478     unsigned XLen = Subtarget.getXLen();
9479     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9480     if (EltBits <= XLen)
9481       return XLen - EltBits + 1;
9482     break;
9483   }
9484   }
9485 
9486   return 1;
9487 }
9488 
9489 const Constant *
9490 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const {
9491   assert(Ld && "Unexpected null LoadSDNode");
9492   if (!ISD::isNormalLoad(Ld))
9493     return nullptr;
9494 
9495   SDValue Ptr = Ld->getBasePtr();
9496 
9497   // Only constant pools with no offset are supported.
9498   auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * {
9499     auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
9500     if (!CNode || CNode->isMachineConstantPoolEntry() ||
9501         CNode->getOffset() != 0)
9502       return nullptr;
9503 
9504     return CNode;
9505   };
9506 
9507   // Simple case, LLA.
9508   if (Ptr.getOpcode() == RISCVISD::LLA) {
9509     auto *CNode = GetSupportedConstantPool(Ptr);
9510     if (!CNode || CNode->getTargetFlags() != 0)
9511       return nullptr;
9512 
9513     return CNode->getConstVal();
9514   }
9515 
9516   // Look for a HI and ADD_LO pair.
9517   if (Ptr.getOpcode() != RISCVISD::ADD_LO ||
9518       Ptr.getOperand(0).getOpcode() != RISCVISD::HI)
9519     return nullptr;
9520 
9521   auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1));
9522   auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0));
9523 
9524   if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO ||
9525       !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI)
9526     return nullptr;
9527 
9528   if (CNodeLo->getConstVal() != CNodeHi->getConstVal())
9529     return nullptr;
9530 
9531   return CNodeLo->getConstVal();
9532 }
9533 
9534 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9535                                                   MachineBasicBlock *BB) {
9536   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9537 
9538   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9539   // Should the count have wrapped while it was being read, we need to try
9540   // again.
9541   // ...
9542   // read:
9543   // rdcycleh x3 # load high word of cycle
9544   // rdcycle  x2 # load low word of cycle
9545   // rdcycleh x4 # load high word of cycle
9546   // bne x3, x4, read # check if high word reads match, otherwise try again
9547   // ...
9548 
9549   MachineFunction &MF = *BB->getParent();
9550   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9551   MachineFunction::iterator It = ++BB->getIterator();
9552 
9553   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9554   MF.insert(It, LoopMBB);
9555 
9556   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9557   MF.insert(It, DoneMBB);
9558 
9559   // Transfer the remainder of BB and its successor edges to DoneMBB.
9560   DoneMBB->splice(DoneMBB->begin(), BB,
9561                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9562   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9563 
9564   BB->addSuccessor(LoopMBB);
9565 
9566   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9567   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9568   Register LoReg = MI.getOperand(0).getReg();
9569   Register HiReg = MI.getOperand(1).getReg();
9570   DebugLoc DL = MI.getDebugLoc();
9571 
9572   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9573   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9574       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9575       .addReg(RISCV::X0);
9576   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9577       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9578       .addReg(RISCV::X0);
9579   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9580       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9581       .addReg(RISCV::X0);
9582 
9583   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9584       .addReg(HiReg)
9585       .addReg(ReadAgainReg)
9586       .addMBB(LoopMBB);
9587 
9588   LoopMBB->addSuccessor(LoopMBB);
9589   LoopMBB->addSuccessor(DoneMBB);
9590 
9591   MI.eraseFromParent();
9592 
9593   return DoneMBB;
9594 }
9595 
9596 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9597                                              MachineBasicBlock *BB) {
9598   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9599 
9600   MachineFunction &MF = *BB->getParent();
9601   DebugLoc DL = MI.getDebugLoc();
9602   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9603   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9604   Register LoReg = MI.getOperand(0).getReg();
9605   Register HiReg = MI.getOperand(1).getReg();
9606   Register SrcReg = MI.getOperand(2).getReg();
9607   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9608   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9609 
9610   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9611                           RI);
9612   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9613   MachineMemOperand *MMOLo =
9614       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9615   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9616       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9617   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9618       .addFrameIndex(FI)
9619       .addImm(0)
9620       .addMemOperand(MMOLo);
9621   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9622       .addFrameIndex(FI)
9623       .addImm(4)
9624       .addMemOperand(MMOHi);
9625   MI.eraseFromParent(); // The pseudo instruction is gone now.
9626   return BB;
9627 }
9628 
9629 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9630                                                  MachineBasicBlock *BB) {
9631   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9632          "Unexpected instruction");
9633 
9634   MachineFunction &MF = *BB->getParent();
9635   DebugLoc DL = MI.getDebugLoc();
9636   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9637   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9638   Register DstReg = MI.getOperand(0).getReg();
9639   Register LoReg = MI.getOperand(1).getReg();
9640   Register HiReg = MI.getOperand(2).getReg();
9641   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9642   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9643 
9644   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9645   MachineMemOperand *MMOLo =
9646       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9647   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9648       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9649   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9650       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9651       .addFrameIndex(FI)
9652       .addImm(0)
9653       .addMemOperand(MMOLo);
9654   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9655       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9656       .addFrameIndex(FI)
9657       .addImm(4)
9658       .addMemOperand(MMOHi);
9659   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9660   MI.eraseFromParent(); // The pseudo instruction is gone now.
9661   return BB;
9662 }
9663 
9664 static bool isSelectPseudo(MachineInstr &MI) {
9665   switch (MI.getOpcode()) {
9666   default:
9667     return false;
9668   case RISCV::Select_GPR_Using_CC_GPR:
9669   case RISCV::Select_FPR16_Using_CC_GPR:
9670   case RISCV::Select_FPR32_Using_CC_GPR:
9671   case RISCV::Select_FPR64_Using_CC_GPR:
9672     return true;
9673   }
9674 }
9675 
9676 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9677                                         unsigned RelOpcode, unsigned EqOpcode,
9678                                         const RISCVSubtarget &Subtarget) {
9679   DebugLoc DL = MI.getDebugLoc();
9680   Register DstReg = MI.getOperand(0).getReg();
9681   Register Src1Reg = MI.getOperand(1).getReg();
9682   Register Src2Reg = MI.getOperand(2).getReg();
9683   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9684   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9685   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9686 
9687   // Save the current FFLAGS.
9688   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9689 
9690   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9691                  .addReg(Src1Reg)
9692                  .addReg(Src2Reg);
9693   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9694     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9695 
9696   // Restore the FFLAGS.
9697   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9698       .addReg(SavedFFlags, RegState::Kill);
9699 
9700   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9701   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9702                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9703                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9704   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9705     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9706 
9707   // Erase the pseudoinstruction.
9708   MI.eraseFromParent();
9709   return BB;
9710 }
9711 
9712 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9713                                            MachineBasicBlock *BB,
9714                                            const RISCVSubtarget &Subtarget) {
9715   // To "insert" Select_* instructions, we actually have to insert the triangle
9716   // control-flow pattern.  The incoming instructions know the destination vreg
9717   // to set, the condition code register to branch on, the true/false values to
9718   // select between, and the condcode to use to select the appropriate branch.
9719   //
9720   // We produce the following control flow:
9721   //     HeadMBB
9722   //     |  \
9723   //     |  IfFalseMBB
9724   //     | /
9725   //    TailMBB
9726   //
9727   // When we find a sequence of selects we attempt to optimize their emission
9728   // by sharing the control flow. Currently we only handle cases where we have
9729   // multiple selects with the exact same condition (same LHS, RHS and CC).
9730   // The selects may be interleaved with other instructions if the other
9731   // instructions meet some requirements we deem safe:
9732   // - They are debug instructions. Otherwise,
9733   // - They do not have side-effects, do not access memory and their inputs do
9734   //   not depend on the results of the select pseudo-instructions.
9735   // The TrueV/FalseV operands of the selects cannot depend on the result of
9736   // previous selects in the sequence.
9737   // These conditions could be further relaxed. See the X86 target for a
9738   // related approach and more information.
9739   Register LHS = MI.getOperand(1).getReg();
9740   Register RHS = MI.getOperand(2).getReg();
9741   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9742 
9743   SmallVector<MachineInstr *, 4> SelectDebugValues;
9744   SmallSet<Register, 4> SelectDests;
9745   SelectDests.insert(MI.getOperand(0).getReg());
9746 
9747   MachineInstr *LastSelectPseudo = &MI;
9748 
9749   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9750        SequenceMBBI != E; ++SequenceMBBI) {
9751     if (SequenceMBBI->isDebugInstr())
9752       continue;
9753     if (isSelectPseudo(*SequenceMBBI)) {
9754       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9755           SequenceMBBI->getOperand(2).getReg() != RHS ||
9756           SequenceMBBI->getOperand(3).getImm() != CC ||
9757           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9758           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9759         break;
9760       LastSelectPseudo = &*SequenceMBBI;
9761       SequenceMBBI->collectDebugValues(SelectDebugValues);
9762       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9763     } else {
9764       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9765           SequenceMBBI->mayLoadOrStore())
9766         break;
9767       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9768             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9769           }))
9770         break;
9771     }
9772   }
9773 
9774   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9775   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9776   DebugLoc DL = MI.getDebugLoc();
9777   MachineFunction::iterator I = ++BB->getIterator();
9778 
9779   MachineBasicBlock *HeadMBB = BB;
9780   MachineFunction *F = BB->getParent();
9781   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9782   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9783 
9784   F->insert(I, IfFalseMBB);
9785   F->insert(I, TailMBB);
9786 
9787   // Transfer debug instructions associated with the selects to TailMBB.
9788   for (MachineInstr *DebugInstr : SelectDebugValues) {
9789     TailMBB->push_back(DebugInstr->removeFromParent());
9790   }
9791 
9792   // Move all instructions after the sequence to TailMBB.
9793   TailMBB->splice(TailMBB->end(), HeadMBB,
9794                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9795   // Update machine-CFG edges by transferring all successors of the current
9796   // block to the new block which will contain the Phi nodes for the selects.
9797   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9798   // Set the successors for HeadMBB.
9799   HeadMBB->addSuccessor(IfFalseMBB);
9800   HeadMBB->addSuccessor(TailMBB);
9801 
9802   // Insert appropriate branch.
9803   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9804     .addReg(LHS)
9805     .addReg(RHS)
9806     .addMBB(TailMBB);
9807 
9808   // IfFalseMBB just falls through to TailMBB.
9809   IfFalseMBB->addSuccessor(TailMBB);
9810 
9811   // Create PHIs for all of the select pseudo-instructions.
9812   auto SelectMBBI = MI.getIterator();
9813   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9814   auto InsertionPoint = TailMBB->begin();
9815   while (SelectMBBI != SelectEnd) {
9816     auto Next = std::next(SelectMBBI);
9817     if (isSelectPseudo(*SelectMBBI)) {
9818       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9819       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9820               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9821           .addReg(SelectMBBI->getOperand(4).getReg())
9822           .addMBB(HeadMBB)
9823           .addReg(SelectMBBI->getOperand(5).getReg())
9824           .addMBB(IfFalseMBB);
9825       SelectMBBI->eraseFromParent();
9826     }
9827     SelectMBBI = Next;
9828   }
9829 
9830   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9831   return TailMBB;
9832 }
9833 
9834 MachineBasicBlock *
9835 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9836                                                  MachineBasicBlock *BB) const {
9837   switch (MI.getOpcode()) {
9838   default:
9839     llvm_unreachable("Unexpected instr type to insert");
9840   case RISCV::ReadCycleWide:
9841     assert(!Subtarget.is64Bit() &&
9842            "ReadCycleWrite is only to be used on riscv32");
9843     return emitReadCycleWidePseudo(MI, BB);
9844   case RISCV::Select_GPR_Using_CC_GPR:
9845   case RISCV::Select_FPR16_Using_CC_GPR:
9846   case RISCV::Select_FPR32_Using_CC_GPR:
9847   case RISCV::Select_FPR64_Using_CC_GPR:
9848     return emitSelectPseudo(MI, BB, Subtarget);
9849   case RISCV::BuildPairF64Pseudo:
9850     return emitBuildPairF64Pseudo(MI, BB);
9851   case RISCV::SplitF64Pseudo:
9852     return emitSplitF64Pseudo(MI, BB);
9853   case RISCV::PseudoQuietFLE_H:
9854     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9855   case RISCV::PseudoQuietFLT_H:
9856     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9857   case RISCV::PseudoQuietFLE_S:
9858     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9859   case RISCV::PseudoQuietFLT_S:
9860     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9861   case RISCV::PseudoQuietFLE_D:
9862     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9863   case RISCV::PseudoQuietFLT_D:
9864     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9865   }
9866 }
9867 
9868 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9869                                                         SDNode *Node) const {
9870   // Add FRM dependency to any instructions with dynamic rounding mode.
9871   unsigned Opc = MI.getOpcode();
9872   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9873   if (Idx < 0)
9874     return;
9875   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9876     return;
9877   // If the instruction already reads FRM, don't add another read.
9878   if (MI.readsRegister(RISCV::FRM))
9879     return;
9880   MI.addOperand(
9881       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9882 }
9883 
9884 // Calling Convention Implementation.
9885 // The expectations for frontend ABI lowering vary from target to target.
9886 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9887 // details, but this is a longer term goal. For now, we simply try to keep the
9888 // role of the frontend as simple and well-defined as possible. The rules can
9889 // be summarised as:
9890 // * Never split up large scalar arguments. We handle them here.
9891 // * If a hardfloat calling convention is being used, and the struct may be
9892 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9893 // available, then pass as two separate arguments. If either the GPRs or FPRs
9894 // are exhausted, then pass according to the rule below.
9895 // * If a struct could never be passed in registers or directly in a stack
9896 // slot (as it is larger than 2*XLEN and the floating point rules don't
9897 // apply), then pass it using a pointer with the byval attribute.
9898 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9899 // word-sized array or a 2*XLEN scalar (depending on alignment).
9900 // * The frontend can determine whether a struct is returned by reference or
9901 // not based on its size and fields. If it will be returned by reference, the
9902 // frontend must modify the prototype so a pointer with the sret annotation is
9903 // passed as the first argument. This is not necessary for large scalar
9904 // returns.
9905 // * Struct return values and varargs should be coerced to structs containing
9906 // register-size fields in the same situations they would be for fixed
9907 // arguments.
9908 
9909 static const MCPhysReg ArgGPRs[] = {
9910   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9911   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9912 };
9913 static const MCPhysReg ArgFPR16s[] = {
9914   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9915   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9916 };
9917 static const MCPhysReg ArgFPR32s[] = {
9918   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9919   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9920 };
9921 static const MCPhysReg ArgFPR64s[] = {
9922   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9923   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9924 };
9925 // This is an interim calling convention and it may be changed in the future.
9926 static const MCPhysReg ArgVRs[] = {
9927     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9928     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9929     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9930 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9931                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9932                                      RISCV::V20M2, RISCV::V22M2};
9933 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9934                                      RISCV::V20M4};
9935 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9936 
9937 // Pass a 2*XLEN argument that has been split into two XLEN values through
9938 // registers or the stack as necessary.
9939 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9940                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9941                                 MVT ValVT2, MVT LocVT2,
9942                                 ISD::ArgFlagsTy ArgFlags2) {
9943   unsigned XLenInBytes = XLen / 8;
9944   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9945     // At least one half can be passed via register.
9946     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9947                                      VA1.getLocVT(), CCValAssign::Full));
9948   } else {
9949     // Both halves must be passed on the stack, with proper alignment.
9950     Align StackAlign =
9951         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9952     State.addLoc(
9953         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9954                             State.AllocateStack(XLenInBytes, StackAlign),
9955                             VA1.getLocVT(), CCValAssign::Full));
9956     State.addLoc(CCValAssign::getMem(
9957         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9958         LocVT2, CCValAssign::Full));
9959     return false;
9960   }
9961 
9962   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9963     // The second half can also be passed via register.
9964     State.addLoc(
9965         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9966   } else {
9967     // The second half is passed via the stack, without additional alignment.
9968     State.addLoc(CCValAssign::getMem(
9969         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9970         LocVT2, CCValAssign::Full));
9971   }
9972 
9973   return false;
9974 }
9975 
9976 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9977                                Optional<unsigned> FirstMaskArgument,
9978                                CCState &State, const RISCVTargetLowering &TLI) {
9979   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9980   if (RC == &RISCV::VRRegClass) {
9981     // Assign the first mask argument to V0.
9982     // This is an interim calling convention and it may be changed in the
9983     // future.
9984     if (FirstMaskArgument && ValNo == *FirstMaskArgument)
9985       return State.AllocateReg(RISCV::V0);
9986     return State.AllocateReg(ArgVRs);
9987   }
9988   if (RC == &RISCV::VRM2RegClass)
9989     return State.AllocateReg(ArgVRM2s);
9990   if (RC == &RISCV::VRM4RegClass)
9991     return State.AllocateReg(ArgVRM4s);
9992   if (RC == &RISCV::VRM8RegClass)
9993     return State.AllocateReg(ArgVRM8s);
9994   llvm_unreachable("Unhandled register class for ValueType");
9995 }
9996 
9997 // Implements the RISC-V calling convention. Returns true upon failure.
9998 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9999                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
10000                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
10001                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
10002                      Optional<unsigned> FirstMaskArgument) {
10003   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
10004   assert(XLen == 32 || XLen == 64);
10005   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
10006 
10007   // Any return value split in to more than two values can't be returned
10008   // directly. Vectors are returned via the available vector registers.
10009   if (!LocVT.isVector() && IsRet && ValNo > 1)
10010     return true;
10011 
10012   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
10013   // variadic argument, or if no F16/F32 argument registers are available.
10014   bool UseGPRForF16_F32 = true;
10015   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
10016   // variadic argument, or if no F64 argument registers are available.
10017   bool UseGPRForF64 = true;
10018 
10019   switch (ABI) {
10020   default:
10021     llvm_unreachable("Unexpected ABI");
10022   case RISCVABI::ABI_ILP32:
10023   case RISCVABI::ABI_LP64:
10024     break;
10025   case RISCVABI::ABI_ILP32F:
10026   case RISCVABI::ABI_LP64F:
10027     UseGPRForF16_F32 = !IsFixed;
10028     break;
10029   case RISCVABI::ABI_ILP32D:
10030   case RISCVABI::ABI_LP64D:
10031     UseGPRForF16_F32 = !IsFixed;
10032     UseGPRForF64 = !IsFixed;
10033     break;
10034   }
10035 
10036   // FPR16, FPR32, and FPR64 alias each other.
10037   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
10038     UseGPRForF16_F32 = true;
10039     UseGPRForF64 = true;
10040   }
10041 
10042   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
10043   // similar local variables rather than directly checking against the target
10044   // ABI.
10045 
10046   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
10047     LocVT = XLenVT;
10048     LocInfo = CCValAssign::BCvt;
10049   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
10050     LocVT = MVT::i64;
10051     LocInfo = CCValAssign::BCvt;
10052   }
10053 
10054   // If this is a variadic argument, the RISC-V calling convention requires
10055   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
10056   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
10057   // be used regardless of whether the original argument was split during
10058   // legalisation or not. The argument will not be passed by registers if the
10059   // original type is larger than 2*XLEN, so the register alignment rule does
10060   // not apply.
10061   unsigned TwoXLenInBytes = (2 * XLen) / 8;
10062   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
10063       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
10064     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
10065     // Skip 'odd' register if necessary.
10066     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
10067       State.AllocateReg(ArgGPRs);
10068   }
10069 
10070   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
10071   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
10072       State.getPendingArgFlags();
10073 
10074   assert(PendingLocs.size() == PendingArgFlags.size() &&
10075          "PendingLocs and PendingArgFlags out of sync");
10076 
10077   // Handle passing f64 on RV32D with a soft float ABI or when floating point
10078   // registers are exhausted.
10079   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
10080     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
10081            "Can't lower f64 if it is split");
10082     // Depending on available argument GPRS, f64 may be passed in a pair of
10083     // GPRs, split between a GPR and the stack, or passed completely on the
10084     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
10085     // cases.
10086     Register Reg = State.AllocateReg(ArgGPRs);
10087     LocVT = MVT::i32;
10088     if (!Reg) {
10089       unsigned StackOffset = State.AllocateStack(8, Align(8));
10090       State.addLoc(
10091           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10092       return false;
10093     }
10094     if (!State.AllocateReg(ArgGPRs))
10095       State.AllocateStack(4, Align(4));
10096     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10097     return false;
10098   }
10099 
10100   // Fixed-length vectors are located in the corresponding scalable-vector
10101   // container types.
10102   if (ValVT.isFixedLengthVector())
10103     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10104 
10105   // Split arguments might be passed indirectly, so keep track of the pending
10106   // values. Split vectors are passed via a mix of registers and indirectly, so
10107   // treat them as we would any other argument.
10108   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
10109     LocVT = XLenVT;
10110     LocInfo = CCValAssign::Indirect;
10111     PendingLocs.push_back(
10112         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
10113     PendingArgFlags.push_back(ArgFlags);
10114     if (!ArgFlags.isSplitEnd()) {
10115       return false;
10116     }
10117   }
10118 
10119   // If the split argument only had two elements, it should be passed directly
10120   // in registers or on the stack.
10121   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
10122       PendingLocs.size() <= 2) {
10123     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
10124     // Apply the normal calling convention rules to the first half of the
10125     // split argument.
10126     CCValAssign VA = PendingLocs[0];
10127     ISD::ArgFlagsTy AF = PendingArgFlags[0];
10128     PendingLocs.clear();
10129     PendingArgFlags.clear();
10130     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
10131                                ArgFlags);
10132   }
10133 
10134   // Allocate to a register if possible, or else a stack slot.
10135   Register Reg;
10136   unsigned StoreSizeBytes = XLen / 8;
10137   Align StackAlign = Align(XLen / 8);
10138 
10139   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
10140     Reg = State.AllocateReg(ArgFPR16s);
10141   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
10142     Reg = State.AllocateReg(ArgFPR32s);
10143   else if (ValVT == MVT::f64 && !UseGPRForF64)
10144     Reg = State.AllocateReg(ArgFPR64s);
10145   else if (ValVT.isVector()) {
10146     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
10147     if (!Reg) {
10148       // For return values, the vector must be passed fully via registers or
10149       // via the stack.
10150       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
10151       // but we're using all of them.
10152       if (IsRet)
10153         return true;
10154       // Try using a GPR to pass the address
10155       if ((Reg = State.AllocateReg(ArgGPRs))) {
10156         LocVT = XLenVT;
10157         LocInfo = CCValAssign::Indirect;
10158       } else if (ValVT.isScalableVector()) {
10159         LocVT = XLenVT;
10160         LocInfo = CCValAssign::Indirect;
10161       } else {
10162         // Pass fixed-length vectors on the stack.
10163         LocVT = ValVT;
10164         StoreSizeBytes = ValVT.getStoreSize();
10165         // Align vectors to their element sizes, being careful for vXi1
10166         // vectors.
10167         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10168       }
10169     }
10170   } else {
10171     Reg = State.AllocateReg(ArgGPRs);
10172   }
10173 
10174   unsigned StackOffset =
10175       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
10176 
10177   // If we reach this point and PendingLocs is non-empty, we must be at the
10178   // end of a split argument that must be passed indirectly.
10179   if (!PendingLocs.empty()) {
10180     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
10181     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
10182 
10183     for (auto &It : PendingLocs) {
10184       if (Reg)
10185         It.convertToReg(Reg);
10186       else
10187         It.convertToMem(StackOffset);
10188       State.addLoc(It);
10189     }
10190     PendingLocs.clear();
10191     PendingArgFlags.clear();
10192     return false;
10193   }
10194 
10195   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
10196           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
10197          "Expected an XLenVT or vector types at this stage");
10198 
10199   if (Reg) {
10200     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10201     return false;
10202   }
10203 
10204   // When a floating-point value is passed on the stack, no bit-conversion is
10205   // needed.
10206   if (ValVT.isFloatingPoint()) {
10207     LocVT = ValVT;
10208     LocInfo = CCValAssign::Full;
10209   }
10210   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10211   return false;
10212 }
10213 
10214 template <typename ArgTy>
10215 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
10216   for (const auto &ArgIdx : enumerate(Args)) {
10217     MVT ArgVT = ArgIdx.value().VT;
10218     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
10219       return ArgIdx.index();
10220   }
10221   return None;
10222 }
10223 
10224 void RISCVTargetLowering::analyzeInputArgs(
10225     MachineFunction &MF, CCState &CCInfo,
10226     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
10227     RISCVCCAssignFn Fn) const {
10228   unsigned NumArgs = Ins.size();
10229   FunctionType *FType = MF.getFunction().getFunctionType();
10230 
10231   Optional<unsigned> FirstMaskArgument;
10232   if (Subtarget.hasVInstructions())
10233     FirstMaskArgument = preAssignMask(Ins);
10234 
10235   for (unsigned i = 0; i != NumArgs; ++i) {
10236     MVT ArgVT = Ins[i].VT;
10237     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
10238 
10239     Type *ArgTy = nullptr;
10240     if (IsRet)
10241       ArgTy = FType->getReturnType();
10242     else if (Ins[i].isOrigArg())
10243       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
10244 
10245     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10246     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10247            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
10248            FirstMaskArgument)) {
10249       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
10250                         << EVT(ArgVT).getEVTString() << '\n');
10251       llvm_unreachable(nullptr);
10252     }
10253   }
10254 }
10255 
10256 void RISCVTargetLowering::analyzeOutputArgs(
10257     MachineFunction &MF, CCState &CCInfo,
10258     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
10259     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
10260   unsigned NumArgs = Outs.size();
10261 
10262   Optional<unsigned> FirstMaskArgument;
10263   if (Subtarget.hasVInstructions())
10264     FirstMaskArgument = preAssignMask(Outs);
10265 
10266   for (unsigned i = 0; i != NumArgs; i++) {
10267     MVT ArgVT = Outs[i].VT;
10268     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10269     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
10270 
10271     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10272     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10273            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
10274            FirstMaskArgument)) {
10275       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
10276                         << EVT(ArgVT).getEVTString() << "\n");
10277       llvm_unreachable(nullptr);
10278     }
10279   }
10280 }
10281 
10282 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
10283 // values.
10284 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
10285                                    const CCValAssign &VA, const SDLoc &DL,
10286                                    const RISCVSubtarget &Subtarget) {
10287   switch (VA.getLocInfo()) {
10288   default:
10289     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10290   case CCValAssign::Full:
10291     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
10292       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
10293     break;
10294   case CCValAssign::BCvt:
10295     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10296       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
10297     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10298       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
10299     else
10300       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
10301     break;
10302   }
10303   return Val;
10304 }
10305 
10306 // The caller is responsible for loading the full value if the argument is
10307 // passed with CCValAssign::Indirect.
10308 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
10309                                 const CCValAssign &VA, const SDLoc &DL,
10310                                 const RISCVTargetLowering &TLI) {
10311   MachineFunction &MF = DAG.getMachineFunction();
10312   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10313   EVT LocVT = VA.getLocVT();
10314   SDValue Val;
10315   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
10316   Register VReg = RegInfo.createVirtualRegister(RC);
10317   RegInfo.addLiveIn(VA.getLocReg(), VReg);
10318   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
10319 
10320   if (VA.getLocInfo() == CCValAssign::Indirect)
10321     return Val;
10322 
10323   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
10324 }
10325 
10326 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
10327                                    const CCValAssign &VA, const SDLoc &DL,
10328                                    const RISCVSubtarget &Subtarget) {
10329   EVT LocVT = VA.getLocVT();
10330 
10331   switch (VA.getLocInfo()) {
10332   default:
10333     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10334   case CCValAssign::Full:
10335     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
10336       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
10337     break;
10338   case CCValAssign::BCvt:
10339     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10340       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
10341     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10342       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
10343     else
10344       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
10345     break;
10346   }
10347   return Val;
10348 }
10349 
10350 // The caller is responsible for loading the full value if the argument is
10351 // passed with CCValAssign::Indirect.
10352 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
10353                                 const CCValAssign &VA, const SDLoc &DL) {
10354   MachineFunction &MF = DAG.getMachineFunction();
10355   MachineFrameInfo &MFI = MF.getFrameInfo();
10356   EVT LocVT = VA.getLocVT();
10357   EVT ValVT = VA.getValVT();
10358   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
10359   if (ValVT.isScalableVector()) {
10360     // When the value is a scalable vector, we save the pointer which points to
10361     // the scalable vector value in the stack. The ValVT will be the pointer
10362     // type, instead of the scalable vector type.
10363     ValVT = LocVT;
10364   }
10365   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
10366                                  /*IsImmutable=*/true);
10367   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
10368   SDValue Val;
10369 
10370   ISD::LoadExtType ExtType;
10371   switch (VA.getLocInfo()) {
10372   default:
10373     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10374   case CCValAssign::Full:
10375   case CCValAssign::Indirect:
10376   case CCValAssign::BCvt:
10377     ExtType = ISD::NON_EXTLOAD;
10378     break;
10379   }
10380   Val = DAG.getExtLoad(
10381       ExtType, DL, LocVT, Chain, FIN,
10382       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
10383   return Val;
10384 }
10385 
10386 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
10387                                        const CCValAssign &VA, const SDLoc &DL) {
10388   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
10389          "Unexpected VA");
10390   MachineFunction &MF = DAG.getMachineFunction();
10391   MachineFrameInfo &MFI = MF.getFrameInfo();
10392   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10393 
10394   if (VA.isMemLoc()) {
10395     // f64 is passed on the stack.
10396     int FI =
10397         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
10398     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10399     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
10400                        MachinePointerInfo::getFixedStack(MF, FI));
10401   }
10402 
10403   assert(VA.isRegLoc() && "Expected register VA assignment");
10404 
10405   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10406   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
10407   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
10408   SDValue Hi;
10409   if (VA.getLocReg() == RISCV::X17) {
10410     // Second half of f64 is passed on the stack.
10411     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
10412     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10413     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10414                      MachinePointerInfo::getFixedStack(MF, FI));
10415   } else {
10416     // Second half of f64 is passed in another GPR.
10417     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10418     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10419     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10420   }
10421   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10422 }
10423 
10424 // FastCC has less than 1% performance improvement for some particular
10425 // benchmark. But theoretically, it may has benenfit for some cases.
10426 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10427                             unsigned ValNo, MVT ValVT, MVT LocVT,
10428                             CCValAssign::LocInfo LocInfo,
10429                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10430                             bool IsFixed, bool IsRet, Type *OrigTy,
10431                             const RISCVTargetLowering &TLI,
10432                             Optional<unsigned> FirstMaskArgument) {
10433 
10434   // X5 and X6 might be used for save-restore libcall.
10435   static const MCPhysReg GPRList[] = {
10436       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10437       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10438       RISCV::X29, RISCV::X30, RISCV::X31};
10439 
10440   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10441     if (unsigned Reg = State.AllocateReg(GPRList)) {
10442       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10443       return false;
10444     }
10445   }
10446 
10447   if (LocVT == MVT::f16) {
10448     static const MCPhysReg FPR16List[] = {
10449         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10450         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10451         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10452         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10453     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10454       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10455       return false;
10456     }
10457   }
10458 
10459   if (LocVT == MVT::f32) {
10460     static const MCPhysReg FPR32List[] = {
10461         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10462         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10463         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10464         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10465     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10466       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10467       return false;
10468     }
10469   }
10470 
10471   if (LocVT == MVT::f64) {
10472     static const MCPhysReg FPR64List[] = {
10473         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10474         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10475         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10476         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10477     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10478       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10479       return false;
10480     }
10481   }
10482 
10483   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10484     unsigned Offset4 = State.AllocateStack(4, Align(4));
10485     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10486     return false;
10487   }
10488 
10489   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10490     unsigned Offset5 = State.AllocateStack(8, Align(8));
10491     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10492     return false;
10493   }
10494 
10495   if (LocVT.isVector()) {
10496     if (unsigned Reg =
10497             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10498       // Fixed-length vectors are located in the corresponding scalable-vector
10499       // container types.
10500       if (ValVT.isFixedLengthVector())
10501         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10502       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10503     } else {
10504       // Try and pass the address via a "fast" GPR.
10505       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10506         LocInfo = CCValAssign::Indirect;
10507         LocVT = TLI.getSubtarget().getXLenVT();
10508         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10509       } else if (ValVT.isFixedLengthVector()) {
10510         auto StackAlign =
10511             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10512         unsigned StackOffset =
10513             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10514         State.addLoc(
10515             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10516       } else {
10517         // Can't pass scalable vectors on the stack.
10518         return true;
10519       }
10520     }
10521 
10522     return false;
10523   }
10524 
10525   return true; // CC didn't match.
10526 }
10527 
10528 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10529                          CCValAssign::LocInfo LocInfo,
10530                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10531 
10532   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10533     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10534     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10535     static const MCPhysReg GPRList[] = {
10536         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10537         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10538     if (unsigned Reg = State.AllocateReg(GPRList)) {
10539       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10540       return false;
10541     }
10542   }
10543 
10544   if (LocVT == MVT::f32) {
10545     // Pass in STG registers: F1, ..., F6
10546     //                        fs0 ... fs5
10547     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10548                                           RISCV::F18_F, RISCV::F19_F,
10549                                           RISCV::F20_F, RISCV::F21_F};
10550     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10551       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10552       return false;
10553     }
10554   }
10555 
10556   if (LocVT == MVT::f64) {
10557     // Pass in STG registers: D1, ..., D6
10558     //                        fs6 ... fs11
10559     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10560                                           RISCV::F24_D, RISCV::F25_D,
10561                                           RISCV::F26_D, RISCV::F27_D};
10562     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10563       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10564       return false;
10565     }
10566   }
10567 
10568   report_fatal_error("No registers left in GHC calling convention");
10569   return true;
10570 }
10571 
10572 // Transform physical registers into virtual registers.
10573 SDValue RISCVTargetLowering::LowerFormalArguments(
10574     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10575     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10576     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10577 
10578   MachineFunction &MF = DAG.getMachineFunction();
10579 
10580   switch (CallConv) {
10581   default:
10582     report_fatal_error("Unsupported calling convention");
10583   case CallingConv::C:
10584   case CallingConv::Fast:
10585     break;
10586   case CallingConv::GHC:
10587     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10588         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10589       report_fatal_error(
10590         "GHC calling convention requires the F and D instruction set extensions");
10591   }
10592 
10593   const Function &Func = MF.getFunction();
10594   if (Func.hasFnAttribute("interrupt")) {
10595     if (!Func.arg_empty())
10596       report_fatal_error(
10597         "Functions with the interrupt attribute cannot have arguments!");
10598 
10599     StringRef Kind =
10600       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10601 
10602     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10603       report_fatal_error(
10604         "Function interrupt attribute argument not supported!");
10605   }
10606 
10607   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10608   MVT XLenVT = Subtarget.getXLenVT();
10609   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10610   // Used with vargs to acumulate store chains.
10611   std::vector<SDValue> OutChains;
10612 
10613   // Assign locations to all of the incoming arguments.
10614   SmallVector<CCValAssign, 16> ArgLocs;
10615   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10616 
10617   if (CallConv == CallingConv::GHC)
10618     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10619   else
10620     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10621                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10622                                                    : CC_RISCV);
10623 
10624   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10625     CCValAssign &VA = ArgLocs[i];
10626     SDValue ArgValue;
10627     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10628     // case.
10629     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10630       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10631     else if (VA.isRegLoc())
10632       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10633     else
10634       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10635 
10636     if (VA.getLocInfo() == CCValAssign::Indirect) {
10637       // If the original argument was split and passed by reference (e.g. i128
10638       // on RV32), we need to load all parts of it here (using the same
10639       // address). Vectors may be partly split to registers and partly to the
10640       // stack, in which case the base address is partly offset and subsequent
10641       // stores are relative to that.
10642       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10643                                    MachinePointerInfo()));
10644       unsigned ArgIndex = Ins[i].OrigArgIndex;
10645       unsigned ArgPartOffset = Ins[i].PartOffset;
10646       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10647       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10648         CCValAssign &PartVA = ArgLocs[i + 1];
10649         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10650         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10651         if (PartVA.getValVT().isScalableVector())
10652           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10653         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10654         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10655                                      MachinePointerInfo()));
10656         ++i;
10657       }
10658       continue;
10659     }
10660     InVals.push_back(ArgValue);
10661   }
10662 
10663   if (IsVarArg) {
10664     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10665     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10666     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10667     MachineFrameInfo &MFI = MF.getFrameInfo();
10668     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10669     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10670 
10671     // Offset of the first variable argument from stack pointer, and size of
10672     // the vararg save area. For now, the varargs save area is either zero or
10673     // large enough to hold a0-a7.
10674     int VaArgOffset, VarArgsSaveSize;
10675 
10676     // If all registers are allocated, then all varargs must be passed on the
10677     // stack and we don't need to save any argregs.
10678     if (ArgRegs.size() == Idx) {
10679       VaArgOffset = CCInfo.getNextStackOffset();
10680       VarArgsSaveSize = 0;
10681     } else {
10682       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10683       VaArgOffset = -VarArgsSaveSize;
10684     }
10685 
10686     // Record the frame index of the first variable argument
10687     // which is a value necessary to VASTART.
10688     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10689     RVFI->setVarArgsFrameIndex(FI);
10690 
10691     // If saving an odd number of registers then create an extra stack slot to
10692     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10693     // offsets to even-numbered registered remain 2*XLEN-aligned.
10694     if (Idx % 2) {
10695       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10696       VarArgsSaveSize += XLenInBytes;
10697     }
10698 
10699     // Copy the integer registers that may have been used for passing varargs
10700     // to the vararg save area.
10701     for (unsigned I = Idx; I < ArgRegs.size();
10702          ++I, VaArgOffset += XLenInBytes) {
10703       const Register Reg = RegInfo.createVirtualRegister(RC);
10704       RegInfo.addLiveIn(ArgRegs[I], Reg);
10705       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10706       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10707       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10708       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10709                                    MachinePointerInfo::getFixedStack(MF, FI));
10710       cast<StoreSDNode>(Store.getNode())
10711           ->getMemOperand()
10712           ->setValue((Value *)nullptr);
10713       OutChains.push_back(Store);
10714     }
10715     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10716   }
10717 
10718   // All stores are grouped in one node to allow the matching between
10719   // the size of Ins and InVals. This only happens for vararg functions.
10720   if (!OutChains.empty()) {
10721     OutChains.push_back(Chain);
10722     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10723   }
10724 
10725   return Chain;
10726 }
10727 
10728 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10729 /// for tail call optimization.
10730 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10731 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10732     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10733     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10734 
10735   auto &Callee = CLI.Callee;
10736   auto CalleeCC = CLI.CallConv;
10737   auto &Outs = CLI.Outs;
10738   auto &Caller = MF.getFunction();
10739   auto CallerCC = Caller.getCallingConv();
10740 
10741   // Exception-handling functions need a special set of instructions to
10742   // indicate a return to the hardware. Tail-calling another function would
10743   // probably break this.
10744   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10745   // should be expanded as new function attributes are introduced.
10746   if (Caller.hasFnAttribute("interrupt"))
10747     return false;
10748 
10749   // Do not tail call opt if the stack is used to pass parameters.
10750   if (CCInfo.getNextStackOffset() != 0)
10751     return false;
10752 
10753   // Do not tail call opt if any parameters need to be passed indirectly.
10754   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10755   // passed indirectly. So the address of the value will be passed in a
10756   // register, or if not available, then the address is put on the stack. In
10757   // order to pass indirectly, space on the stack often needs to be allocated
10758   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10759   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10760   // are passed CCValAssign::Indirect.
10761   for (auto &VA : ArgLocs)
10762     if (VA.getLocInfo() == CCValAssign::Indirect)
10763       return false;
10764 
10765   // Do not tail call opt if either caller or callee uses struct return
10766   // semantics.
10767   auto IsCallerStructRet = Caller.hasStructRetAttr();
10768   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10769   if (IsCallerStructRet || IsCalleeStructRet)
10770     return false;
10771 
10772   // Externally-defined functions with weak linkage should not be
10773   // tail-called. The behaviour of branch instructions in this situation (as
10774   // used for tail calls) is implementation-defined, so we cannot rely on the
10775   // linker replacing the tail call with a return.
10776   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10777     const GlobalValue *GV = G->getGlobal();
10778     if (GV->hasExternalWeakLinkage())
10779       return false;
10780   }
10781 
10782   // The callee has to preserve all registers the caller needs to preserve.
10783   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10784   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10785   if (CalleeCC != CallerCC) {
10786     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10787     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10788       return false;
10789   }
10790 
10791   // Byval parameters hand the function a pointer directly into the stack area
10792   // we want to reuse during a tail call. Working around this *is* possible
10793   // but less efficient and uglier in LowerCall.
10794   for (auto &Arg : Outs)
10795     if (Arg.Flags.isByVal())
10796       return false;
10797 
10798   return true;
10799 }
10800 
10801 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10802   return DAG.getDataLayout().getPrefTypeAlign(
10803       VT.getTypeForEVT(*DAG.getContext()));
10804 }
10805 
10806 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10807 // and output parameter nodes.
10808 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10809                                        SmallVectorImpl<SDValue> &InVals) const {
10810   SelectionDAG &DAG = CLI.DAG;
10811   SDLoc &DL = CLI.DL;
10812   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10813   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10814   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10815   SDValue Chain = CLI.Chain;
10816   SDValue Callee = CLI.Callee;
10817   bool &IsTailCall = CLI.IsTailCall;
10818   CallingConv::ID CallConv = CLI.CallConv;
10819   bool IsVarArg = CLI.IsVarArg;
10820   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10821   MVT XLenVT = Subtarget.getXLenVT();
10822 
10823   MachineFunction &MF = DAG.getMachineFunction();
10824 
10825   // Analyze the operands of the call, assigning locations to each operand.
10826   SmallVector<CCValAssign, 16> ArgLocs;
10827   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10828 
10829   if (CallConv == CallingConv::GHC)
10830     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10831   else
10832     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10833                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10834                                                     : CC_RISCV);
10835 
10836   // Check if it's really possible to do a tail call.
10837   if (IsTailCall)
10838     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10839 
10840   if (IsTailCall)
10841     ++NumTailCalls;
10842   else if (CLI.CB && CLI.CB->isMustTailCall())
10843     report_fatal_error("failed to perform tail call elimination on a call "
10844                        "site marked musttail");
10845 
10846   // Get a count of how many bytes are to be pushed on the stack.
10847   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10848 
10849   // Create local copies for byval args
10850   SmallVector<SDValue, 8> ByValArgs;
10851   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10852     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10853     if (!Flags.isByVal())
10854       continue;
10855 
10856     SDValue Arg = OutVals[i];
10857     unsigned Size = Flags.getByValSize();
10858     Align Alignment = Flags.getNonZeroByValAlign();
10859 
10860     int FI =
10861         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10862     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10863     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10864 
10865     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10866                           /*IsVolatile=*/false,
10867                           /*AlwaysInline=*/false, IsTailCall,
10868                           MachinePointerInfo(), MachinePointerInfo());
10869     ByValArgs.push_back(FIPtr);
10870   }
10871 
10872   if (!IsTailCall)
10873     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10874 
10875   // Copy argument values to their designated locations.
10876   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10877   SmallVector<SDValue, 8> MemOpChains;
10878   SDValue StackPtr;
10879   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10880     CCValAssign &VA = ArgLocs[i];
10881     SDValue ArgValue = OutVals[i];
10882     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10883 
10884     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10885     bool IsF64OnRV32DSoftABI =
10886         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10887     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10888       SDValue SplitF64 = DAG.getNode(
10889           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10890       SDValue Lo = SplitF64.getValue(0);
10891       SDValue Hi = SplitF64.getValue(1);
10892 
10893       Register RegLo = VA.getLocReg();
10894       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10895 
10896       if (RegLo == RISCV::X17) {
10897         // Second half of f64 is passed on the stack.
10898         // Work out the address of the stack slot.
10899         if (!StackPtr.getNode())
10900           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10901         // Emit the store.
10902         MemOpChains.push_back(
10903             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10904       } else {
10905         // Second half of f64 is passed in another GPR.
10906         assert(RegLo < RISCV::X31 && "Invalid register pair");
10907         Register RegHigh = RegLo + 1;
10908         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10909       }
10910       continue;
10911     }
10912 
10913     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10914     // as any other MemLoc.
10915 
10916     // Promote the value if needed.
10917     // For now, only handle fully promoted and indirect arguments.
10918     if (VA.getLocInfo() == CCValAssign::Indirect) {
10919       // Store the argument in a stack slot and pass its address.
10920       Align StackAlign =
10921           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10922                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10923       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10924       // If the original argument was split (e.g. i128), we need
10925       // to store the required parts of it here (and pass just one address).
10926       // Vectors may be partly split to registers and partly to the stack, in
10927       // which case the base address is partly offset and subsequent stores are
10928       // relative to that.
10929       unsigned ArgIndex = Outs[i].OrigArgIndex;
10930       unsigned ArgPartOffset = Outs[i].PartOffset;
10931       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10932       // Calculate the total size to store. We don't have access to what we're
10933       // actually storing other than performing the loop and collecting the
10934       // info.
10935       SmallVector<std::pair<SDValue, SDValue>> Parts;
10936       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10937         SDValue PartValue = OutVals[i + 1];
10938         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10939         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10940         EVT PartVT = PartValue.getValueType();
10941         if (PartVT.isScalableVector())
10942           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10943         StoredSize += PartVT.getStoreSize();
10944         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10945         Parts.push_back(std::make_pair(PartValue, Offset));
10946         ++i;
10947       }
10948       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10949       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10950       MemOpChains.push_back(
10951           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10952                        MachinePointerInfo::getFixedStack(MF, FI)));
10953       for (const auto &Part : Parts) {
10954         SDValue PartValue = Part.first;
10955         SDValue PartOffset = Part.second;
10956         SDValue Address =
10957             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10958         MemOpChains.push_back(
10959             DAG.getStore(Chain, DL, PartValue, Address,
10960                          MachinePointerInfo::getFixedStack(MF, FI)));
10961       }
10962       ArgValue = SpillSlot;
10963     } else {
10964       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10965     }
10966 
10967     // Use local copy if it is a byval arg.
10968     if (Flags.isByVal())
10969       ArgValue = ByValArgs[j++];
10970 
10971     if (VA.isRegLoc()) {
10972       // Queue up the argument copies and emit them at the end.
10973       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10974     } else {
10975       assert(VA.isMemLoc() && "Argument not register or memory");
10976       assert(!IsTailCall && "Tail call not allowed if stack is used "
10977                             "for passing parameters");
10978 
10979       // Work out the address of the stack slot.
10980       if (!StackPtr.getNode())
10981         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10982       SDValue Address =
10983           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10984                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10985 
10986       // Emit the store.
10987       MemOpChains.push_back(
10988           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10989     }
10990   }
10991 
10992   // Join the stores, which are independent of one another.
10993   if (!MemOpChains.empty())
10994     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10995 
10996   SDValue Glue;
10997 
10998   // Build a sequence of copy-to-reg nodes, chained and glued together.
10999   for (auto &Reg : RegsToPass) {
11000     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
11001     Glue = Chain.getValue(1);
11002   }
11003 
11004   // Validate that none of the argument registers have been marked as
11005   // reserved, if so report an error. Do the same for the return address if this
11006   // is not a tailcall.
11007   validateCCReservedRegs(RegsToPass, MF);
11008   if (!IsTailCall &&
11009       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
11010     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11011         MF.getFunction(),
11012         "Return address register required, but has been reserved."});
11013 
11014   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
11015   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
11016   // split it and then direct call can be matched by PseudoCALL.
11017   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
11018     const GlobalValue *GV = S->getGlobal();
11019 
11020     unsigned OpFlags = RISCVII::MO_CALL;
11021     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
11022       OpFlags = RISCVII::MO_PLT;
11023 
11024     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
11025   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
11026     unsigned OpFlags = RISCVII::MO_CALL;
11027 
11028     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
11029                                                  nullptr))
11030       OpFlags = RISCVII::MO_PLT;
11031 
11032     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
11033   }
11034 
11035   // The first call operand is the chain and the second is the target address.
11036   SmallVector<SDValue, 8> Ops;
11037   Ops.push_back(Chain);
11038   Ops.push_back(Callee);
11039 
11040   // Add argument registers to the end of the list so that they are
11041   // known live into the call.
11042   for (auto &Reg : RegsToPass)
11043     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
11044 
11045   if (!IsTailCall) {
11046     // Add a register mask operand representing the call-preserved registers.
11047     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
11048     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
11049     assert(Mask && "Missing call preserved mask for calling convention");
11050     Ops.push_back(DAG.getRegisterMask(Mask));
11051   }
11052 
11053   // Glue the call to the argument copies, if any.
11054   if (Glue.getNode())
11055     Ops.push_back(Glue);
11056 
11057   // Emit the call.
11058   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11059 
11060   if (IsTailCall) {
11061     MF.getFrameInfo().setHasTailCall();
11062     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
11063   }
11064 
11065   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
11066   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
11067   Glue = Chain.getValue(1);
11068 
11069   // Mark the end of the call, which is glued to the call itself.
11070   Chain = DAG.getCALLSEQ_END(Chain,
11071                              DAG.getConstant(NumBytes, DL, PtrVT, true),
11072                              DAG.getConstant(0, DL, PtrVT, true),
11073                              Glue, DL);
11074   Glue = Chain.getValue(1);
11075 
11076   // Assign locations to each value returned by this call.
11077   SmallVector<CCValAssign, 16> RVLocs;
11078   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
11079   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
11080 
11081   // Copy all of the result registers out of their specified physreg.
11082   for (auto &VA : RVLocs) {
11083     // Copy the value out
11084     SDValue RetValue =
11085         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
11086     // Glue the RetValue to the end of the call sequence
11087     Chain = RetValue.getValue(1);
11088     Glue = RetValue.getValue(2);
11089 
11090     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11091       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
11092       SDValue RetValue2 =
11093           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
11094       Chain = RetValue2.getValue(1);
11095       Glue = RetValue2.getValue(2);
11096       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
11097                              RetValue2);
11098     }
11099 
11100     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
11101 
11102     InVals.push_back(RetValue);
11103   }
11104 
11105   return Chain;
11106 }
11107 
11108 bool RISCVTargetLowering::CanLowerReturn(
11109     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
11110     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
11111   SmallVector<CCValAssign, 16> RVLocs;
11112   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
11113 
11114   Optional<unsigned> FirstMaskArgument;
11115   if (Subtarget.hasVInstructions())
11116     FirstMaskArgument = preAssignMask(Outs);
11117 
11118   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
11119     MVT VT = Outs[i].VT;
11120     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
11121     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
11122     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
11123                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
11124                  *this, FirstMaskArgument))
11125       return false;
11126   }
11127   return true;
11128 }
11129 
11130 SDValue
11131 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
11132                                  bool IsVarArg,
11133                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
11134                                  const SmallVectorImpl<SDValue> &OutVals,
11135                                  const SDLoc &DL, SelectionDAG &DAG) const {
11136   const MachineFunction &MF = DAG.getMachineFunction();
11137   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11138 
11139   // Stores the assignment of the return value to a location.
11140   SmallVector<CCValAssign, 16> RVLocs;
11141 
11142   // Info about the registers and stack slot.
11143   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
11144                  *DAG.getContext());
11145 
11146   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
11147                     nullptr, CC_RISCV);
11148 
11149   if (CallConv == CallingConv::GHC && !RVLocs.empty())
11150     report_fatal_error("GHC functions return void only");
11151 
11152   SDValue Glue;
11153   SmallVector<SDValue, 4> RetOps(1, Chain);
11154 
11155   // Copy the result values into the output registers.
11156   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
11157     SDValue Val = OutVals[i];
11158     CCValAssign &VA = RVLocs[i];
11159     assert(VA.isRegLoc() && "Can only return in registers!");
11160 
11161     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11162       // Handle returning f64 on RV32D with a soft float ABI.
11163       assert(VA.isRegLoc() && "Expected return via registers");
11164       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
11165                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
11166       SDValue Lo = SplitF64.getValue(0);
11167       SDValue Hi = SplitF64.getValue(1);
11168       Register RegLo = VA.getLocReg();
11169       assert(RegLo < RISCV::X31 && "Invalid register pair");
11170       Register RegHi = RegLo + 1;
11171 
11172       if (STI.isRegisterReservedByUser(RegLo) ||
11173           STI.isRegisterReservedByUser(RegHi))
11174         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11175             MF.getFunction(),
11176             "Return value register required, but has been reserved."});
11177 
11178       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
11179       Glue = Chain.getValue(1);
11180       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
11181       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
11182       Glue = Chain.getValue(1);
11183       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
11184     } else {
11185       // Handle a 'normal' return.
11186       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
11187       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
11188 
11189       if (STI.isRegisterReservedByUser(VA.getLocReg()))
11190         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11191             MF.getFunction(),
11192             "Return value register required, but has been reserved."});
11193 
11194       // Guarantee that all emitted copies are stuck together.
11195       Glue = Chain.getValue(1);
11196       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
11197     }
11198   }
11199 
11200   RetOps[0] = Chain; // Update chain.
11201 
11202   // Add the glue node if we have it.
11203   if (Glue.getNode()) {
11204     RetOps.push_back(Glue);
11205   }
11206 
11207   unsigned RetOpc = RISCVISD::RET_FLAG;
11208   // Interrupt service routines use different return instructions.
11209   const Function &Func = DAG.getMachineFunction().getFunction();
11210   if (Func.hasFnAttribute("interrupt")) {
11211     if (!Func.getReturnType()->isVoidTy())
11212       report_fatal_error(
11213           "Functions with the interrupt attribute must have void return type!");
11214 
11215     MachineFunction &MF = DAG.getMachineFunction();
11216     StringRef Kind =
11217       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
11218 
11219     if (Kind == "user")
11220       RetOpc = RISCVISD::URET_FLAG;
11221     else if (Kind == "supervisor")
11222       RetOpc = RISCVISD::SRET_FLAG;
11223     else
11224       RetOpc = RISCVISD::MRET_FLAG;
11225   }
11226 
11227   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
11228 }
11229 
11230 void RISCVTargetLowering::validateCCReservedRegs(
11231     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
11232     MachineFunction &MF) const {
11233   const Function &F = MF.getFunction();
11234   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11235 
11236   if (llvm::any_of(Regs, [&STI](auto Reg) {
11237         return STI.isRegisterReservedByUser(Reg.first);
11238       }))
11239     F.getContext().diagnose(DiagnosticInfoUnsupported{
11240         F, "Argument register required, but has been reserved."});
11241 }
11242 
11243 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11244   return CI->isTailCall();
11245 }
11246 
11247 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
11248 #define NODE_NAME_CASE(NODE)                                                   \
11249   case RISCVISD::NODE:                                                         \
11250     return "RISCVISD::" #NODE;
11251   // clang-format off
11252   switch ((RISCVISD::NodeType)Opcode) {
11253   case RISCVISD::FIRST_NUMBER:
11254     break;
11255   NODE_NAME_CASE(RET_FLAG)
11256   NODE_NAME_CASE(URET_FLAG)
11257   NODE_NAME_CASE(SRET_FLAG)
11258   NODE_NAME_CASE(MRET_FLAG)
11259   NODE_NAME_CASE(CALL)
11260   NODE_NAME_CASE(SELECT_CC)
11261   NODE_NAME_CASE(BR_CC)
11262   NODE_NAME_CASE(BuildPairF64)
11263   NODE_NAME_CASE(SplitF64)
11264   NODE_NAME_CASE(TAIL)
11265   NODE_NAME_CASE(ADD_LO)
11266   NODE_NAME_CASE(HI)
11267   NODE_NAME_CASE(LLA)
11268   NODE_NAME_CASE(ADD_TPREL)
11269   NODE_NAME_CASE(LA)
11270   NODE_NAME_CASE(LA_TLS_IE)
11271   NODE_NAME_CASE(LA_TLS_GD)
11272   NODE_NAME_CASE(MULHSU)
11273   NODE_NAME_CASE(SLLW)
11274   NODE_NAME_CASE(SRAW)
11275   NODE_NAME_CASE(SRLW)
11276   NODE_NAME_CASE(DIVW)
11277   NODE_NAME_CASE(DIVUW)
11278   NODE_NAME_CASE(REMUW)
11279   NODE_NAME_CASE(ROLW)
11280   NODE_NAME_CASE(RORW)
11281   NODE_NAME_CASE(CLZW)
11282   NODE_NAME_CASE(CTZW)
11283   NODE_NAME_CASE(FSLW)
11284   NODE_NAME_CASE(FSRW)
11285   NODE_NAME_CASE(FSL)
11286   NODE_NAME_CASE(FSR)
11287   NODE_NAME_CASE(FMV_H_X)
11288   NODE_NAME_CASE(FMV_X_ANYEXTH)
11289   NODE_NAME_CASE(FMV_X_SIGNEXTH)
11290   NODE_NAME_CASE(FMV_W_X_RV64)
11291   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
11292   NODE_NAME_CASE(FCVT_X)
11293   NODE_NAME_CASE(FCVT_XU)
11294   NODE_NAME_CASE(FCVT_W_RV64)
11295   NODE_NAME_CASE(FCVT_WU_RV64)
11296   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
11297   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
11298   NODE_NAME_CASE(READ_CYCLE_WIDE)
11299   NODE_NAME_CASE(GREV)
11300   NODE_NAME_CASE(GREVW)
11301   NODE_NAME_CASE(GORC)
11302   NODE_NAME_CASE(GORCW)
11303   NODE_NAME_CASE(SHFL)
11304   NODE_NAME_CASE(SHFLW)
11305   NODE_NAME_CASE(UNSHFL)
11306   NODE_NAME_CASE(UNSHFLW)
11307   NODE_NAME_CASE(BFP)
11308   NODE_NAME_CASE(BFPW)
11309   NODE_NAME_CASE(BCOMPRESS)
11310   NODE_NAME_CASE(BCOMPRESSW)
11311   NODE_NAME_CASE(BDECOMPRESS)
11312   NODE_NAME_CASE(BDECOMPRESSW)
11313   NODE_NAME_CASE(VMV_V_X_VL)
11314   NODE_NAME_CASE(VFMV_V_F_VL)
11315   NODE_NAME_CASE(VMV_X_S)
11316   NODE_NAME_CASE(VMV_S_X_VL)
11317   NODE_NAME_CASE(VFMV_S_F_VL)
11318   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
11319   NODE_NAME_CASE(READ_VLENB)
11320   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
11321   NODE_NAME_CASE(VSLIDEUP_VL)
11322   NODE_NAME_CASE(VSLIDE1UP_VL)
11323   NODE_NAME_CASE(VSLIDEDOWN_VL)
11324   NODE_NAME_CASE(VSLIDE1DOWN_VL)
11325   NODE_NAME_CASE(VID_VL)
11326   NODE_NAME_CASE(VFNCVT_ROD_VL)
11327   NODE_NAME_CASE(VECREDUCE_ADD_VL)
11328   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
11329   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
11330   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
11331   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
11332   NODE_NAME_CASE(VECREDUCE_AND_VL)
11333   NODE_NAME_CASE(VECREDUCE_OR_VL)
11334   NODE_NAME_CASE(VECREDUCE_XOR_VL)
11335   NODE_NAME_CASE(VECREDUCE_FADD_VL)
11336   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
11337   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
11338   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
11339   NODE_NAME_CASE(ADD_VL)
11340   NODE_NAME_CASE(AND_VL)
11341   NODE_NAME_CASE(MUL_VL)
11342   NODE_NAME_CASE(OR_VL)
11343   NODE_NAME_CASE(SDIV_VL)
11344   NODE_NAME_CASE(SHL_VL)
11345   NODE_NAME_CASE(SREM_VL)
11346   NODE_NAME_CASE(SRA_VL)
11347   NODE_NAME_CASE(SRL_VL)
11348   NODE_NAME_CASE(SUB_VL)
11349   NODE_NAME_CASE(UDIV_VL)
11350   NODE_NAME_CASE(UREM_VL)
11351   NODE_NAME_CASE(XOR_VL)
11352   NODE_NAME_CASE(SADDSAT_VL)
11353   NODE_NAME_CASE(UADDSAT_VL)
11354   NODE_NAME_CASE(SSUBSAT_VL)
11355   NODE_NAME_CASE(USUBSAT_VL)
11356   NODE_NAME_CASE(FADD_VL)
11357   NODE_NAME_CASE(FSUB_VL)
11358   NODE_NAME_CASE(FMUL_VL)
11359   NODE_NAME_CASE(FDIV_VL)
11360   NODE_NAME_CASE(FNEG_VL)
11361   NODE_NAME_CASE(FABS_VL)
11362   NODE_NAME_CASE(FSQRT_VL)
11363   NODE_NAME_CASE(VFMADD_VL)
11364   NODE_NAME_CASE(VFNMADD_VL)
11365   NODE_NAME_CASE(VFMSUB_VL)
11366   NODE_NAME_CASE(VFNMSUB_VL)
11367   NODE_NAME_CASE(FCOPYSIGN_VL)
11368   NODE_NAME_CASE(SMIN_VL)
11369   NODE_NAME_CASE(SMAX_VL)
11370   NODE_NAME_CASE(UMIN_VL)
11371   NODE_NAME_CASE(UMAX_VL)
11372   NODE_NAME_CASE(FMINNUM_VL)
11373   NODE_NAME_CASE(FMAXNUM_VL)
11374   NODE_NAME_CASE(MULHS_VL)
11375   NODE_NAME_CASE(MULHU_VL)
11376   NODE_NAME_CASE(FP_TO_SINT_VL)
11377   NODE_NAME_CASE(FP_TO_UINT_VL)
11378   NODE_NAME_CASE(SINT_TO_FP_VL)
11379   NODE_NAME_CASE(UINT_TO_FP_VL)
11380   NODE_NAME_CASE(FP_EXTEND_VL)
11381   NODE_NAME_CASE(FP_ROUND_VL)
11382   NODE_NAME_CASE(VWMUL_VL)
11383   NODE_NAME_CASE(VWMULU_VL)
11384   NODE_NAME_CASE(VWMULSU_VL)
11385   NODE_NAME_CASE(VWADD_VL)
11386   NODE_NAME_CASE(VWADDU_VL)
11387   NODE_NAME_CASE(VWSUB_VL)
11388   NODE_NAME_CASE(VWSUBU_VL)
11389   NODE_NAME_CASE(VWADD_W_VL)
11390   NODE_NAME_CASE(VWADDU_W_VL)
11391   NODE_NAME_CASE(VWSUB_W_VL)
11392   NODE_NAME_CASE(VWSUBU_W_VL)
11393   NODE_NAME_CASE(SETCC_VL)
11394   NODE_NAME_CASE(VSELECT_VL)
11395   NODE_NAME_CASE(VP_MERGE_VL)
11396   NODE_NAME_CASE(VMAND_VL)
11397   NODE_NAME_CASE(VMOR_VL)
11398   NODE_NAME_CASE(VMXOR_VL)
11399   NODE_NAME_CASE(VMCLR_VL)
11400   NODE_NAME_CASE(VMSET_VL)
11401   NODE_NAME_CASE(VRGATHER_VX_VL)
11402   NODE_NAME_CASE(VRGATHER_VV_VL)
11403   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
11404   NODE_NAME_CASE(VSEXT_VL)
11405   NODE_NAME_CASE(VZEXT_VL)
11406   NODE_NAME_CASE(VCPOP_VL)
11407   NODE_NAME_CASE(READ_CSR)
11408   NODE_NAME_CASE(WRITE_CSR)
11409   NODE_NAME_CASE(SWAP_CSR)
11410   }
11411   // clang-format on
11412   return nullptr;
11413 #undef NODE_NAME_CASE
11414 }
11415 
11416 /// getConstraintType - Given a constraint letter, return the type of
11417 /// constraint it is for this target.
11418 RISCVTargetLowering::ConstraintType
11419 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
11420   if (Constraint.size() == 1) {
11421     switch (Constraint[0]) {
11422     default:
11423       break;
11424     case 'f':
11425       return C_RegisterClass;
11426     case 'I':
11427     case 'J':
11428     case 'K':
11429       return C_Immediate;
11430     case 'A':
11431       return C_Memory;
11432     case 'S': // A symbolic address
11433       return C_Other;
11434     }
11435   } else {
11436     if (Constraint == "vr" || Constraint == "vm")
11437       return C_RegisterClass;
11438   }
11439   return TargetLowering::getConstraintType(Constraint);
11440 }
11441 
11442 std::pair<unsigned, const TargetRegisterClass *>
11443 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11444                                                   StringRef Constraint,
11445                                                   MVT VT) const {
11446   // First, see if this is a constraint that directly corresponds to a
11447   // RISCV register class.
11448   if (Constraint.size() == 1) {
11449     switch (Constraint[0]) {
11450     case 'r':
11451       // TODO: Support fixed vectors up to XLen for P extension?
11452       if (VT.isVector())
11453         break;
11454       return std::make_pair(0U, &RISCV::GPRRegClass);
11455     case 'f':
11456       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11457         return std::make_pair(0U, &RISCV::FPR16RegClass);
11458       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11459         return std::make_pair(0U, &RISCV::FPR32RegClass);
11460       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11461         return std::make_pair(0U, &RISCV::FPR64RegClass);
11462       break;
11463     default:
11464       break;
11465     }
11466   } else if (Constraint == "vr") {
11467     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11468                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11469       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11470         return std::make_pair(0U, RC);
11471     }
11472   } else if (Constraint == "vm") {
11473     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11474       return std::make_pair(0U, &RISCV::VMV0RegClass);
11475   }
11476 
11477   // Clang will correctly decode the usage of register name aliases into their
11478   // official names. However, other frontends like `rustc` do not. This allows
11479   // users of these frontends to use the ABI names for registers in LLVM-style
11480   // register constraints.
11481   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11482                                .Case("{zero}", RISCV::X0)
11483                                .Case("{ra}", RISCV::X1)
11484                                .Case("{sp}", RISCV::X2)
11485                                .Case("{gp}", RISCV::X3)
11486                                .Case("{tp}", RISCV::X4)
11487                                .Case("{t0}", RISCV::X5)
11488                                .Case("{t1}", RISCV::X6)
11489                                .Case("{t2}", RISCV::X7)
11490                                .Cases("{s0}", "{fp}", RISCV::X8)
11491                                .Case("{s1}", RISCV::X9)
11492                                .Case("{a0}", RISCV::X10)
11493                                .Case("{a1}", RISCV::X11)
11494                                .Case("{a2}", RISCV::X12)
11495                                .Case("{a3}", RISCV::X13)
11496                                .Case("{a4}", RISCV::X14)
11497                                .Case("{a5}", RISCV::X15)
11498                                .Case("{a6}", RISCV::X16)
11499                                .Case("{a7}", RISCV::X17)
11500                                .Case("{s2}", RISCV::X18)
11501                                .Case("{s3}", RISCV::X19)
11502                                .Case("{s4}", RISCV::X20)
11503                                .Case("{s5}", RISCV::X21)
11504                                .Case("{s6}", RISCV::X22)
11505                                .Case("{s7}", RISCV::X23)
11506                                .Case("{s8}", RISCV::X24)
11507                                .Case("{s9}", RISCV::X25)
11508                                .Case("{s10}", RISCV::X26)
11509                                .Case("{s11}", RISCV::X27)
11510                                .Case("{t3}", RISCV::X28)
11511                                .Case("{t4}", RISCV::X29)
11512                                .Case("{t5}", RISCV::X30)
11513                                .Case("{t6}", RISCV::X31)
11514                                .Default(RISCV::NoRegister);
11515   if (XRegFromAlias != RISCV::NoRegister)
11516     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11517 
11518   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11519   // TableGen record rather than the AsmName to choose registers for InlineAsm
11520   // constraints, plus we want to match those names to the widest floating point
11521   // register type available, manually select floating point registers here.
11522   //
11523   // The second case is the ABI name of the register, so that frontends can also
11524   // use the ABI names in register constraint lists.
11525   if (Subtarget.hasStdExtF()) {
11526     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11527                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11528                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11529                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11530                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11531                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11532                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11533                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11534                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11535                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11536                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11537                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11538                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11539                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11540                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11541                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11542                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11543                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11544                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11545                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11546                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11547                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11548                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11549                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11550                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11551                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11552                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11553                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11554                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11555                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11556                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11557                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11558                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11559                         .Default(RISCV::NoRegister);
11560     if (FReg != RISCV::NoRegister) {
11561       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11562       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11563         unsigned RegNo = FReg - RISCV::F0_F;
11564         unsigned DReg = RISCV::F0_D + RegNo;
11565         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11566       }
11567       if (VT == MVT::f32 || VT == MVT::Other)
11568         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11569       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11570         unsigned RegNo = FReg - RISCV::F0_F;
11571         unsigned HReg = RISCV::F0_H + RegNo;
11572         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11573       }
11574     }
11575   }
11576 
11577   if (Subtarget.hasVInstructions()) {
11578     Register VReg = StringSwitch<Register>(Constraint.lower())
11579                         .Case("{v0}", RISCV::V0)
11580                         .Case("{v1}", RISCV::V1)
11581                         .Case("{v2}", RISCV::V2)
11582                         .Case("{v3}", RISCV::V3)
11583                         .Case("{v4}", RISCV::V4)
11584                         .Case("{v5}", RISCV::V5)
11585                         .Case("{v6}", RISCV::V6)
11586                         .Case("{v7}", RISCV::V7)
11587                         .Case("{v8}", RISCV::V8)
11588                         .Case("{v9}", RISCV::V9)
11589                         .Case("{v10}", RISCV::V10)
11590                         .Case("{v11}", RISCV::V11)
11591                         .Case("{v12}", RISCV::V12)
11592                         .Case("{v13}", RISCV::V13)
11593                         .Case("{v14}", RISCV::V14)
11594                         .Case("{v15}", RISCV::V15)
11595                         .Case("{v16}", RISCV::V16)
11596                         .Case("{v17}", RISCV::V17)
11597                         .Case("{v18}", RISCV::V18)
11598                         .Case("{v19}", RISCV::V19)
11599                         .Case("{v20}", RISCV::V20)
11600                         .Case("{v21}", RISCV::V21)
11601                         .Case("{v22}", RISCV::V22)
11602                         .Case("{v23}", RISCV::V23)
11603                         .Case("{v24}", RISCV::V24)
11604                         .Case("{v25}", RISCV::V25)
11605                         .Case("{v26}", RISCV::V26)
11606                         .Case("{v27}", RISCV::V27)
11607                         .Case("{v28}", RISCV::V28)
11608                         .Case("{v29}", RISCV::V29)
11609                         .Case("{v30}", RISCV::V30)
11610                         .Case("{v31}", RISCV::V31)
11611                         .Default(RISCV::NoRegister);
11612     if (VReg != RISCV::NoRegister) {
11613       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11614         return std::make_pair(VReg, &RISCV::VMRegClass);
11615       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11616         return std::make_pair(VReg, &RISCV::VRRegClass);
11617       for (const auto *RC :
11618            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11619         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11620           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11621           return std::make_pair(VReg, RC);
11622         }
11623       }
11624     }
11625   }
11626 
11627   std::pair<Register, const TargetRegisterClass *> Res =
11628       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11629 
11630   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11631   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11632   // Subtarget into account.
11633   if (Res.second == &RISCV::GPRF16RegClass ||
11634       Res.second == &RISCV::GPRF32RegClass ||
11635       Res.second == &RISCV::GPRF64RegClass)
11636     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11637 
11638   return Res;
11639 }
11640 
11641 unsigned
11642 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11643   // Currently only support length 1 constraints.
11644   if (ConstraintCode.size() == 1) {
11645     switch (ConstraintCode[0]) {
11646     case 'A':
11647       return InlineAsm::Constraint_A;
11648     default:
11649       break;
11650     }
11651   }
11652 
11653   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11654 }
11655 
11656 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11657     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11658     SelectionDAG &DAG) const {
11659   // Currently only support length 1 constraints.
11660   if (Constraint.length() == 1) {
11661     switch (Constraint[0]) {
11662     case 'I':
11663       // Validate & create a 12-bit signed immediate operand.
11664       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11665         uint64_t CVal = C->getSExtValue();
11666         if (isInt<12>(CVal))
11667           Ops.push_back(
11668               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11669       }
11670       return;
11671     case 'J':
11672       // Validate & create an integer zero operand.
11673       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11674         if (C->getZExtValue() == 0)
11675           Ops.push_back(
11676               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11677       return;
11678     case 'K':
11679       // Validate & create a 5-bit unsigned immediate operand.
11680       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11681         uint64_t CVal = C->getZExtValue();
11682         if (isUInt<5>(CVal))
11683           Ops.push_back(
11684               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11685       }
11686       return;
11687     case 'S':
11688       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11689         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11690                                                  GA->getValueType(0)));
11691       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11692         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11693                                                 BA->getValueType(0)));
11694       }
11695       return;
11696     default:
11697       break;
11698     }
11699   }
11700   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11701 }
11702 
11703 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11704                                                    Instruction *Inst,
11705                                                    AtomicOrdering Ord) const {
11706   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11707     return Builder.CreateFence(Ord);
11708   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11709     return Builder.CreateFence(AtomicOrdering::Release);
11710   return nullptr;
11711 }
11712 
11713 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11714                                                     Instruction *Inst,
11715                                                     AtomicOrdering Ord) const {
11716   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11717     return Builder.CreateFence(AtomicOrdering::Acquire);
11718   return nullptr;
11719 }
11720 
11721 TargetLowering::AtomicExpansionKind
11722 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11723   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11724   // point operations can't be used in an lr/sc sequence without breaking the
11725   // forward-progress guarantee.
11726   if (AI->isFloatingPointOperation())
11727     return AtomicExpansionKind::CmpXChg;
11728 
11729   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11730   if (Size == 8 || Size == 16)
11731     return AtomicExpansionKind::MaskedIntrinsic;
11732   return AtomicExpansionKind::None;
11733 }
11734 
11735 static Intrinsic::ID
11736 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11737   if (XLen == 32) {
11738     switch (BinOp) {
11739     default:
11740       llvm_unreachable("Unexpected AtomicRMW BinOp");
11741     case AtomicRMWInst::Xchg:
11742       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11743     case AtomicRMWInst::Add:
11744       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11745     case AtomicRMWInst::Sub:
11746       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11747     case AtomicRMWInst::Nand:
11748       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11749     case AtomicRMWInst::Max:
11750       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11751     case AtomicRMWInst::Min:
11752       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11753     case AtomicRMWInst::UMax:
11754       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11755     case AtomicRMWInst::UMin:
11756       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11757     }
11758   }
11759 
11760   if (XLen == 64) {
11761     switch (BinOp) {
11762     default:
11763       llvm_unreachable("Unexpected AtomicRMW BinOp");
11764     case AtomicRMWInst::Xchg:
11765       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11766     case AtomicRMWInst::Add:
11767       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11768     case AtomicRMWInst::Sub:
11769       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11770     case AtomicRMWInst::Nand:
11771       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11772     case AtomicRMWInst::Max:
11773       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11774     case AtomicRMWInst::Min:
11775       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11776     case AtomicRMWInst::UMax:
11777       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11778     case AtomicRMWInst::UMin:
11779       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11780     }
11781   }
11782 
11783   llvm_unreachable("Unexpected XLen\n");
11784 }
11785 
11786 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11787     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11788     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11789   unsigned XLen = Subtarget.getXLen();
11790   Value *Ordering =
11791       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11792   Type *Tys[] = {AlignedAddr->getType()};
11793   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11794       AI->getModule(),
11795       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11796 
11797   if (XLen == 64) {
11798     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11799     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11800     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11801   }
11802 
11803   Value *Result;
11804 
11805   // Must pass the shift amount needed to sign extend the loaded value prior
11806   // to performing a signed comparison for min/max. ShiftAmt is the number of
11807   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11808   // is the number of bits to left+right shift the value in order to
11809   // sign-extend.
11810   if (AI->getOperation() == AtomicRMWInst::Min ||
11811       AI->getOperation() == AtomicRMWInst::Max) {
11812     const DataLayout &DL = AI->getModule()->getDataLayout();
11813     unsigned ValWidth =
11814         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11815     Value *SextShamt =
11816         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11817     Result = Builder.CreateCall(LrwOpScwLoop,
11818                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11819   } else {
11820     Result =
11821         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11822   }
11823 
11824   if (XLen == 64)
11825     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11826   return Result;
11827 }
11828 
11829 TargetLowering::AtomicExpansionKind
11830 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11831     AtomicCmpXchgInst *CI) const {
11832   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11833   if (Size == 8 || Size == 16)
11834     return AtomicExpansionKind::MaskedIntrinsic;
11835   return AtomicExpansionKind::None;
11836 }
11837 
11838 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11839     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11840     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11841   unsigned XLen = Subtarget.getXLen();
11842   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11843   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11844   if (XLen == 64) {
11845     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11846     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11847     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11848     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11849   }
11850   Type *Tys[] = {AlignedAddr->getType()};
11851   Function *MaskedCmpXchg =
11852       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11853   Value *Result = Builder.CreateCall(
11854       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11855   if (XLen == 64)
11856     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11857   return Result;
11858 }
11859 
11860 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT,
11861                                                         EVT DataVT) const {
11862   return false;
11863 }
11864 
11865 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11866                                                EVT VT) const {
11867   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11868     return false;
11869 
11870   switch (FPVT.getSimpleVT().SimpleTy) {
11871   case MVT::f16:
11872     return Subtarget.hasStdExtZfh();
11873   case MVT::f32:
11874     return Subtarget.hasStdExtF();
11875   case MVT::f64:
11876     return Subtarget.hasStdExtD();
11877   default:
11878     return false;
11879   }
11880 }
11881 
11882 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11883   // If we are using the small code model, we can reduce size of jump table
11884   // entry to 4 bytes.
11885   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11886       getTargetMachine().getCodeModel() == CodeModel::Small) {
11887     return MachineJumpTableInfo::EK_Custom32;
11888   }
11889   return TargetLowering::getJumpTableEncoding();
11890 }
11891 
11892 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11893     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11894     unsigned uid, MCContext &Ctx) const {
11895   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11896          getTargetMachine().getCodeModel() == CodeModel::Small);
11897   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11898 }
11899 
11900 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11901                                                      EVT VT) const {
11902   VT = VT.getScalarType();
11903 
11904   if (!VT.isSimple())
11905     return false;
11906 
11907   switch (VT.getSimpleVT().SimpleTy) {
11908   case MVT::f16:
11909     return Subtarget.hasStdExtZfh();
11910   case MVT::f32:
11911     return Subtarget.hasStdExtF();
11912   case MVT::f64:
11913     return Subtarget.hasStdExtD();
11914   default:
11915     break;
11916   }
11917 
11918   return false;
11919 }
11920 
11921 Register RISCVTargetLowering::getExceptionPointerRegister(
11922     const Constant *PersonalityFn) const {
11923   return RISCV::X10;
11924 }
11925 
11926 Register RISCVTargetLowering::getExceptionSelectorRegister(
11927     const Constant *PersonalityFn) const {
11928   return RISCV::X11;
11929 }
11930 
11931 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11932   // Return false to suppress the unnecessary extensions if the LibCall
11933   // arguments or return value is f32 type for LP64 ABI.
11934   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11935   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11936     return false;
11937 
11938   return true;
11939 }
11940 
11941 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11942   if (Subtarget.is64Bit() && Type == MVT::i32)
11943     return true;
11944 
11945   return IsSigned;
11946 }
11947 
11948 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11949                                                  SDValue C) const {
11950   // Check integral scalar types.
11951   if (VT.isScalarInteger()) {
11952     // Omit the optimization if the sub target has the M extension and the data
11953     // size exceeds XLen.
11954     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11955       return false;
11956     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11957       // Break the MUL to a SLLI and an ADD/SUB.
11958       const APInt &Imm = ConstNode->getAPIntValue();
11959       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11960           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11961         return true;
11962       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11963       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11964           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11965            (Imm - 8).isPowerOf2()))
11966         return true;
11967       // Omit the following optimization if the sub target has the M extension
11968       // and the data size >= XLen.
11969       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11970         return false;
11971       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11972       // a pair of LUI/ADDI.
11973       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11974         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11975         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11976             (1 - ImmS).isPowerOf2())
11977         return true;
11978       }
11979     }
11980   }
11981 
11982   return false;
11983 }
11984 
11985 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
11986                                                       SDValue ConstNode) const {
11987   // Let the DAGCombiner decide for vectors.
11988   EVT VT = AddNode.getValueType();
11989   if (VT.isVector())
11990     return true;
11991 
11992   // Let the DAGCombiner decide for larger types.
11993   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11994     return true;
11995 
11996   // It is worse if c1 is simm12 while c1*c2 is not.
11997   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11998   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11999   const APInt &C1 = C1Node->getAPIntValue();
12000   const APInt &C2 = C2Node->getAPIntValue();
12001   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
12002     return false;
12003 
12004   // Default to true and let the DAGCombiner decide.
12005   return true;
12006 }
12007 
12008 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
12009     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
12010     bool *Fast) const {
12011   if (!VT.isVector()) {
12012     if (Fast)
12013       *Fast = false;
12014     return Subtarget.enableUnalignedScalarMem();
12015   }
12016 
12017   // All vector implementations must support element alignment
12018   EVT ElemVT = VT.getVectorElementType();
12019   if (Alignment >= ElemVT.getStoreSize()) {
12020     if (Fast)
12021       *Fast = true;
12022     return true;
12023   }
12024 
12025   return false;
12026 }
12027 
12028 bool RISCVTargetLowering::splitValueIntoRegisterParts(
12029     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
12030     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
12031   bool IsABIRegCopy = CC.has_value();
12032   EVT ValueVT = Val.getValueType();
12033   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
12034     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
12035     // and cast to f32.
12036     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
12037     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
12038     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
12039                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
12040     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
12041     Parts[0] = Val;
12042     return true;
12043   }
12044 
12045   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
12046     LLVMContext &Context = *DAG.getContext();
12047     EVT ValueEltVT = ValueVT.getVectorElementType();
12048     EVT PartEltVT = PartVT.getVectorElementType();
12049     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
12050     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
12051     if (PartVTBitSize % ValueVTBitSize == 0) {
12052       assert(PartVTBitSize >= ValueVTBitSize);
12053       // If the element types are different, bitcast to the same element type of
12054       // PartVT first.
12055       // Give an example here, we want copy a <vscale x 1 x i8> value to
12056       // <vscale x 4 x i16>.
12057       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
12058       // subvector, then we can bitcast to <vscale x 4 x i16>.
12059       if (ValueEltVT != PartEltVT) {
12060         if (PartVTBitSize > ValueVTBitSize) {
12061           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
12062           assert(Count != 0 && "The number of element should not be zero.");
12063           EVT SameEltTypeVT =
12064               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
12065           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
12066                             DAG.getUNDEF(SameEltTypeVT), Val,
12067                             DAG.getVectorIdxConstant(0, DL));
12068         }
12069         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
12070       } else {
12071         Val =
12072             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
12073                         Val, DAG.getVectorIdxConstant(0, DL));
12074       }
12075       Parts[0] = Val;
12076       return true;
12077     }
12078   }
12079   return false;
12080 }
12081 
12082 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
12083     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
12084     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
12085   bool IsABIRegCopy = CC.has_value();
12086   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
12087     SDValue Val = Parts[0];
12088 
12089     // Cast the f32 to i32, truncate to i16, and cast back to f16.
12090     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
12091     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
12092     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
12093     return Val;
12094   }
12095 
12096   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
12097     LLVMContext &Context = *DAG.getContext();
12098     SDValue Val = Parts[0];
12099     EVT ValueEltVT = ValueVT.getVectorElementType();
12100     EVT PartEltVT = PartVT.getVectorElementType();
12101     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
12102     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
12103     if (PartVTBitSize % ValueVTBitSize == 0) {
12104       assert(PartVTBitSize >= ValueVTBitSize);
12105       EVT SameEltTypeVT = ValueVT;
12106       // If the element types are different, convert it to the same element type
12107       // of PartVT.
12108       // Give an example here, we want copy a <vscale x 1 x i8> value from
12109       // <vscale x 4 x i16>.
12110       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
12111       // then we can extract <vscale x 1 x i8>.
12112       if (ValueEltVT != PartEltVT) {
12113         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
12114         assert(Count != 0 && "The number of element should not be zero.");
12115         SameEltTypeVT =
12116             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
12117         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
12118       }
12119       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
12120                         DAG.getVectorIdxConstant(0, DL));
12121       return Val;
12122     }
12123   }
12124   return SDValue();
12125 }
12126 
12127 SDValue
12128 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12129                                    SelectionDAG &DAG,
12130                                    SmallVectorImpl<SDNode *> &Created) const {
12131   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
12132   if (isIntDivCheap(N->getValueType(0), Attr))
12133     return SDValue(N, 0); // Lower SDIV as SDIV
12134 
12135   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
12136          "Unexpected divisor!");
12137 
12138   // Conditional move is needed, so do the transformation iff Zbt is enabled.
12139   if (!Subtarget.hasStdExtZbt())
12140     return SDValue();
12141 
12142   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
12143   // Besides, more critical path instructions will be generated when dividing
12144   // by 2. So we keep using the original DAGs for these cases.
12145   unsigned Lg2 = Divisor.countTrailingZeros();
12146   if (Lg2 == 1 || Lg2 >= 12)
12147     return SDValue();
12148 
12149   // fold (sdiv X, pow2)
12150   EVT VT = N->getValueType(0);
12151   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
12152     return SDValue();
12153 
12154   SDLoc DL(N);
12155   SDValue N0 = N->getOperand(0);
12156   SDValue Zero = DAG.getConstant(0, DL, VT);
12157   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
12158 
12159   // Add (N0 < 0) ? Pow2 - 1 : 0;
12160   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
12161   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
12162   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
12163 
12164   Created.push_back(Cmp.getNode());
12165   Created.push_back(Add.getNode());
12166   Created.push_back(Sel.getNode());
12167 
12168   // Divide by pow2.
12169   SDValue SRA =
12170       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
12171 
12172   // If we're dividing by a positive value, we're done.  Otherwise, we must
12173   // negate the result.
12174   if (Divisor.isNonNegative())
12175     return SRA;
12176 
12177   Created.push_back(SRA.getNode());
12178   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
12179 }
12180 
12181 #define GET_REGISTER_MATCHER
12182 #include "RISCVGenAsmMatcher.inc"
12183 
12184 Register
12185 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
12186                                        const MachineFunction &MF) const {
12187   Register Reg = MatchRegisterAltName(RegName);
12188   if (Reg == RISCV::NoRegister)
12189     Reg = MatchRegisterName(RegName);
12190   if (Reg == RISCV::NoRegister)
12191     report_fatal_error(
12192         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
12193   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
12194   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
12195     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
12196                              StringRef(RegName) + "\"."));
12197   return Reg;
12198 }
12199 
12200 namespace llvm {
12201 namespace RISCVVIntrinsicsTable {
12202 
12203 #define GET_RISCVVIntrinsicsTable_IMPL
12204 #include "RISCVGenSearchableTables.inc"
12205 
12206 } // namespace RISCVVIntrinsicsTable
12207 
12208 } // namespace llvm
12209