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.getRealMinVLen() < 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 
7007     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
7008 
7009     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7010 
7011     // Freeze the source so we can increase it's use count.
7012     Src = DAG.getFreeze(Src);
7013 
7014     // Copy sign bit to all bits using the sraiw pattern.
7015     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
7016                                    DAG.getValueType(MVT::i32));
7017     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
7018                            DAG.getConstant(31, DL, MVT::i64));
7019 
7020     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
7021     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
7022 
7023     // NOTE: The result is only required to be anyextended, but sext is
7024     // consistent with type legalization of sub.
7025     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
7026                          DAG.getValueType(MVT::i32));
7027     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
7028     return;
7029   }
7030   case ISD::BITCAST: {
7031     EVT VT = N->getValueType(0);
7032     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
7033     SDValue Op0 = N->getOperand(0);
7034     EVT Op0VT = Op0.getValueType();
7035     MVT XLenVT = Subtarget.getXLenVT();
7036     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
7037       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
7038       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
7039     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
7040                Subtarget.hasStdExtF()) {
7041       SDValue FPConv =
7042           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
7043       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
7044     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
7045                isTypeLegal(Op0VT)) {
7046       // Custom-legalize bitcasts from fixed-length vector types to illegal
7047       // scalar types in order to improve codegen. Bitcast the vector to a
7048       // one-element vector type whose element type is the same as the result
7049       // type, and extract the first element.
7050       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
7051       if (isTypeLegal(BVT)) {
7052         SDValue BVec = DAG.getBitcast(BVT, Op0);
7053         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
7054                                       DAG.getConstant(0, DL, XLenVT)));
7055       }
7056     }
7057     break;
7058   }
7059   case RISCVISD::GREV:
7060   case RISCVISD::GORC:
7061   case RISCVISD::SHFL: {
7062     MVT VT = N->getSimpleValueType(0);
7063     MVT XLenVT = Subtarget.getXLenVT();
7064     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
7065            "Unexpected custom legalisation");
7066     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
7067     assert((Subtarget.hasStdExtZbp() ||
7068             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
7069              N->getConstantOperandVal(1) == 7)) &&
7070            "Unexpected extension");
7071     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7072     SDValue NewOp1 =
7073         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
7074     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
7075     // ReplaceNodeResults requires we maintain the same type for the return
7076     // value.
7077     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
7078     break;
7079   }
7080   case ISD::BSWAP:
7081   case ISD::BITREVERSE: {
7082     MVT VT = N->getSimpleValueType(0);
7083     MVT XLenVT = Subtarget.getXLenVT();
7084     assert((VT == MVT::i8 || VT == MVT::i16 ||
7085             (VT == MVT::i32 && Subtarget.is64Bit())) &&
7086            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
7087     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7088     unsigned Imm = VT.getSizeInBits() - 1;
7089     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
7090     if (N->getOpcode() == ISD::BSWAP)
7091       Imm &= ~0x7U;
7092     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
7093                                 DAG.getConstant(Imm, DL, XLenVT));
7094     // ReplaceNodeResults requires we maintain the same type for the return
7095     // value.
7096     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
7097     break;
7098   }
7099   case ISD::FSHL:
7100   case ISD::FSHR: {
7101     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7102            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
7103     SDValue NewOp0 =
7104         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7105     SDValue NewOp1 =
7106         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7107     SDValue NewShAmt =
7108         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7109     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
7110     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
7111     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
7112                            DAG.getConstant(0x1f, DL, MVT::i64));
7113     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
7114     // instruction use different orders. fshl will return its first operand for
7115     // shift of zero, fshr will return its second operand. fsl and fsr both
7116     // return rs1 so the ISD nodes need to have different operand orders.
7117     // Shift amount is in rs2.
7118     unsigned Opc = RISCVISD::FSLW;
7119     if (N->getOpcode() == ISD::FSHR) {
7120       std::swap(NewOp0, NewOp1);
7121       Opc = RISCVISD::FSRW;
7122     }
7123     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
7124     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
7125     break;
7126   }
7127   case ISD::EXTRACT_VECTOR_ELT: {
7128     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
7129     // type is illegal (currently only vXi64 RV32).
7130     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
7131     // transferred to the destination register. We issue two of these from the
7132     // upper- and lower- halves of the SEW-bit vector element, slid down to the
7133     // first element.
7134     SDValue Vec = N->getOperand(0);
7135     SDValue Idx = N->getOperand(1);
7136 
7137     // The vector type hasn't been legalized yet so we can't issue target
7138     // specific nodes if it needs legalization.
7139     // FIXME: We would manually legalize if it's important.
7140     if (!isTypeLegal(Vec.getValueType()))
7141       return;
7142 
7143     MVT VecVT = Vec.getSimpleValueType();
7144 
7145     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7146            VecVT.getVectorElementType() == MVT::i64 &&
7147            "Unexpected EXTRACT_VECTOR_ELT legalization");
7148 
7149     // If this is a fixed vector, we need to convert it to a scalable vector.
7150     MVT ContainerVT = VecVT;
7151     if (VecVT.isFixedLengthVector()) {
7152       ContainerVT = getContainerForFixedLengthVector(VecVT);
7153       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7154     }
7155 
7156     MVT XLenVT = Subtarget.getXLenVT();
7157 
7158     // Use a VL of 1 to avoid processing more elements than we need.
7159     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7160     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
7161 
7162     // Unless the index is known to be 0, we must slide the vector down to get
7163     // the desired element into index 0.
7164     if (!isNullConstant(Idx)) {
7165       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7166                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7167     }
7168 
7169     // Extract the lower XLEN bits of the correct vector element.
7170     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7171 
7172     // To extract the upper XLEN bits of the vector element, shift the first
7173     // element right by 32 bits and re-extract the lower XLEN bits.
7174     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7175                                      DAG.getUNDEF(ContainerVT),
7176                                      DAG.getConstant(32, DL, XLenVT), VL);
7177     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7178                                  ThirtyTwoV, Mask, VL);
7179 
7180     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7181 
7182     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7183     break;
7184   }
7185   case ISD::INTRINSIC_WO_CHAIN: {
7186     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7187     switch (IntNo) {
7188     default:
7189       llvm_unreachable(
7190           "Don't know how to custom type legalize this intrinsic!");
7191     case Intrinsic::riscv_grev:
7192     case Intrinsic::riscv_gorc: {
7193       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7194              "Unexpected custom legalisation");
7195       SDValue NewOp1 =
7196           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7197       SDValue NewOp2 =
7198           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7199       unsigned Opc =
7200           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7201       // If the control is a constant, promote the node by clearing any extra
7202       // bits bits in the control. isel will form greviw/gorciw if the result is
7203       // sign extended.
7204       if (isa<ConstantSDNode>(NewOp2)) {
7205         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7206                              DAG.getConstant(0x1f, DL, MVT::i64));
7207         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7208       }
7209       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7210       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7211       break;
7212     }
7213     case Intrinsic::riscv_bcompress:
7214     case Intrinsic::riscv_bdecompress:
7215     case Intrinsic::riscv_bfp:
7216     case Intrinsic::riscv_fsl:
7217     case Intrinsic::riscv_fsr: {
7218       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7219              "Unexpected custom legalisation");
7220       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7221       break;
7222     }
7223     case Intrinsic::riscv_orc_b: {
7224       // Lower to the GORCI encoding for orc.b with the operand extended.
7225       SDValue NewOp =
7226           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7227       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7228                                 DAG.getConstant(7, DL, MVT::i64));
7229       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7230       return;
7231     }
7232     case Intrinsic::riscv_shfl:
7233     case Intrinsic::riscv_unshfl: {
7234       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7235              "Unexpected custom legalisation");
7236       SDValue NewOp1 =
7237           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7238       SDValue NewOp2 =
7239           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7240       unsigned Opc =
7241           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7242       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7243       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7244       // will be shuffled the same way as the lower 32 bit half, but the two
7245       // halves won't cross.
7246       if (isa<ConstantSDNode>(NewOp2)) {
7247         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7248                              DAG.getConstant(0xf, DL, MVT::i64));
7249         Opc =
7250             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7251       }
7252       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7253       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7254       break;
7255     }
7256     case Intrinsic::riscv_vmv_x_s: {
7257       EVT VT = N->getValueType(0);
7258       MVT XLenVT = Subtarget.getXLenVT();
7259       if (VT.bitsLT(XLenVT)) {
7260         // Simple case just extract using vmv.x.s and truncate.
7261         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7262                                       Subtarget.getXLenVT(), N->getOperand(1));
7263         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7264         return;
7265       }
7266 
7267       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7268              "Unexpected custom legalization");
7269 
7270       // We need to do the move in two steps.
7271       SDValue Vec = N->getOperand(1);
7272       MVT VecVT = Vec.getSimpleValueType();
7273 
7274       // First extract the lower XLEN bits of the element.
7275       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7276 
7277       // To extract the upper XLEN bits of the vector element, shift the first
7278       // element right by 32 bits and re-extract the lower XLEN bits.
7279       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7280       SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG);
7281 
7282       SDValue ThirtyTwoV =
7283           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7284                       DAG.getConstant(32, DL, XLenVT), VL);
7285       SDValue LShr32 =
7286           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7287       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7288 
7289       Results.push_back(
7290           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7291       break;
7292     }
7293     }
7294     break;
7295   }
7296   case ISD::VECREDUCE_ADD:
7297   case ISD::VECREDUCE_AND:
7298   case ISD::VECREDUCE_OR:
7299   case ISD::VECREDUCE_XOR:
7300   case ISD::VECREDUCE_SMAX:
7301   case ISD::VECREDUCE_UMAX:
7302   case ISD::VECREDUCE_SMIN:
7303   case ISD::VECREDUCE_UMIN:
7304     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7305       Results.push_back(V);
7306     break;
7307   case ISD::VP_REDUCE_ADD:
7308   case ISD::VP_REDUCE_AND:
7309   case ISD::VP_REDUCE_OR:
7310   case ISD::VP_REDUCE_XOR:
7311   case ISD::VP_REDUCE_SMAX:
7312   case ISD::VP_REDUCE_UMAX:
7313   case ISD::VP_REDUCE_SMIN:
7314   case ISD::VP_REDUCE_UMIN:
7315     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7316       Results.push_back(V);
7317     break;
7318   case ISD::FLT_ROUNDS_: {
7319     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7320     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7321     Results.push_back(Res.getValue(0));
7322     Results.push_back(Res.getValue(1));
7323     break;
7324   }
7325   }
7326 }
7327 
7328 // A structure to hold one of the bit-manipulation patterns below. Together, a
7329 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7330 //   (or (and (shl x, 1), 0xAAAAAAAA),
7331 //       (and (srl x, 1), 0x55555555))
7332 struct RISCVBitmanipPat {
7333   SDValue Op;
7334   unsigned ShAmt;
7335   bool IsSHL;
7336 
7337   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7338     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7339   }
7340 };
7341 
7342 // Matches patterns of the form
7343 //   (and (shl x, C2), (C1 << C2))
7344 //   (and (srl x, C2), C1)
7345 //   (shl (and x, C1), C2)
7346 //   (srl (and x, (C1 << C2)), C2)
7347 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7348 // The expected masks for each shift amount are specified in BitmanipMasks where
7349 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7350 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7351 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7352 // XLen is 64.
7353 static Optional<RISCVBitmanipPat>
7354 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7355   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7356          "Unexpected number of masks");
7357   Optional<uint64_t> Mask;
7358   // Optionally consume a mask around the shift operation.
7359   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7360     Mask = Op.getConstantOperandVal(1);
7361     Op = Op.getOperand(0);
7362   }
7363   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7364     return None;
7365   bool IsSHL = Op.getOpcode() == ISD::SHL;
7366 
7367   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7368     return None;
7369   uint64_t ShAmt = Op.getConstantOperandVal(1);
7370 
7371   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7372   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7373     return None;
7374   // If we don't have enough masks for 64 bit, then we must be trying to
7375   // match SHFL so we're only allowed to shift 1/4 of the width.
7376   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7377     return None;
7378 
7379   SDValue Src = Op.getOperand(0);
7380 
7381   // The expected mask is shifted left when the AND is found around SHL
7382   // patterns.
7383   //   ((x >> 1) & 0x55555555)
7384   //   ((x << 1) & 0xAAAAAAAA)
7385   bool SHLExpMask = IsSHL;
7386 
7387   if (!Mask) {
7388     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7389     // the mask is all ones: consume that now.
7390     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7391       Mask = Src.getConstantOperandVal(1);
7392       Src = Src.getOperand(0);
7393       // The expected mask is now in fact shifted left for SRL, so reverse the
7394       // decision.
7395       //   ((x & 0xAAAAAAAA) >> 1)
7396       //   ((x & 0x55555555) << 1)
7397       SHLExpMask = !SHLExpMask;
7398     } else {
7399       // Use a default shifted mask of all-ones if there's no AND, truncated
7400       // down to the expected width. This simplifies the logic later on.
7401       Mask = maskTrailingOnes<uint64_t>(Width);
7402       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7403     }
7404   }
7405 
7406   unsigned MaskIdx = Log2_32(ShAmt);
7407   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7408 
7409   if (SHLExpMask)
7410     ExpMask <<= ShAmt;
7411 
7412   if (Mask != ExpMask)
7413     return None;
7414 
7415   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7416 }
7417 
7418 // Matches any of the following bit-manipulation patterns:
7419 //   (and (shl x, 1), (0x55555555 << 1))
7420 //   (and (srl x, 1), 0x55555555)
7421 //   (shl (and x, 0x55555555), 1)
7422 //   (srl (and x, (0x55555555 << 1)), 1)
7423 // where the shift amount and mask may vary thus:
7424 //   [1]  = 0x55555555 / 0xAAAAAAAA
7425 //   [2]  = 0x33333333 / 0xCCCCCCCC
7426 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7427 //   [8]  = 0x00FF00FF / 0xFF00FF00
7428 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7429 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7430 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7431   // These are the unshifted masks which we use to match bit-manipulation
7432   // patterns. They may be shifted left in certain circumstances.
7433   static const uint64_t BitmanipMasks[] = {
7434       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7435       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7436 
7437   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7438 }
7439 
7440 // Try to fold (<bop> x, (reduction.<bop> vec, start))
7441 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) {
7442   auto BinOpToRVVReduce = [](unsigned Opc) {
7443     switch (Opc) {
7444     default:
7445       llvm_unreachable("Unhandled binary to transfrom reduction");
7446     case ISD::ADD:
7447       return RISCVISD::VECREDUCE_ADD_VL;
7448     case ISD::UMAX:
7449       return RISCVISD::VECREDUCE_UMAX_VL;
7450     case ISD::SMAX:
7451       return RISCVISD::VECREDUCE_SMAX_VL;
7452     case ISD::UMIN:
7453       return RISCVISD::VECREDUCE_UMIN_VL;
7454     case ISD::SMIN:
7455       return RISCVISD::VECREDUCE_SMIN_VL;
7456     case ISD::AND:
7457       return RISCVISD::VECREDUCE_AND_VL;
7458     case ISD::OR:
7459       return RISCVISD::VECREDUCE_OR_VL;
7460     case ISD::XOR:
7461       return RISCVISD::VECREDUCE_XOR_VL;
7462     case ISD::FADD:
7463       return RISCVISD::VECREDUCE_FADD_VL;
7464     case ISD::FMAXNUM:
7465       return RISCVISD::VECREDUCE_FMAX_VL;
7466     case ISD::FMINNUM:
7467       return RISCVISD::VECREDUCE_FMIN_VL;
7468     }
7469   };
7470 
7471   auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) {
7472     return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7473            isNullConstant(V.getOperand(1)) &&
7474            V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc);
7475   };
7476 
7477   unsigned Opc = N->getOpcode();
7478   unsigned ReduceIdx;
7479   if (IsReduction(N->getOperand(0), Opc))
7480     ReduceIdx = 0;
7481   else if (IsReduction(N->getOperand(1), Opc))
7482     ReduceIdx = 1;
7483   else
7484     return SDValue();
7485 
7486   // Skip if FADD disallows reassociation but the combiner needs.
7487   if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation())
7488     return SDValue();
7489 
7490   SDValue Extract = N->getOperand(ReduceIdx);
7491   SDValue Reduce = Extract.getOperand(0);
7492   if (!Reduce.hasOneUse())
7493     return SDValue();
7494 
7495   SDValue ScalarV = Reduce.getOperand(2);
7496 
7497   // Make sure that ScalarV is a splat with VL=1.
7498   if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL &&
7499       ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL &&
7500       ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL)
7501     return SDValue();
7502 
7503   if (!isOneConstant(ScalarV.getOperand(2)))
7504     return SDValue();
7505 
7506   // TODO: Deal with value other than neutral element.
7507   auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) {
7508     if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() &&
7509         isNullFPConstant(V))
7510       return true;
7511     return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(),
7512                                  N->getFlags()) == V;
7513   };
7514 
7515   // Check the scalar of ScalarV is neutral element
7516   if (!IsRVVNeutralElement(N, ScalarV.getOperand(1)))
7517     return SDValue();
7518 
7519   if (!ScalarV.hasOneUse())
7520     return SDValue();
7521 
7522   EVT SplatVT = ScalarV.getValueType();
7523   SDValue NewStart = N->getOperand(1 - ReduceIdx);
7524   unsigned SplatOpc = RISCVISD::VFMV_S_F_VL;
7525   if (SplatVT.isInteger()) {
7526     auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode());
7527     if (!C || C->isZero() || !isInt<5>(C->getSExtValue()))
7528       SplatOpc = RISCVISD::VMV_S_X_VL;
7529     else
7530       SplatOpc = RISCVISD::VMV_V_X_VL;
7531   }
7532 
7533   SDValue NewScalarV =
7534       DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart,
7535                   ScalarV.getOperand(2));
7536   SDValue NewReduce =
7537       DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(),
7538                   Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV,
7539                   Reduce.getOperand(3), Reduce.getOperand(4));
7540   return DAG.getNode(Extract.getOpcode(), SDLoc(Extract),
7541                      Extract.getValueType(), NewReduce, Extract.getOperand(1));
7542 }
7543 
7544 // Match the following pattern as a GREVI(W) operation
7545 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7546 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7547                                const RISCVSubtarget &Subtarget) {
7548   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7549   EVT VT = Op.getValueType();
7550 
7551   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7552     auto LHS = matchGREVIPat(Op.getOperand(0));
7553     auto RHS = matchGREVIPat(Op.getOperand(1));
7554     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7555       SDLoc DL(Op);
7556       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7557                          DAG.getConstant(LHS->ShAmt, DL, VT));
7558     }
7559   }
7560   return SDValue();
7561 }
7562 
7563 // Matches any the following pattern as a GORCI(W) operation
7564 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7565 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7566 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7567 // Note that with the variant of 3.,
7568 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7569 // the inner pattern will first be matched as GREVI and then the outer
7570 // pattern will be matched to GORC via the first rule above.
7571 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7572 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7573                                const RISCVSubtarget &Subtarget) {
7574   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7575   EVT VT = Op.getValueType();
7576 
7577   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7578     SDLoc DL(Op);
7579     SDValue Op0 = Op.getOperand(0);
7580     SDValue Op1 = Op.getOperand(1);
7581 
7582     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7583       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7584           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7585           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7586         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7587       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7588       if ((Reverse.getOpcode() == ISD::ROTL ||
7589            Reverse.getOpcode() == ISD::ROTR) &&
7590           Reverse.getOperand(0) == X &&
7591           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7592         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7593         if (RotAmt == (VT.getSizeInBits() / 2))
7594           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7595                              DAG.getConstant(RotAmt, DL, VT));
7596       }
7597       return SDValue();
7598     };
7599 
7600     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7601     if (SDValue V = MatchOROfReverse(Op0, Op1))
7602       return V;
7603     if (SDValue V = MatchOROfReverse(Op1, Op0))
7604       return V;
7605 
7606     // OR is commutable so canonicalize its OR operand to the left
7607     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7608       std::swap(Op0, Op1);
7609     if (Op0.getOpcode() != ISD::OR)
7610       return SDValue();
7611     SDValue OrOp0 = Op0.getOperand(0);
7612     SDValue OrOp1 = Op0.getOperand(1);
7613     auto LHS = matchGREVIPat(OrOp0);
7614     // OR is commutable so swap the operands and try again: x might have been
7615     // on the left
7616     if (!LHS) {
7617       std::swap(OrOp0, OrOp1);
7618       LHS = matchGREVIPat(OrOp0);
7619     }
7620     auto RHS = matchGREVIPat(Op1);
7621     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7622       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7623                          DAG.getConstant(LHS->ShAmt, DL, VT));
7624     }
7625   }
7626   return SDValue();
7627 }
7628 
7629 // Matches any of the following bit-manipulation patterns:
7630 //   (and (shl x, 1), (0x22222222 << 1))
7631 //   (and (srl x, 1), 0x22222222)
7632 //   (shl (and x, 0x22222222), 1)
7633 //   (srl (and x, (0x22222222 << 1)), 1)
7634 // where the shift amount and mask may vary thus:
7635 //   [1]  = 0x22222222 / 0x44444444
7636 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7637 //   [4]  = 0x00F000F0 / 0x0F000F00
7638 //   [8]  = 0x0000FF00 / 0x00FF0000
7639 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7640 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7641   // These are the unshifted masks which we use to match bit-manipulation
7642   // patterns. They may be shifted left in certain circumstances.
7643   static const uint64_t BitmanipMasks[] = {
7644       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7645       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7646 
7647   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7648 }
7649 
7650 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7651 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7652                                const RISCVSubtarget &Subtarget) {
7653   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7654   EVT VT = Op.getValueType();
7655 
7656   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7657     return SDValue();
7658 
7659   SDValue Op0 = Op.getOperand(0);
7660   SDValue Op1 = Op.getOperand(1);
7661 
7662   // Or is commutable so canonicalize the second OR to the LHS.
7663   if (Op0.getOpcode() != ISD::OR)
7664     std::swap(Op0, Op1);
7665   if (Op0.getOpcode() != ISD::OR)
7666     return SDValue();
7667 
7668   // We found an inner OR, so our operands are the operands of the inner OR
7669   // and the other operand of the outer OR.
7670   SDValue A = Op0.getOperand(0);
7671   SDValue B = Op0.getOperand(1);
7672   SDValue C = Op1;
7673 
7674   auto Match1 = matchSHFLPat(A);
7675   auto Match2 = matchSHFLPat(B);
7676 
7677   // If neither matched, we failed.
7678   if (!Match1 && !Match2)
7679     return SDValue();
7680 
7681   // We had at least one match. if one failed, try the remaining C operand.
7682   if (!Match1) {
7683     std::swap(A, C);
7684     Match1 = matchSHFLPat(A);
7685     if (!Match1)
7686       return SDValue();
7687   } else if (!Match2) {
7688     std::swap(B, C);
7689     Match2 = matchSHFLPat(B);
7690     if (!Match2)
7691       return SDValue();
7692   }
7693   assert(Match1 && Match2);
7694 
7695   // Make sure our matches pair up.
7696   if (!Match1->formsPairWith(*Match2))
7697     return SDValue();
7698 
7699   // All the remains is to make sure C is an AND with the same input, that masks
7700   // out the bits that are being shuffled.
7701   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7702       C.getOperand(0) != Match1->Op)
7703     return SDValue();
7704 
7705   uint64_t Mask = C.getConstantOperandVal(1);
7706 
7707   static const uint64_t BitmanipMasks[] = {
7708       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7709       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7710   };
7711 
7712   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7713   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7714   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7715 
7716   if (Mask != ExpMask)
7717     return SDValue();
7718 
7719   SDLoc DL(Op);
7720   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7721                      DAG.getConstant(Match1->ShAmt, DL, VT));
7722 }
7723 
7724 // Optimize (add (shl x, c0), (shl y, c1)) ->
7725 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7726 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7727                                   const RISCVSubtarget &Subtarget) {
7728   // Perform this optimization only in the zba extension.
7729   if (!Subtarget.hasStdExtZba())
7730     return SDValue();
7731 
7732   // Skip for vector types and larger types.
7733   EVT VT = N->getValueType(0);
7734   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7735     return SDValue();
7736 
7737   // The two operand nodes must be SHL and have no other use.
7738   SDValue N0 = N->getOperand(0);
7739   SDValue N1 = N->getOperand(1);
7740   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7741       !N0->hasOneUse() || !N1->hasOneUse())
7742     return SDValue();
7743 
7744   // Check c0 and c1.
7745   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7746   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7747   if (!N0C || !N1C)
7748     return SDValue();
7749   int64_t C0 = N0C->getSExtValue();
7750   int64_t C1 = N1C->getSExtValue();
7751   if (C0 <= 0 || C1 <= 0)
7752     return SDValue();
7753 
7754   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7755   int64_t Bits = std::min(C0, C1);
7756   int64_t Diff = std::abs(C0 - C1);
7757   if (Diff != 1 && Diff != 2 && Diff != 3)
7758     return SDValue();
7759 
7760   // Build nodes.
7761   SDLoc DL(N);
7762   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7763   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7764   SDValue NA0 =
7765       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7766   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7767   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7768 }
7769 
7770 // Combine
7771 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7772 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7773 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7774 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7775 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7776 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7777 // The grev patterns represents BSWAP.
7778 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7779 // off the grev.
7780 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7781                                           const RISCVSubtarget &Subtarget) {
7782   bool IsWInstruction =
7783       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7784   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7785           IsWInstruction) &&
7786          "Unexpected opcode!");
7787   SDValue Src = N->getOperand(0);
7788   EVT VT = N->getValueType(0);
7789   SDLoc DL(N);
7790 
7791   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7792     return SDValue();
7793 
7794   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7795       !isa<ConstantSDNode>(Src.getOperand(1)))
7796     return SDValue();
7797 
7798   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7799   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7800 
7801   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7802   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7803   unsigned ShAmt1 = N->getConstantOperandVal(1);
7804   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7805   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7806     return SDValue();
7807 
7808   Src = Src.getOperand(0);
7809 
7810   // Toggle bit the MSB of the shift.
7811   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7812   if (CombinedShAmt == 0)
7813     return Src;
7814 
7815   SDValue Res = DAG.getNode(
7816       RISCVISD::GREV, DL, VT, Src,
7817       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7818   if (!IsWInstruction)
7819     return Res;
7820 
7821   // Sign extend the result to match the behavior of the rotate. This will be
7822   // selected to GREVIW in isel.
7823   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7824                      DAG.getValueType(MVT::i32));
7825 }
7826 
7827 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7828 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7829 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7830 // not undo itself, but they are redundant.
7831 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7832   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7833   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7834   SDValue Src = N->getOperand(0);
7835 
7836   if (Src.getOpcode() != N->getOpcode())
7837     return SDValue();
7838 
7839   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7840       !isa<ConstantSDNode>(Src.getOperand(1)))
7841     return SDValue();
7842 
7843   unsigned ShAmt1 = N->getConstantOperandVal(1);
7844   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7845   Src = Src.getOperand(0);
7846 
7847   unsigned CombinedShAmt;
7848   if (IsGORC)
7849     CombinedShAmt = ShAmt1 | ShAmt2;
7850   else
7851     CombinedShAmt = ShAmt1 ^ ShAmt2;
7852 
7853   if (CombinedShAmt == 0)
7854     return Src;
7855 
7856   SDLoc DL(N);
7857   return DAG.getNode(
7858       N->getOpcode(), DL, N->getValueType(0), Src,
7859       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7860 }
7861 
7862 // Combine a constant select operand into its use:
7863 //
7864 // (and (select cond, -1, c), x)
7865 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7866 // (or  (select cond, 0, c), x)
7867 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7868 // (xor (select cond, 0, c), x)
7869 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7870 // (add (select cond, 0, c), x)
7871 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7872 // (sub x, (select cond, 0, c))
7873 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7874 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7875                                    SelectionDAG &DAG, bool AllOnes) {
7876   EVT VT = N->getValueType(0);
7877 
7878   // Skip vectors.
7879   if (VT.isVector())
7880     return SDValue();
7881 
7882   if ((Slct.getOpcode() != ISD::SELECT &&
7883        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7884       !Slct.hasOneUse())
7885     return SDValue();
7886 
7887   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7888     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7889   };
7890 
7891   bool SwapSelectOps;
7892   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7893   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7894   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7895   SDValue NonConstantVal;
7896   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7897     SwapSelectOps = false;
7898     NonConstantVal = FalseVal;
7899   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7900     SwapSelectOps = true;
7901     NonConstantVal = TrueVal;
7902   } else
7903     return SDValue();
7904 
7905   // Slct is now know to be the desired identity constant when CC is true.
7906   TrueVal = OtherOp;
7907   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7908   // Unless SwapSelectOps says the condition should be false.
7909   if (SwapSelectOps)
7910     std::swap(TrueVal, FalseVal);
7911 
7912   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7913     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7914                        {Slct.getOperand(0), Slct.getOperand(1),
7915                         Slct.getOperand(2), TrueVal, FalseVal});
7916 
7917   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7918                      {Slct.getOperand(0), TrueVal, FalseVal});
7919 }
7920 
7921 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7922 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7923                                               bool AllOnes) {
7924   SDValue N0 = N->getOperand(0);
7925   SDValue N1 = N->getOperand(1);
7926   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7927     return Result;
7928   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7929     return Result;
7930   return SDValue();
7931 }
7932 
7933 // Transform (add (mul x, c0), c1) ->
7934 //           (add (mul (add x, c1/c0), c0), c1%c0).
7935 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7936 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7937 // to an infinite loop in DAGCombine if transformed.
7938 // Or transform (add (mul x, c0), c1) ->
7939 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7940 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7941 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7942 // lead to an infinite loop in DAGCombine if transformed.
7943 // Or transform (add (mul x, c0), c1) ->
7944 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7945 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7946 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7947 // lead to an infinite loop in DAGCombine if transformed.
7948 // Or transform (add (mul x, c0), c1) ->
7949 //              (mul (add x, c1/c0), c0).
7950 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7951 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7952                                      const RISCVSubtarget &Subtarget) {
7953   // Skip for vector types and larger types.
7954   EVT VT = N->getValueType(0);
7955   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7956     return SDValue();
7957   // The first operand node must be a MUL and has no other use.
7958   SDValue N0 = N->getOperand(0);
7959   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7960     return SDValue();
7961   // Check if c0 and c1 match above conditions.
7962   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7963   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7964   if (!N0C || !N1C)
7965     return SDValue();
7966   // If N0C has multiple uses it's possible one of the cases in
7967   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7968   // in an infinite loop.
7969   if (!N0C->hasOneUse())
7970     return SDValue();
7971   int64_t C0 = N0C->getSExtValue();
7972   int64_t C1 = N1C->getSExtValue();
7973   int64_t CA, CB;
7974   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7975     return SDValue();
7976   // Search for proper CA (non-zero) and CB that both are simm12.
7977   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7978       !isInt<12>(C0 * (C1 / C0))) {
7979     CA = C1 / C0;
7980     CB = C1 % C0;
7981   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7982              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7983     CA = C1 / C0 + 1;
7984     CB = C1 % C0 - C0;
7985   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7986              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7987     CA = C1 / C0 - 1;
7988     CB = C1 % C0 + C0;
7989   } else
7990     return SDValue();
7991   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7992   SDLoc DL(N);
7993   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7994                              DAG.getConstant(CA, DL, VT));
7995   SDValue New1 =
7996       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7997   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7998 }
7999 
8000 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
8001                                  const RISCVSubtarget &Subtarget) {
8002   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
8003     return V;
8004   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
8005     return V;
8006   if (SDValue V = combineBinOpToReduce(N, DAG))
8007     return V;
8008   // fold (add (select lhs, rhs, cc, 0, y), x) ->
8009   //      (select lhs, rhs, cc, x, (add x, y))
8010   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8011 }
8012 
8013 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
8014   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
8015   //      (select lhs, rhs, cc, x, (sub x, y))
8016   SDValue N0 = N->getOperand(0);
8017   SDValue N1 = N->getOperand(1);
8018   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
8019 }
8020 
8021 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
8022                                  const RISCVSubtarget &Subtarget) {
8023   SDValue N0 = N->getOperand(0);
8024   // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero
8025   // extending X. This is safe since we only need the LSB after the shift and
8026   // shift amounts larger than 31 would produce poison. If we wait until
8027   // type legalization, we'll create RISCVISD::SRLW and we can't recover it
8028   // to use a BEXT instruction.
8029   if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() &&
8030       N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) &&
8031       N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) &&
8032       N0.hasOneUse()) {
8033     SDLoc DL(N);
8034     SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0));
8035     SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1));
8036     SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1);
8037     SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl,
8038                               DAG.getConstant(1, DL, MVT::i64));
8039     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And);
8040   }
8041 
8042   if (SDValue V = combineBinOpToReduce(N, DAG))
8043     return V;
8044 
8045   // fold (and (select lhs, rhs, cc, -1, y), x) ->
8046   //      (select lhs, rhs, cc, x, (and x, y))
8047   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
8048 }
8049 
8050 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
8051                                 const RISCVSubtarget &Subtarget) {
8052   if (Subtarget.hasStdExtZbp()) {
8053     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
8054       return GREV;
8055     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
8056       return GORC;
8057     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
8058       return SHFL;
8059   }
8060 
8061   if (SDValue V = combineBinOpToReduce(N, DAG))
8062     return V;
8063   // fold (or (select cond, 0, y), x) ->
8064   //      (select cond, x, (or x, y))
8065   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8066 }
8067 
8068 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
8069   SDValue N0 = N->getOperand(0);
8070   SDValue N1 = N->getOperand(1);
8071 
8072   // fold (xor (sllw 1, x), -1) -> (rolw ~1, x)
8073   // NOTE: Assumes ROL being legal means ROLW is legal.
8074   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8075   if (N0.getOpcode() == RISCVISD::SLLW &&
8076       isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) &&
8077       TLI.isOperationLegal(ISD::ROTL, MVT::i64)) {
8078     SDLoc DL(N);
8079     return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64,
8080                        DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1));
8081   }
8082 
8083   if (SDValue V = combineBinOpToReduce(N, DAG))
8084     return V;
8085   // fold (xor (select cond, 0, y), x) ->
8086   //      (select cond, x, (xor x, y))
8087   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8088 }
8089 
8090 static SDValue
8091 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
8092                                 const RISCVSubtarget &Subtarget) {
8093   SDValue Src = N->getOperand(0);
8094   EVT VT = N->getValueType(0);
8095 
8096   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
8097   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8098       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
8099     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
8100                        Src.getOperand(0));
8101 
8102   // Fold (i64 (sext_inreg (abs X), i32)) ->
8103   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
8104   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
8105   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
8106   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
8107   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
8108   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
8109   // may get combined into an earlier operation so we need to use
8110   // ComputeNumSignBits.
8111   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
8112   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
8113   // we can't assume that X has 33 sign bits. We must check.
8114   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
8115       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
8116       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
8117       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
8118     SDLoc DL(N);
8119     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
8120     SDValue Neg =
8121         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
8122     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
8123                       DAG.getValueType(MVT::i32));
8124     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
8125   }
8126 
8127   return SDValue();
8128 }
8129 
8130 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
8131 // vwadd(u).vv/vx or vwsub(u).vv/vx.
8132 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
8133                                              bool Commute = false) {
8134   assert((N->getOpcode() == RISCVISD::ADD_VL ||
8135           N->getOpcode() == RISCVISD::SUB_VL) &&
8136          "Unexpected opcode");
8137   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
8138   SDValue Op0 = N->getOperand(0);
8139   SDValue Op1 = N->getOperand(1);
8140   if (Commute)
8141     std::swap(Op0, Op1);
8142 
8143   MVT VT = N->getSimpleValueType(0);
8144 
8145   // Determine the narrow size for a widening add/sub.
8146   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8147   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8148                                   VT.getVectorElementCount());
8149 
8150   SDValue Mask = N->getOperand(2);
8151   SDValue VL = N->getOperand(3);
8152 
8153   SDLoc DL(N);
8154 
8155   // If the RHS is a sext or zext, we can form a widening op.
8156   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
8157        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
8158       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
8159     unsigned ExtOpc = Op1.getOpcode();
8160     Op1 = Op1.getOperand(0);
8161     // Re-introduce narrower extends if needed.
8162     if (Op1.getValueType() != NarrowVT)
8163       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8164 
8165     unsigned WOpc;
8166     if (ExtOpc == RISCVISD::VSEXT_VL)
8167       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
8168     else
8169       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
8170 
8171     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
8172   }
8173 
8174   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
8175   // sext/zext?
8176 
8177   return SDValue();
8178 }
8179 
8180 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
8181 // vwsub(u).vv/vx.
8182 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
8183   SDValue Op0 = N->getOperand(0);
8184   SDValue Op1 = N->getOperand(1);
8185   SDValue Mask = N->getOperand(2);
8186   SDValue VL = N->getOperand(3);
8187 
8188   MVT VT = N->getSimpleValueType(0);
8189   MVT NarrowVT = Op1.getSimpleValueType();
8190   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
8191 
8192   unsigned VOpc;
8193   switch (N->getOpcode()) {
8194   default: llvm_unreachable("Unexpected opcode");
8195   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
8196   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
8197   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
8198   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
8199   }
8200 
8201   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8202                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
8203 
8204   SDLoc DL(N);
8205 
8206   // If the LHS is a sext or zext, we can narrow this op to the same size as
8207   // the RHS.
8208   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
8209        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
8210       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
8211     unsigned ExtOpc = Op0.getOpcode();
8212     Op0 = Op0.getOperand(0);
8213     // Re-introduce narrower extends if needed.
8214     if (Op0.getValueType() != NarrowVT)
8215       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8216     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
8217   }
8218 
8219   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8220                N->getOpcode() == RISCVISD::VWADDU_W_VL;
8221 
8222   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
8223   // to commute and use a vwadd(u).vx instead.
8224   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
8225       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
8226     Op0 = Op0.getOperand(1);
8227 
8228     // See if have enough sign bits or zero bits in the scalar to use a
8229     // widening add/sub by splatting to smaller element size.
8230     unsigned EltBits = VT.getScalarSizeInBits();
8231     unsigned ScalarBits = Op0.getValueSizeInBits();
8232     // Make sure we're getting all element bits from the scalar register.
8233     // FIXME: Support implicit sign extension of vmv.v.x?
8234     if (ScalarBits < EltBits)
8235       return SDValue();
8236 
8237     if (IsSigned) {
8238       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
8239         return SDValue();
8240     } else {
8241       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8242       if (!DAG.MaskedValueIsZero(Op0, Mask))
8243         return SDValue();
8244     }
8245 
8246     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8247                       DAG.getUNDEF(NarrowVT), Op0, VL);
8248     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
8249   }
8250 
8251   return SDValue();
8252 }
8253 
8254 // Try to form VWMUL, VWMULU or VWMULSU.
8255 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
8256 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
8257                                        bool Commute) {
8258   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
8259   SDValue Op0 = N->getOperand(0);
8260   SDValue Op1 = N->getOperand(1);
8261   if (Commute)
8262     std::swap(Op0, Op1);
8263 
8264   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
8265   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
8266   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
8267   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
8268     return SDValue();
8269 
8270   SDValue Mask = N->getOperand(2);
8271   SDValue VL = N->getOperand(3);
8272 
8273   // Make sure the mask and VL match.
8274   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8275     return SDValue();
8276 
8277   MVT VT = N->getSimpleValueType(0);
8278 
8279   // Determine the narrow size for a widening multiply.
8280   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8281   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8282                                   VT.getVectorElementCount());
8283 
8284   SDLoc DL(N);
8285 
8286   // See if the other operand is the same opcode.
8287   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8288     if (!Op1.hasOneUse())
8289       return SDValue();
8290 
8291     // Make sure the mask and VL match.
8292     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8293       return SDValue();
8294 
8295     Op1 = Op1.getOperand(0);
8296   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8297     // The operand is a splat of a scalar.
8298 
8299     // The pasthru must be undef for tail agnostic
8300     if (!Op1.getOperand(0).isUndef())
8301       return SDValue();
8302     // The VL must be the same.
8303     if (Op1.getOperand(2) != VL)
8304       return SDValue();
8305 
8306     // Get the scalar value.
8307     Op1 = Op1.getOperand(1);
8308 
8309     // See if have enough sign bits or zero bits in the scalar to use a
8310     // widening multiply by splatting to smaller element size.
8311     unsigned EltBits = VT.getScalarSizeInBits();
8312     unsigned ScalarBits = Op1.getValueSizeInBits();
8313     // Make sure we're getting all element bits from the scalar register.
8314     // FIXME: Support implicit sign extension of vmv.v.x?
8315     if (ScalarBits < EltBits)
8316       return SDValue();
8317 
8318     // If the LHS is a sign extend, try to use vwmul.
8319     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8320       // Can use vwmul.
8321     } else {
8322       // Otherwise try to use vwmulu or vwmulsu.
8323       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8324       if (DAG.MaskedValueIsZero(Op1, Mask))
8325         IsVWMULSU = IsSignExt;
8326       else
8327         return SDValue();
8328     }
8329 
8330     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8331                       DAG.getUNDEF(NarrowVT), Op1, VL);
8332   } else
8333     return SDValue();
8334 
8335   Op0 = Op0.getOperand(0);
8336 
8337   // Re-introduce narrower extends if needed.
8338   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8339   if (Op0.getValueType() != NarrowVT)
8340     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8341   // vwmulsu requires second operand to be zero extended.
8342   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8343   if (Op1.getValueType() != NarrowVT)
8344     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8345 
8346   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8347   if (!IsVWMULSU)
8348     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8349   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8350 }
8351 
8352 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8353   switch (Op.getOpcode()) {
8354   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8355   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8356   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8357   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8358   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8359   }
8360 
8361   return RISCVFPRndMode::Invalid;
8362 }
8363 
8364 // Fold
8365 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8366 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8367 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8368 //   (fp_to_int (fceil X))      -> fcvt X, rup
8369 //   (fp_to_int (fround X))     -> fcvt X, rmm
8370 static SDValue performFP_TO_INTCombine(SDNode *N,
8371                                        TargetLowering::DAGCombinerInfo &DCI,
8372                                        const RISCVSubtarget &Subtarget) {
8373   SelectionDAG &DAG = DCI.DAG;
8374   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8375   MVT XLenVT = Subtarget.getXLenVT();
8376 
8377   // Only handle XLen or i32 types. Other types narrower than XLen will
8378   // eventually be legalized to XLenVT.
8379   EVT VT = N->getValueType(0);
8380   if (VT != MVT::i32 && VT != XLenVT)
8381     return SDValue();
8382 
8383   SDValue Src = N->getOperand(0);
8384 
8385   // Ensure the FP type is also legal.
8386   if (!TLI.isTypeLegal(Src.getValueType()))
8387     return SDValue();
8388 
8389   // Don't do this for f16 with Zfhmin and not Zfh.
8390   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8391     return SDValue();
8392 
8393   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8394   if (FRM == RISCVFPRndMode::Invalid)
8395     return SDValue();
8396 
8397   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8398 
8399   unsigned Opc;
8400   if (VT == XLenVT)
8401     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8402   else
8403     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8404 
8405   SDLoc DL(N);
8406   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8407                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8408   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8409 }
8410 
8411 // Fold
8412 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8413 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8414 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8415 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8416 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8417 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8418                                        TargetLowering::DAGCombinerInfo &DCI,
8419                                        const RISCVSubtarget &Subtarget) {
8420   SelectionDAG &DAG = DCI.DAG;
8421   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8422   MVT XLenVT = Subtarget.getXLenVT();
8423 
8424   // Only handle XLen types. Other types narrower than XLen will eventually be
8425   // legalized to XLenVT.
8426   EVT DstVT = N->getValueType(0);
8427   if (DstVT != XLenVT)
8428     return SDValue();
8429 
8430   SDValue Src = N->getOperand(0);
8431 
8432   // Ensure the FP type is also legal.
8433   if (!TLI.isTypeLegal(Src.getValueType()))
8434     return SDValue();
8435 
8436   // Don't do this for f16 with Zfhmin and not Zfh.
8437   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8438     return SDValue();
8439 
8440   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8441 
8442   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8443   if (FRM == RISCVFPRndMode::Invalid)
8444     return SDValue();
8445 
8446   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8447 
8448   unsigned Opc;
8449   if (SatVT == DstVT)
8450     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8451   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8452     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8453   else
8454     return SDValue();
8455   // FIXME: Support other SatVTs by clamping before or after the conversion.
8456 
8457   Src = Src.getOperand(0);
8458 
8459   SDLoc DL(N);
8460   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8461                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8462 
8463   // RISCV FP-to-int conversions saturate to the destination register size, but
8464   // don't produce 0 for nan.
8465   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8466   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8467 }
8468 
8469 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8470 // smaller than XLenVT.
8471 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8472                                         const RISCVSubtarget &Subtarget) {
8473   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8474 
8475   SDValue Src = N->getOperand(0);
8476   if (Src.getOpcode() != ISD::BSWAP)
8477     return SDValue();
8478 
8479   EVT VT = N->getValueType(0);
8480   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8481       !isPowerOf2_32(VT.getSizeInBits()))
8482     return SDValue();
8483 
8484   SDLoc DL(N);
8485   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8486                      DAG.getConstant(7, DL, VT));
8487 }
8488 
8489 // Convert from one FMA opcode to another based on whether we are negating the
8490 // multiply result and/or the accumulator.
8491 // NOTE: Only supports RVV operations with VL.
8492 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) {
8493   assert((NegMul || NegAcc) && "Not negating anything?");
8494 
8495   // Negating the multiply result changes ADD<->SUB and toggles 'N'.
8496   if (NegMul) {
8497     // clang-format off
8498     switch (Opcode) {
8499     default: llvm_unreachable("Unexpected opcode");
8500     case RISCVISD::VFMADD_VL:  Opcode = RISCVISD::VFNMSUB_VL; break;
8501     case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFMADD_VL;  break;
8502     case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFMSUB_VL;  break;
8503     case RISCVISD::VFMSUB_VL:  Opcode = RISCVISD::VFNMADD_VL; break;
8504     }
8505     // clang-format on
8506   }
8507 
8508   // Negating the accumulator changes ADD<->SUB.
8509   if (NegAcc) {
8510     // clang-format off
8511     switch (Opcode) {
8512     default: llvm_unreachable("Unexpected opcode");
8513     case RISCVISD::VFMADD_VL:  Opcode = RISCVISD::VFMSUB_VL;  break;
8514     case RISCVISD::VFMSUB_VL:  Opcode = RISCVISD::VFMADD_VL;  break;
8515     case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break;
8516     case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break;
8517     }
8518     // clang-format on
8519   }
8520 
8521   return Opcode;
8522 }
8523 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8524                                                DAGCombinerInfo &DCI) const {
8525   SelectionDAG &DAG = DCI.DAG;
8526 
8527   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8528   // bits are demanded. N will be added to the Worklist if it was not deleted.
8529   // Caller should return SDValue(N, 0) if this returns true.
8530   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8531     SDValue Op = N->getOperand(OpNo);
8532     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8533     if (!SimplifyDemandedBits(Op, Mask, DCI))
8534       return false;
8535 
8536     if (N->getOpcode() != ISD::DELETED_NODE)
8537       DCI.AddToWorklist(N);
8538     return true;
8539   };
8540 
8541   switch (N->getOpcode()) {
8542   default:
8543     break;
8544   case RISCVISD::SplitF64: {
8545     SDValue Op0 = N->getOperand(0);
8546     // If the input to SplitF64 is just BuildPairF64 then the operation is
8547     // redundant. Instead, use BuildPairF64's operands directly.
8548     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8549       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8550 
8551     if (Op0->isUndef()) {
8552       SDValue Lo = DAG.getUNDEF(MVT::i32);
8553       SDValue Hi = DAG.getUNDEF(MVT::i32);
8554       return DCI.CombineTo(N, Lo, Hi);
8555     }
8556 
8557     SDLoc DL(N);
8558 
8559     // It's cheaper to materialise two 32-bit integers than to load a double
8560     // from the constant pool and transfer it to integer registers through the
8561     // stack.
8562     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8563       APInt V = C->getValueAPF().bitcastToAPInt();
8564       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8565       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8566       return DCI.CombineTo(N, Lo, Hi);
8567     }
8568 
8569     // This is a target-specific version of a DAGCombine performed in
8570     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8571     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8572     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8573     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8574         !Op0.getNode()->hasOneUse())
8575       break;
8576     SDValue NewSplitF64 =
8577         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8578                     Op0.getOperand(0));
8579     SDValue Lo = NewSplitF64.getValue(0);
8580     SDValue Hi = NewSplitF64.getValue(1);
8581     APInt SignBit = APInt::getSignMask(32);
8582     if (Op0.getOpcode() == ISD::FNEG) {
8583       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8584                                   DAG.getConstant(SignBit, DL, MVT::i32));
8585       return DCI.CombineTo(N, Lo, NewHi);
8586     }
8587     assert(Op0.getOpcode() == ISD::FABS);
8588     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8589                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8590     return DCI.CombineTo(N, Lo, NewHi);
8591   }
8592   case RISCVISD::SLLW:
8593   case RISCVISD::SRAW:
8594   case RISCVISD::SRLW: {
8595     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8596     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8597         SimplifyDemandedLowBitsHelper(1, 5))
8598       return SDValue(N, 0);
8599 
8600     break;
8601   }
8602   case ISD::ROTR:
8603   case ISD::ROTL:
8604   case RISCVISD::RORW:
8605   case RISCVISD::ROLW: {
8606     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8607       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8608       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8609           SimplifyDemandedLowBitsHelper(1, 5))
8610         return SDValue(N, 0);
8611     }
8612 
8613     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8614   }
8615   case RISCVISD::CLZW:
8616   case RISCVISD::CTZW: {
8617     // Only the lower 32 bits of the first operand are read
8618     if (SimplifyDemandedLowBitsHelper(0, 32))
8619       return SDValue(N, 0);
8620     break;
8621   }
8622   case RISCVISD::GREV:
8623   case RISCVISD::GORC: {
8624     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8625     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8626     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8627     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8628       return SDValue(N, 0);
8629 
8630     return combineGREVI_GORCI(N, DAG);
8631   }
8632   case RISCVISD::GREVW:
8633   case RISCVISD::GORCW: {
8634     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8635     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8636         SimplifyDemandedLowBitsHelper(1, 5))
8637       return SDValue(N, 0);
8638 
8639     break;
8640   }
8641   case RISCVISD::SHFL:
8642   case RISCVISD::UNSHFL: {
8643     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8644     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8645     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8646     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8647       return SDValue(N, 0);
8648 
8649     break;
8650   }
8651   case RISCVISD::SHFLW:
8652   case RISCVISD::UNSHFLW: {
8653     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8654     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8655         SimplifyDemandedLowBitsHelper(1, 4))
8656       return SDValue(N, 0);
8657 
8658     break;
8659   }
8660   case RISCVISD::BCOMPRESSW:
8661   case RISCVISD::BDECOMPRESSW: {
8662     // Only the lower 32 bits of LHS and RHS are read.
8663     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8664         SimplifyDemandedLowBitsHelper(1, 32))
8665       return SDValue(N, 0);
8666 
8667     break;
8668   }
8669   case RISCVISD::FSR:
8670   case RISCVISD::FSL:
8671   case RISCVISD::FSRW:
8672   case RISCVISD::FSLW: {
8673     bool IsWInstruction =
8674         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8675     unsigned BitWidth =
8676         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8677     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8678     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8679     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8680       return SDValue(N, 0);
8681 
8682     break;
8683   }
8684   case RISCVISD::FMV_X_ANYEXTH:
8685   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8686     SDLoc DL(N);
8687     SDValue Op0 = N->getOperand(0);
8688     MVT VT = N->getSimpleValueType(0);
8689     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8690     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8691     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8692     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8693          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8694         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8695          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8696       assert(Op0.getOperand(0).getValueType() == VT &&
8697              "Unexpected value type!");
8698       return Op0.getOperand(0);
8699     }
8700 
8701     // This is a target-specific version of a DAGCombine performed in
8702     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8703     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8704     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8705     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8706         !Op0.getNode()->hasOneUse())
8707       break;
8708     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8709     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8710     APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits());
8711     if (Op0.getOpcode() == ISD::FNEG)
8712       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8713                          DAG.getConstant(SignBit, DL, VT));
8714 
8715     assert(Op0.getOpcode() == ISD::FABS);
8716     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8717                        DAG.getConstant(~SignBit, DL, VT));
8718   }
8719   case ISD::ADD:
8720     return performADDCombine(N, DAG, Subtarget);
8721   case ISD::SUB:
8722     return performSUBCombine(N, DAG);
8723   case ISD::AND:
8724     return performANDCombine(N, DAG, Subtarget);
8725   case ISD::OR:
8726     return performORCombine(N, DAG, Subtarget);
8727   case ISD::XOR:
8728     return performXORCombine(N, DAG);
8729   case ISD::FADD:
8730   case ISD::UMAX:
8731   case ISD::UMIN:
8732   case ISD::SMAX:
8733   case ISD::SMIN:
8734   case ISD::FMAXNUM:
8735   case ISD::FMINNUM:
8736     return combineBinOpToReduce(N, DAG);
8737   case ISD::SIGN_EXTEND_INREG:
8738     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8739   case ISD::ZERO_EXTEND:
8740     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8741     // type legalization. This is safe because fp_to_uint produces poison if
8742     // it overflows.
8743     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8744       SDValue Src = N->getOperand(0);
8745       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8746           isTypeLegal(Src.getOperand(0).getValueType()))
8747         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8748                            Src.getOperand(0));
8749       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8750           isTypeLegal(Src.getOperand(1).getValueType())) {
8751         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8752         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8753                                   Src.getOperand(0), Src.getOperand(1));
8754         DCI.CombineTo(N, Res);
8755         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8756         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8757         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8758       }
8759     }
8760     return SDValue();
8761   case RISCVISD::SELECT_CC: {
8762     // Transform
8763     SDValue LHS = N->getOperand(0);
8764     SDValue RHS = N->getOperand(1);
8765     SDValue TrueV = N->getOperand(3);
8766     SDValue FalseV = N->getOperand(4);
8767 
8768     // If the True and False values are the same, we don't need a select_cc.
8769     if (TrueV == FalseV)
8770       return TrueV;
8771 
8772     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8773     if (!ISD::isIntEqualitySetCC(CCVal))
8774       break;
8775 
8776     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8777     //      (select_cc X, Y, lt, trueV, falseV)
8778     // Sometimes the setcc is introduced after select_cc has been formed.
8779     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8780         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8781       // If we're looking for eq 0 instead of ne 0, we need to invert the
8782       // condition.
8783       bool Invert = CCVal == ISD::SETEQ;
8784       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8785       if (Invert)
8786         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8787 
8788       SDLoc DL(N);
8789       RHS = LHS.getOperand(1);
8790       LHS = LHS.getOperand(0);
8791       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8792 
8793       SDValue TargetCC = DAG.getCondCode(CCVal);
8794       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8795                          {LHS, RHS, TargetCC, TrueV, FalseV});
8796     }
8797 
8798     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8799     //      (select_cc X, Y, eq/ne, trueV, falseV)
8800     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8801       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8802                          {LHS.getOperand(0), LHS.getOperand(1),
8803                           N->getOperand(2), TrueV, FalseV});
8804     // (select_cc X, 1, setne, trueV, falseV) ->
8805     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8806     // This can occur when legalizing some floating point comparisons.
8807     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8808     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8809       SDLoc DL(N);
8810       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8811       SDValue TargetCC = DAG.getCondCode(CCVal);
8812       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8813       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8814                          {LHS, RHS, TargetCC, TrueV, FalseV});
8815     }
8816 
8817     break;
8818   }
8819   case RISCVISD::BR_CC: {
8820     SDValue LHS = N->getOperand(1);
8821     SDValue RHS = N->getOperand(2);
8822     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8823     if (!ISD::isIntEqualitySetCC(CCVal))
8824       break;
8825 
8826     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8827     //      (br_cc X, Y, lt, dest)
8828     // Sometimes the setcc is introduced after br_cc has been formed.
8829     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8830         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8831       // If we're looking for eq 0 instead of ne 0, we need to invert the
8832       // condition.
8833       bool Invert = CCVal == ISD::SETEQ;
8834       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8835       if (Invert)
8836         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8837 
8838       SDLoc DL(N);
8839       RHS = LHS.getOperand(1);
8840       LHS = LHS.getOperand(0);
8841       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8842 
8843       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8844                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8845                          N->getOperand(4));
8846     }
8847 
8848     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8849     //      (br_cc X, Y, eq/ne, trueV, falseV)
8850     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8851       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8852                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8853                          N->getOperand(3), N->getOperand(4));
8854 
8855     // (br_cc X, 1, setne, br_cc) ->
8856     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8857     // This can occur when legalizing some floating point comparisons.
8858     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8859     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8860       SDLoc DL(N);
8861       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8862       SDValue TargetCC = DAG.getCondCode(CCVal);
8863       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8864       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8865                          N->getOperand(0), LHS, RHS, TargetCC,
8866                          N->getOperand(4));
8867     }
8868     break;
8869   }
8870   case ISD::BITREVERSE:
8871     return performBITREVERSECombine(N, DAG, Subtarget);
8872   case ISD::FP_TO_SINT:
8873   case ISD::FP_TO_UINT:
8874     return performFP_TO_INTCombine(N, DCI, Subtarget);
8875   case ISD::FP_TO_SINT_SAT:
8876   case ISD::FP_TO_UINT_SAT:
8877     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8878   case ISD::FCOPYSIGN: {
8879     EVT VT = N->getValueType(0);
8880     if (!VT.isVector())
8881       break;
8882     // There is a form of VFSGNJ which injects the negated sign of its second
8883     // operand. Try and bubble any FNEG up after the extend/round to produce
8884     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8885     // TRUNC=1.
8886     SDValue In2 = N->getOperand(1);
8887     // Avoid cases where the extend/round has multiple uses, as duplicating
8888     // those is typically more expensive than removing a fneg.
8889     if (!In2.hasOneUse())
8890       break;
8891     if (In2.getOpcode() != ISD::FP_EXTEND &&
8892         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8893       break;
8894     In2 = In2.getOperand(0);
8895     if (In2.getOpcode() != ISD::FNEG)
8896       break;
8897     SDLoc DL(N);
8898     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8899     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8900                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8901   }
8902   case ISD::MGATHER:
8903   case ISD::MSCATTER:
8904   case ISD::VP_GATHER:
8905   case ISD::VP_SCATTER: {
8906     if (!DCI.isBeforeLegalize())
8907       break;
8908     SDValue Index, ScaleOp;
8909     bool IsIndexScaled = false;
8910     bool IsIndexSigned = false;
8911     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8912       Index = VPGSN->getIndex();
8913       ScaleOp = VPGSN->getScale();
8914       IsIndexScaled = VPGSN->isIndexScaled();
8915       IsIndexSigned = VPGSN->isIndexSigned();
8916     } else {
8917       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8918       Index = MGSN->getIndex();
8919       ScaleOp = MGSN->getScale();
8920       IsIndexScaled = MGSN->isIndexScaled();
8921       IsIndexSigned = MGSN->isIndexSigned();
8922     }
8923     EVT IndexVT = Index.getValueType();
8924     MVT XLenVT = Subtarget.getXLenVT();
8925     // RISCV indexed loads only support the "unsigned unscaled" addressing
8926     // mode, so anything else must be manually legalized.
8927     bool NeedsIdxLegalization =
8928         IsIndexScaled ||
8929         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8930     if (!NeedsIdxLegalization)
8931       break;
8932 
8933     SDLoc DL(N);
8934 
8935     // Any index legalization should first promote to XLenVT, so we don't lose
8936     // bits when scaling. This may create an illegal index type so we let
8937     // LLVM's legalization take care of the splitting.
8938     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8939     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8940       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8941       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8942                           DL, IndexVT, Index);
8943     }
8944 
8945     if (IsIndexScaled) {
8946       // Manually scale the indices.
8947       // TODO: Sanitize the scale operand here?
8948       // TODO: For VP nodes, should we use VP_SHL here?
8949       unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8950       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8951       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8952       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8953       ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType());
8954     }
8955 
8956     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED;
8957     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8958       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8959                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8960                               ScaleOp, VPGN->getMask(),
8961                               VPGN->getVectorLength()},
8962                              VPGN->getMemOperand(), NewIndexTy);
8963     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8964       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8965                               {VPSN->getChain(), VPSN->getValue(),
8966                                VPSN->getBasePtr(), Index, ScaleOp,
8967                                VPSN->getMask(), VPSN->getVectorLength()},
8968                               VPSN->getMemOperand(), NewIndexTy);
8969     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8970       return DAG.getMaskedGather(
8971           N->getVTList(), MGN->getMemoryVT(), DL,
8972           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8973            MGN->getBasePtr(), Index, ScaleOp},
8974           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8975     const auto *MSN = cast<MaskedScatterSDNode>(N);
8976     return DAG.getMaskedScatter(
8977         N->getVTList(), MSN->getMemoryVT(), DL,
8978         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8979          Index, ScaleOp},
8980         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8981   }
8982   case RISCVISD::SRA_VL:
8983   case RISCVISD::SRL_VL:
8984   case RISCVISD::SHL_VL: {
8985     SDValue ShAmt = N->getOperand(1);
8986     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8987       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8988       SDLoc DL(N);
8989       SDValue VL = N->getOperand(3);
8990       EVT VT = N->getValueType(0);
8991       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8992                           ShAmt.getOperand(1), VL);
8993       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8994                          N->getOperand(2), N->getOperand(3));
8995     }
8996     break;
8997   }
8998   case ISD::SRA:
8999   case ISD::SRL:
9000   case ISD::SHL: {
9001     SDValue ShAmt = N->getOperand(1);
9002     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
9003       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
9004       SDLoc DL(N);
9005       EVT VT = N->getValueType(0);
9006       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
9007                           ShAmt.getOperand(1),
9008                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
9009       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
9010     }
9011     break;
9012   }
9013   case RISCVISD::ADD_VL:
9014     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
9015       return V;
9016     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
9017   case RISCVISD::SUB_VL:
9018     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
9019   case RISCVISD::VWADD_W_VL:
9020   case RISCVISD::VWADDU_W_VL:
9021   case RISCVISD::VWSUB_W_VL:
9022   case RISCVISD::VWSUBU_W_VL:
9023     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
9024   case RISCVISD::MUL_VL:
9025     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
9026       return V;
9027     // Mul is commutative.
9028     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
9029   case RISCVISD::VFMADD_VL:
9030   case RISCVISD::VFNMADD_VL:
9031   case RISCVISD::VFMSUB_VL:
9032   case RISCVISD::VFNMSUB_VL: {
9033     // Fold FNEG_VL into FMA opcodes.
9034     SDValue A = N->getOperand(0);
9035     SDValue B = N->getOperand(1);
9036     SDValue C = N->getOperand(2);
9037     SDValue Mask = N->getOperand(3);
9038     SDValue VL = N->getOperand(4);
9039 
9040     auto invertIfNegative = [&Mask, &VL](SDValue &V) {
9041       if (V.getOpcode() == RISCVISD::FNEG_VL && V.getOperand(1) == Mask &&
9042           V.getOperand(2) == VL) {
9043         // Return the negated input.
9044         V = V.getOperand(0);
9045         return true;
9046       }
9047 
9048       return false;
9049     };
9050 
9051     bool NegA = invertIfNegative(A);
9052     bool NegB = invertIfNegative(B);
9053     bool NegC = invertIfNegative(C);
9054 
9055     // If no operands are negated, we're done.
9056     if (!NegA && !NegB && !NegC)
9057       return SDValue();
9058 
9059     unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC);
9060     return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), A, B, C, Mask,
9061                        VL);
9062   }
9063   case ISD::STORE: {
9064     auto *Store = cast<StoreSDNode>(N);
9065     SDValue Val = Store->getValue();
9066     // Combine store of vmv.x.s to vse with VL of 1.
9067     // FIXME: Support FP.
9068     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
9069       SDValue Src = Val.getOperand(0);
9070       EVT VecVT = Src.getValueType();
9071       EVT MemVT = Store->getMemoryVT();
9072       // The memory VT and the element type must match.
9073       if (VecVT.getVectorElementType() == MemVT) {
9074         SDLoc DL(N);
9075         MVT MaskVT = getMaskTypeFor(VecVT);
9076         return DAG.getStoreVP(
9077             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
9078             DAG.getConstant(1, DL, MaskVT),
9079             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
9080             Store->getMemOperand(), Store->getAddressingMode(),
9081             Store->isTruncatingStore(), /*IsCompress*/ false);
9082       }
9083     }
9084 
9085     break;
9086   }
9087   case ISD::SPLAT_VECTOR: {
9088     EVT VT = N->getValueType(0);
9089     // Only perform this combine on legal MVT types.
9090     if (!isTypeLegal(VT))
9091       break;
9092     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
9093                                          DAG, Subtarget))
9094       return Gather;
9095     break;
9096   }
9097   case RISCVISD::VMV_V_X_VL: {
9098     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
9099     // scalar input.
9100     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
9101     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
9102     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
9103       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
9104         return SDValue(N, 0);
9105 
9106     break;
9107   }
9108   case ISD::INTRINSIC_WO_CHAIN: {
9109     unsigned IntNo = N->getConstantOperandVal(0);
9110     switch (IntNo) {
9111       // By default we do not combine any intrinsic.
9112     default:
9113       return SDValue();
9114     case Intrinsic::riscv_vcpop:
9115     case Intrinsic::riscv_vcpop_mask:
9116     case Intrinsic::riscv_vfirst:
9117     case Intrinsic::riscv_vfirst_mask: {
9118       SDValue VL = N->getOperand(2);
9119       if (IntNo == Intrinsic::riscv_vcpop_mask ||
9120           IntNo == Intrinsic::riscv_vfirst_mask)
9121         VL = N->getOperand(3);
9122       if (!isNullConstant(VL))
9123         return SDValue();
9124       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
9125       SDLoc DL(N);
9126       EVT VT = N->getValueType(0);
9127       if (IntNo == Intrinsic::riscv_vfirst ||
9128           IntNo == Intrinsic::riscv_vfirst_mask)
9129         return DAG.getConstant(-1, DL, VT);
9130       return DAG.getConstant(0, DL, VT);
9131     }
9132     }
9133   }
9134   case ISD::BITCAST: {
9135     assert(Subtarget.useRVVForFixedLengthVectors());
9136     SDValue N0 = N->getOperand(0);
9137     EVT VT = N->getValueType(0);
9138     EVT SrcVT = N0.getValueType();
9139     // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer
9140     // type, widen both sides to avoid a trip through memory.
9141     if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) &&
9142         VT.isScalarInteger()) {
9143       unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
9144       SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
9145       Ops[0] = N0;
9146       SDLoc DL(N);
9147       N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops);
9148       N0 = DAG.getBitcast(MVT::i8, N0);
9149       return DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
9150     }
9151 
9152     return SDValue();
9153   }
9154   }
9155 
9156   return SDValue();
9157 }
9158 
9159 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
9160     const SDNode *N, CombineLevel Level) const {
9161   // The following folds are only desirable if `(OP _, c1 << c2)` can be
9162   // materialised in fewer instructions than `(OP _, c1)`:
9163   //
9164   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
9165   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
9166   SDValue N0 = N->getOperand(0);
9167   EVT Ty = N0.getValueType();
9168   if (Ty.isScalarInteger() &&
9169       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
9170     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9171     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
9172     if (C1 && C2) {
9173       const APInt &C1Int = C1->getAPIntValue();
9174       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
9175 
9176       // We can materialise `c1 << c2` into an add immediate, so it's "free",
9177       // and the combine should happen, to potentially allow further combines
9178       // later.
9179       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
9180           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
9181         return true;
9182 
9183       // We can materialise `c1` in an add immediate, so it's "free", and the
9184       // combine should be prevented.
9185       if (C1Int.getMinSignedBits() <= 64 &&
9186           isLegalAddImmediate(C1Int.getSExtValue()))
9187         return false;
9188 
9189       // Neither constant will fit into an immediate, so find materialisation
9190       // costs.
9191       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
9192                                               Subtarget.getFeatureBits(),
9193                                               /*CompressionCost*/true);
9194       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
9195           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
9196           /*CompressionCost*/true);
9197 
9198       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
9199       // combine should be prevented.
9200       if (C1Cost < ShiftedC1Cost)
9201         return false;
9202     }
9203   }
9204   return true;
9205 }
9206 
9207 bool RISCVTargetLowering::targetShrinkDemandedConstant(
9208     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
9209     TargetLoweringOpt &TLO) const {
9210   // Delay this optimization as late as possible.
9211   if (!TLO.LegalOps)
9212     return false;
9213 
9214   EVT VT = Op.getValueType();
9215   if (VT.isVector())
9216     return false;
9217 
9218   // Only handle AND for now.
9219   if (Op.getOpcode() != ISD::AND)
9220     return false;
9221 
9222   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9223   if (!C)
9224     return false;
9225 
9226   const APInt &Mask = C->getAPIntValue();
9227 
9228   // Clear all non-demanded bits initially.
9229   APInt ShrunkMask = Mask & DemandedBits;
9230 
9231   // Try to make a smaller immediate by setting undemanded bits.
9232 
9233   APInt ExpandedMask = Mask | ~DemandedBits;
9234 
9235   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
9236     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
9237   };
9238   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
9239     if (NewMask == Mask)
9240       return true;
9241     SDLoc DL(Op);
9242     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
9243     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
9244     return TLO.CombineTo(Op, NewOp);
9245   };
9246 
9247   // If the shrunk mask fits in sign extended 12 bits, let the target
9248   // independent code apply it.
9249   if (ShrunkMask.isSignedIntN(12))
9250     return false;
9251 
9252   // Preserve (and X, 0xffff) when zext.h is supported.
9253   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
9254     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
9255     if (IsLegalMask(NewMask))
9256       return UseMask(NewMask);
9257   }
9258 
9259   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
9260   if (VT == MVT::i64) {
9261     APInt NewMask = APInt(64, 0xffffffff);
9262     if (IsLegalMask(NewMask))
9263       return UseMask(NewMask);
9264   }
9265 
9266   // For the remaining optimizations, we need to be able to make a negative
9267   // number through a combination of mask and undemanded bits.
9268   if (!ExpandedMask.isNegative())
9269     return false;
9270 
9271   // What is the fewest number of bits we need to represent the negative number.
9272   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
9273 
9274   // Try to make a 12 bit negative immediate. If that fails try to make a 32
9275   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
9276   APInt NewMask = ShrunkMask;
9277   if (MinSignedBits <= 12)
9278     NewMask.setBitsFrom(11);
9279   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
9280     NewMask.setBitsFrom(31);
9281   else
9282     return false;
9283 
9284   // Check that our new mask is a subset of the demanded mask.
9285   assert(IsLegalMask(NewMask));
9286   return UseMask(NewMask);
9287 }
9288 
9289 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
9290   static const uint64_t GREVMasks[] = {
9291       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
9292       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
9293 
9294   for (unsigned Stage = 0; Stage != 6; ++Stage) {
9295     unsigned Shift = 1 << Stage;
9296     if (ShAmt & Shift) {
9297       uint64_t Mask = GREVMasks[Stage];
9298       uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
9299       if (IsGORC)
9300         Res |= x;
9301       x = Res;
9302     }
9303   }
9304 
9305   return x;
9306 }
9307 
9308 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9309                                                         KnownBits &Known,
9310                                                         const APInt &DemandedElts,
9311                                                         const SelectionDAG &DAG,
9312                                                         unsigned Depth) const {
9313   unsigned BitWidth = Known.getBitWidth();
9314   unsigned Opc = Op.getOpcode();
9315   assert((Opc >= ISD::BUILTIN_OP_END ||
9316           Opc == ISD::INTRINSIC_WO_CHAIN ||
9317           Opc == ISD::INTRINSIC_W_CHAIN ||
9318           Opc == ISD::INTRINSIC_VOID) &&
9319          "Should use MaskedValueIsZero if you don't know whether Op"
9320          " is a target node!");
9321 
9322   Known.resetAll();
9323   switch (Opc) {
9324   default: break;
9325   case RISCVISD::SELECT_CC: {
9326     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
9327     // If we don't know any bits, early out.
9328     if (Known.isUnknown())
9329       break;
9330     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
9331 
9332     // Only known if known in both the LHS and RHS.
9333     Known = KnownBits::commonBits(Known, Known2);
9334     break;
9335   }
9336   case RISCVISD::REMUW: {
9337     KnownBits Known2;
9338     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9339     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9340     // We only care about the lower 32 bits.
9341     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
9342     // Restore the original width by sign extending.
9343     Known = Known.sext(BitWidth);
9344     break;
9345   }
9346   case RISCVISD::DIVUW: {
9347     KnownBits Known2;
9348     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9349     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9350     // We only care about the lower 32 bits.
9351     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
9352     // Restore the original width by sign extending.
9353     Known = Known.sext(BitWidth);
9354     break;
9355   }
9356   case RISCVISD::CTZW: {
9357     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9358     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
9359     unsigned LowBits = Log2_32(PossibleTZ) + 1;
9360     Known.Zero.setBitsFrom(LowBits);
9361     break;
9362   }
9363   case RISCVISD::CLZW: {
9364     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9365     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
9366     unsigned LowBits = Log2_32(PossibleLZ) + 1;
9367     Known.Zero.setBitsFrom(LowBits);
9368     break;
9369   }
9370   case RISCVISD::GREV:
9371   case RISCVISD::GORC: {
9372     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9373       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9374       unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1);
9375       bool IsGORC = Op.getOpcode() == RISCVISD::GORC;
9376       // To compute zeros, we need to invert the value and invert it back after.
9377       Known.Zero =
9378           ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC);
9379       Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC);
9380     }
9381     break;
9382   }
9383   case RISCVISD::READ_VLENB: {
9384     // If we know the minimum VLen from Zvl extensions, we can use that to
9385     // determine the trailing zeros of VLENB.
9386     // FIXME: Limit to 128 bit vectors until we have more testing.
9387     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
9388     if (MinVLenB > 0)
9389       Known.Zero.setLowBits(Log2_32(MinVLenB));
9390     // We assume VLENB is no more than 65536 / 8 bytes.
9391     Known.Zero.setBitsFrom(14);
9392     break;
9393   }
9394   case ISD::INTRINSIC_W_CHAIN:
9395   case ISD::INTRINSIC_WO_CHAIN: {
9396     unsigned IntNo =
9397         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9398     switch (IntNo) {
9399     default:
9400       // We can't do anything for most intrinsics.
9401       break;
9402     case Intrinsic::riscv_vsetvli:
9403     case Intrinsic::riscv_vsetvlimax:
9404     case Intrinsic::riscv_vsetvli_opt:
9405     case Intrinsic::riscv_vsetvlimax_opt:
9406       // Assume that VL output is positive and would fit in an int32_t.
9407       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9408       if (BitWidth >= 32)
9409         Known.Zero.setBitsFrom(31);
9410       break;
9411     }
9412     break;
9413   }
9414   }
9415 }
9416 
9417 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9418     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9419     unsigned Depth) const {
9420   switch (Op.getOpcode()) {
9421   default:
9422     break;
9423   case RISCVISD::SELECT_CC: {
9424     unsigned Tmp =
9425         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9426     if (Tmp == 1) return 1;  // Early out.
9427     unsigned Tmp2 =
9428         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9429     return std::min(Tmp, Tmp2);
9430   }
9431   case RISCVISD::SLLW:
9432   case RISCVISD::SRAW:
9433   case RISCVISD::SRLW:
9434   case RISCVISD::DIVW:
9435   case RISCVISD::DIVUW:
9436   case RISCVISD::REMUW:
9437   case RISCVISD::ROLW:
9438   case RISCVISD::RORW:
9439   case RISCVISD::GREVW:
9440   case RISCVISD::GORCW:
9441   case RISCVISD::FSLW:
9442   case RISCVISD::FSRW:
9443   case RISCVISD::SHFLW:
9444   case RISCVISD::UNSHFLW:
9445   case RISCVISD::BCOMPRESSW:
9446   case RISCVISD::BDECOMPRESSW:
9447   case RISCVISD::BFPW:
9448   case RISCVISD::FCVT_W_RV64:
9449   case RISCVISD::FCVT_WU_RV64:
9450   case RISCVISD::STRICT_FCVT_W_RV64:
9451   case RISCVISD::STRICT_FCVT_WU_RV64:
9452     // TODO: As the result is sign-extended, this is conservatively correct. A
9453     // more precise answer could be calculated for SRAW depending on known
9454     // bits in the shift amount.
9455     return 33;
9456   case RISCVISD::SHFL:
9457   case RISCVISD::UNSHFL: {
9458     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9459     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9460     // will stay within the upper 32 bits. If there were more than 32 sign bits
9461     // before there will be at least 33 sign bits after.
9462     if (Op.getValueType() == MVT::i64 &&
9463         isa<ConstantSDNode>(Op.getOperand(1)) &&
9464         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9465       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9466       if (Tmp > 32)
9467         return 33;
9468     }
9469     break;
9470   }
9471   case RISCVISD::VMV_X_S: {
9472     // The number of sign bits of the scalar result is computed by obtaining the
9473     // element type of the input vector operand, subtracting its width from the
9474     // XLEN, and then adding one (sign bit within the element type). If the
9475     // element type is wider than XLen, the least-significant XLEN bits are
9476     // taken.
9477     unsigned XLen = Subtarget.getXLen();
9478     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9479     if (EltBits <= XLen)
9480       return XLen - EltBits + 1;
9481     break;
9482   }
9483   }
9484 
9485   return 1;
9486 }
9487 
9488 const Constant *
9489 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const {
9490   assert(Ld && "Unexpected null LoadSDNode");
9491   if (!ISD::isNormalLoad(Ld))
9492     return nullptr;
9493 
9494   SDValue Ptr = Ld->getBasePtr();
9495 
9496   // Only constant pools with no offset are supported.
9497   auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * {
9498     auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
9499     if (!CNode || CNode->isMachineConstantPoolEntry() ||
9500         CNode->getOffset() != 0)
9501       return nullptr;
9502 
9503     return CNode;
9504   };
9505 
9506   // Simple case, LLA.
9507   if (Ptr.getOpcode() == RISCVISD::LLA) {
9508     auto *CNode = GetSupportedConstantPool(Ptr);
9509     if (!CNode || CNode->getTargetFlags() != 0)
9510       return nullptr;
9511 
9512     return CNode->getConstVal();
9513   }
9514 
9515   // Look for a HI and ADD_LO pair.
9516   if (Ptr.getOpcode() != RISCVISD::ADD_LO ||
9517       Ptr.getOperand(0).getOpcode() != RISCVISD::HI)
9518     return nullptr;
9519 
9520   auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1));
9521   auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0));
9522 
9523   if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO ||
9524       !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI)
9525     return nullptr;
9526 
9527   if (CNodeLo->getConstVal() != CNodeHi->getConstVal())
9528     return nullptr;
9529 
9530   return CNodeLo->getConstVal();
9531 }
9532 
9533 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9534                                                   MachineBasicBlock *BB) {
9535   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9536 
9537   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9538   // Should the count have wrapped while it was being read, we need to try
9539   // again.
9540   // ...
9541   // read:
9542   // rdcycleh x3 # load high word of cycle
9543   // rdcycle  x2 # load low word of cycle
9544   // rdcycleh x4 # load high word of cycle
9545   // bne x3, x4, read # check if high word reads match, otherwise try again
9546   // ...
9547 
9548   MachineFunction &MF = *BB->getParent();
9549   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9550   MachineFunction::iterator It = ++BB->getIterator();
9551 
9552   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9553   MF.insert(It, LoopMBB);
9554 
9555   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9556   MF.insert(It, DoneMBB);
9557 
9558   // Transfer the remainder of BB and its successor edges to DoneMBB.
9559   DoneMBB->splice(DoneMBB->begin(), BB,
9560                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9561   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9562 
9563   BB->addSuccessor(LoopMBB);
9564 
9565   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9566   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9567   Register LoReg = MI.getOperand(0).getReg();
9568   Register HiReg = MI.getOperand(1).getReg();
9569   DebugLoc DL = MI.getDebugLoc();
9570 
9571   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9572   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9573       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9574       .addReg(RISCV::X0);
9575   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9576       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9577       .addReg(RISCV::X0);
9578   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9579       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9580       .addReg(RISCV::X0);
9581 
9582   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9583       .addReg(HiReg)
9584       .addReg(ReadAgainReg)
9585       .addMBB(LoopMBB);
9586 
9587   LoopMBB->addSuccessor(LoopMBB);
9588   LoopMBB->addSuccessor(DoneMBB);
9589 
9590   MI.eraseFromParent();
9591 
9592   return DoneMBB;
9593 }
9594 
9595 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9596                                              MachineBasicBlock *BB) {
9597   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9598 
9599   MachineFunction &MF = *BB->getParent();
9600   DebugLoc DL = MI.getDebugLoc();
9601   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9602   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9603   Register LoReg = MI.getOperand(0).getReg();
9604   Register HiReg = MI.getOperand(1).getReg();
9605   Register SrcReg = MI.getOperand(2).getReg();
9606   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9607   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9608 
9609   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9610                           RI);
9611   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9612   MachineMemOperand *MMOLo =
9613       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9614   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9615       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9616   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9617       .addFrameIndex(FI)
9618       .addImm(0)
9619       .addMemOperand(MMOLo);
9620   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9621       .addFrameIndex(FI)
9622       .addImm(4)
9623       .addMemOperand(MMOHi);
9624   MI.eraseFromParent(); // The pseudo instruction is gone now.
9625   return BB;
9626 }
9627 
9628 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9629                                                  MachineBasicBlock *BB) {
9630   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9631          "Unexpected instruction");
9632 
9633   MachineFunction &MF = *BB->getParent();
9634   DebugLoc DL = MI.getDebugLoc();
9635   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9636   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9637   Register DstReg = MI.getOperand(0).getReg();
9638   Register LoReg = MI.getOperand(1).getReg();
9639   Register HiReg = MI.getOperand(2).getReg();
9640   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9641   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9642 
9643   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9644   MachineMemOperand *MMOLo =
9645       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9646   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9647       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9648   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9649       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9650       .addFrameIndex(FI)
9651       .addImm(0)
9652       .addMemOperand(MMOLo);
9653   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9654       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9655       .addFrameIndex(FI)
9656       .addImm(4)
9657       .addMemOperand(MMOHi);
9658   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9659   MI.eraseFromParent(); // The pseudo instruction is gone now.
9660   return BB;
9661 }
9662 
9663 static bool isSelectPseudo(MachineInstr &MI) {
9664   switch (MI.getOpcode()) {
9665   default:
9666     return false;
9667   case RISCV::Select_GPR_Using_CC_GPR:
9668   case RISCV::Select_FPR16_Using_CC_GPR:
9669   case RISCV::Select_FPR32_Using_CC_GPR:
9670   case RISCV::Select_FPR64_Using_CC_GPR:
9671     return true;
9672   }
9673 }
9674 
9675 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9676                                         unsigned RelOpcode, unsigned EqOpcode,
9677                                         const RISCVSubtarget &Subtarget) {
9678   DebugLoc DL = MI.getDebugLoc();
9679   Register DstReg = MI.getOperand(0).getReg();
9680   Register Src1Reg = MI.getOperand(1).getReg();
9681   Register Src2Reg = MI.getOperand(2).getReg();
9682   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9683   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9684   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9685 
9686   // Save the current FFLAGS.
9687   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9688 
9689   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9690                  .addReg(Src1Reg)
9691                  .addReg(Src2Reg);
9692   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9693     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9694 
9695   // Restore the FFLAGS.
9696   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9697       .addReg(SavedFFlags, RegState::Kill);
9698 
9699   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9700   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9701                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9702                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9703   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9704     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9705 
9706   // Erase the pseudoinstruction.
9707   MI.eraseFromParent();
9708   return BB;
9709 }
9710 
9711 static MachineBasicBlock *
9712 EmitLoweredCascadedSelect(MachineInstr &First, MachineInstr &Second,
9713                           MachineBasicBlock *ThisMBB,
9714                           const RISCVSubtarget &Subtarget) {
9715   // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5)
9716   // Without this, custom-inserter would have generated:
9717   //
9718   //   A
9719   //   | \
9720   //   |  B
9721   //   | /
9722   //   C
9723   //   | \
9724   //   |  D
9725   //   | /
9726   //   E
9727   //
9728   // A: X = ...; Y = ...
9729   // B: empty
9730   // C: Z = PHI [X, A], [Y, B]
9731   // D: empty
9732   // E: PHI [X, C], [Z, D]
9733   //
9734   // If we lower both Select_FPRX_ in a single step, we can instead generate:
9735   //
9736   //   A
9737   //   | \
9738   //   |  C
9739   //   | /|
9740   //   |/ |
9741   //   |  |
9742   //   |  D
9743   //   | /
9744   //   E
9745   //
9746   // A: X = ...; Y = ...
9747   // D: empty
9748   // E: PHI [X, A], [X, C], [Y, D]
9749 
9750   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9751   const DebugLoc &DL = First.getDebugLoc();
9752   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
9753   MachineFunction *F = ThisMBB->getParent();
9754   MachineBasicBlock *FirstMBB = F->CreateMachineBasicBlock(LLVM_BB);
9755   MachineBasicBlock *SecondMBB = F->CreateMachineBasicBlock(LLVM_BB);
9756   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9757   MachineFunction::iterator It = ++ThisMBB->getIterator();
9758   F->insert(It, FirstMBB);
9759   F->insert(It, SecondMBB);
9760   F->insert(It, SinkMBB);
9761 
9762   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
9763   SinkMBB->splice(SinkMBB->begin(), ThisMBB,
9764                   std::next(MachineBasicBlock::iterator(First)),
9765                   ThisMBB->end());
9766   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
9767 
9768   // Fallthrough block for ThisMBB.
9769   ThisMBB->addSuccessor(FirstMBB);
9770   // Fallthrough block for FirstMBB.
9771   FirstMBB->addSuccessor(SecondMBB);
9772   ThisMBB->addSuccessor(SinkMBB);
9773   FirstMBB->addSuccessor(SinkMBB);
9774   // This is fallthrough.
9775   SecondMBB->addSuccessor(SinkMBB);
9776 
9777   auto FirstCC = static_cast<RISCVCC::CondCode>(First.getOperand(3).getImm());
9778   Register FLHS = First.getOperand(1).getReg();
9779   Register FRHS = First.getOperand(2).getReg();
9780   // Insert appropriate branch.
9781   BuildMI(ThisMBB, DL, TII.getBrCond(FirstCC))
9782       .addReg(FLHS)
9783       .addReg(FRHS)
9784       .addMBB(SinkMBB);
9785 
9786   Register SLHS = Second.getOperand(1).getReg();
9787   Register SRHS = Second.getOperand(2).getReg();
9788   Register Op1Reg4 = First.getOperand(4).getReg();
9789   Register Op1Reg5 = First.getOperand(5).getReg();
9790 
9791   auto SecondCC = static_cast<RISCVCC::CondCode>(Second.getOperand(3).getImm());
9792   // Insert appropriate branch.
9793   BuildMI(FirstMBB, DL, TII.getBrCond(SecondCC))
9794       .addReg(SLHS)
9795       .addReg(SRHS)
9796       .addMBB(SinkMBB);
9797 
9798   Register DestReg = Second.getOperand(0).getReg();
9799   Register Op2Reg4 = Second.getOperand(4).getReg();
9800   BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII.get(RISCV::PHI), DestReg)
9801       .addReg(Op1Reg4)
9802       .addMBB(ThisMBB)
9803       .addReg(Op2Reg4)
9804       .addMBB(FirstMBB)
9805       .addReg(Op1Reg5)
9806       .addMBB(SecondMBB);
9807 
9808   // Now remove the Select_FPRX_s.
9809   First.eraseFromParent();
9810   Second.eraseFromParent();
9811   return SinkMBB;
9812 }
9813 
9814 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9815                                            MachineBasicBlock *BB,
9816                                            const RISCVSubtarget &Subtarget) {
9817   // To "insert" Select_* instructions, we actually have to insert the triangle
9818   // control-flow pattern.  The incoming instructions know the destination vreg
9819   // to set, the condition code register to branch on, the true/false values to
9820   // select between, and the condcode to use to select the appropriate branch.
9821   //
9822   // We produce the following control flow:
9823   //     HeadMBB
9824   //     |  \
9825   //     |  IfFalseMBB
9826   //     | /
9827   //    TailMBB
9828   //
9829   // When we find a sequence of selects we attempt to optimize their emission
9830   // by sharing the control flow. Currently we only handle cases where we have
9831   // multiple selects with the exact same condition (same LHS, RHS and CC).
9832   // The selects may be interleaved with other instructions if the other
9833   // instructions meet some requirements we deem safe:
9834   // - They are debug instructions. Otherwise,
9835   // - They do not have side-effects, do not access memory and their inputs do
9836   //   not depend on the results of the select pseudo-instructions.
9837   // The TrueV/FalseV operands of the selects cannot depend on the result of
9838   // previous selects in the sequence.
9839   // These conditions could be further relaxed. See the X86 target for a
9840   // related approach and more information.
9841   //
9842   // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5))
9843   // is checked here and handled by a separate function -
9844   // EmitLoweredCascadedSelect.
9845   Register LHS = MI.getOperand(1).getReg();
9846   Register RHS = MI.getOperand(2).getReg();
9847   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9848 
9849   SmallVector<MachineInstr *, 4> SelectDebugValues;
9850   SmallSet<Register, 4> SelectDests;
9851   SelectDests.insert(MI.getOperand(0).getReg());
9852 
9853   MachineInstr *LastSelectPseudo = &MI;
9854   auto Next = next_nodbg(MI.getIterator(), BB->instr_end());
9855   if (MI.getOpcode() != RISCV::Select_GPR_Using_CC_GPR && Next != BB->end() &&
9856       Next->getOpcode() == MI.getOpcode() &&
9857       Next->getOperand(5).getReg() == MI.getOperand(0).getReg() &&
9858       Next->getOperand(5).isKill()) {
9859     return EmitLoweredCascadedSelect(MI, *Next, BB, Subtarget);
9860   }
9861 
9862   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9863        SequenceMBBI != E; ++SequenceMBBI) {
9864     if (SequenceMBBI->isDebugInstr())
9865       continue;
9866     if (isSelectPseudo(*SequenceMBBI)) {
9867       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9868           SequenceMBBI->getOperand(2).getReg() != RHS ||
9869           SequenceMBBI->getOperand(3).getImm() != CC ||
9870           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9871           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9872         break;
9873       LastSelectPseudo = &*SequenceMBBI;
9874       SequenceMBBI->collectDebugValues(SelectDebugValues);
9875       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9876     } else {
9877       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9878           SequenceMBBI->mayLoadOrStore())
9879         break;
9880       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9881             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9882           }))
9883         break;
9884     }
9885   }
9886 
9887   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9888   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9889   DebugLoc DL = MI.getDebugLoc();
9890   MachineFunction::iterator I = ++BB->getIterator();
9891 
9892   MachineBasicBlock *HeadMBB = BB;
9893   MachineFunction *F = BB->getParent();
9894   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9895   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9896 
9897   F->insert(I, IfFalseMBB);
9898   F->insert(I, TailMBB);
9899 
9900   // Transfer debug instructions associated with the selects to TailMBB.
9901   for (MachineInstr *DebugInstr : SelectDebugValues) {
9902     TailMBB->push_back(DebugInstr->removeFromParent());
9903   }
9904 
9905   // Move all instructions after the sequence to TailMBB.
9906   TailMBB->splice(TailMBB->end(), HeadMBB,
9907                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9908   // Update machine-CFG edges by transferring all successors of the current
9909   // block to the new block which will contain the Phi nodes for the selects.
9910   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9911   // Set the successors for HeadMBB.
9912   HeadMBB->addSuccessor(IfFalseMBB);
9913   HeadMBB->addSuccessor(TailMBB);
9914 
9915   // Insert appropriate branch.
9916   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9917     .addReg(LHS)
9918     .addReg(RHS)
9919     .addMBB(TailMBB);
9920 
9921   // IfFalseMBB just falls through to TailMBB.
9922   IfFalseMBB->addSuccessor(TailMBB);
9923 
9924   // Create PHIs for all of the select pseudo-instructions.
9925   auto SelectMBBI = MI.getIterator();
9926   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9927   auto InsertionPoint = TailMBB->begin();
9928   while (SelectMBBI != SelectEnd) {
9929     auto Next = std::next(SelectMBBI);
9930     if (isSelectPseudo(*SelectMBBI)) {
9931       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9932       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9933               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9934           .addReg(SelectMBBI->getOperand(4).getReg())
9935           .addMBB(HeadMBB)
9936           .addReg(SelectMBBI->getOperand(5).getReg())
9937           .addMBB(IfFalseMBB);
9938       SelectMBBI->eraseFromParent();
9939     }
9940     SelectMBBI = Next;
9941   }
9942 
9943   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9944   return TailMBB;
9945 }
9946 
9947 MachineBasicBlock *
9948 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9949                                                  MachineBasicBlock *BB) const {
9950   switch (MI.getOpcode()) {
9951   default:
9952     llvm_unreachable("Unexpected instr type to insert");
9953   case RISCV::ReadCycleWide:
9954     assert(!Subtarget.is64Bit() &&
9955            "ReadCycleWrite is only to be used on riscv32");
9956     return emitReadCycleWidePseudo(MI, BB);
9957   case RISCV::Select_GPR_Using_CC_GPR:
9958   case RISCV::Select_FPR16_Using_CC_GPR:
9959   case RISCV::Select_FPR32_Using_CC_GPR:
9960   case RISCV::Select_FPR64_Using_CC_GPR:
9961     return emitSelectPseudo(MI, BB, Subtarget);
9962   case RISCV::BuildPairF64Pseudo:
9963     return emitBuildPairF64Pseudo(MI, BB);
9964   case RISCV::SplitF64Pseudo:
9965     return emitSplitF64Pseudo(MI, BB);
9966   case RISCV::PseudoQuietFLE_H:
9967     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9968   case RISCV::PseudoQuietFLT_H:
9969     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9970   case RISCV::PseudoQuietFLE_S:
9971     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9972   case RISCV::PseudoQuietFLT_S:
9973     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9974   case RISCV::PseudoQuietFLE_D:
9975     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9976   case RISCV::PseudoQuietFLT_D:
9977     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9978   }
9979 }
9980 
9981 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9982                                                         SDNode *Node) const {
9983   // Add FRM dependency to any instructions with dynamic rounding mode.
9984   unsigned Opc = MI.getOpcode();
9985   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9986   if (Idx < 0)
9987     return;
9988   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9989     return;
9990   // If the instruction already reads FRM, don't add another read.
9991   if (MI.readsRegister(RISCV::FRM))
9992     return;
9993   MI.addOperand(
9994       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9995 }
9996 
9997 // Calling Convention Implementation.
9998 // The expectations for frontend ABI lowering vary from target to target.
9999 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
10000 // details, but this is a longer term goal. For now, we simply try to keep the
10001 // role of the frontend as simple and well-defined as possible. The rules can
10002 // be summarised as:
10003 // * Never split up large scalar arguments. We handle them here.
10004 // * If a hardfloat calling convention is being used, and the struct may be
10005 // passed in a pair of registers (fp+fp, int+fp), and both registers are
10006 // available, then pass as two separate arguments. If either the GPRs or FPRs
10007 // are exhausted, then pass according to the rule below.
10008 // * If a struct could never be passed in registers or directly in a stack
10009 // slot (as it is larger than 2*XLEN and the floating point rules don't
10010 // apply), then pass it using a pointer with the byval attribute.
10011 // * If a struct is less than 2*XLEN, then coerce to either a two-element
10012 // word-sized array or a 2*XLEN scalar (depending on alignment).
10013 // * The frontend can determine whether a struct is returned by reference or
10014 // not based on its size and fields. If it will be returned by reference, the
10015 // frontend must modify the prototype so a pointer with the sret annotation is
10016 // passed as the first argument. This is not necessary for large scalar
10017 // returns.
10018 // * Struct return values and varargs should be coerced to structs containing
10019 // register-size fields in the same situations they would be for fixed
10020 // arguments.
10021 
10022 static const MCPhysReg ArgGPRs[] = {
10023   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
10024   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
10025 };
10026 static const MCPhysReg ArgFPR16s[] = {
10027   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
10028   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
10029 };
10030 static const MCPhysReg ArgFPR32s[] = {
10031   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
10032   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
10033 };
10034 static const MCPhysReg ArgFPR64s[] = {
10035   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
10036   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
10037 };
10038 // This is an interim calling convention and it may be changed in the future.
10039 static const MCPhysReg ArgVRs[] = {
10040     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
10041     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
10042     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
10043 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
10044                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
10045                                      RISCV::V20M2, RISCV::V22M2};
10046 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
10047                                      RISCV::V20M4};
10048 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
10049 
10050 // Pass a 2*XLEN argument that has been split into two XLEN values through
10051 // registers or the stack as necessary.
10052 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
10053                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
10054                                 MVT ValVT2, MVT LocVT2,
10055                                 ISD::ArgFlagsTy ArgFlags2) {
10056   unsigned XLenInBytes = XLen / 8;
10057   if (Register Reg = State.AllocateReg(ArgGPRs)) {
10058     // At least one half can be passed via register.
10059     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
10060                                      VA1.getLocVT(), CCValAssign::Full));
10061   } else {
10062     // Both halves must be passed on the stack, with proper alignment.
10063     Align StackAlign =
10064         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
10065     State.addLoc(
10066         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
10067                             State.AllocateStack(XLenInBytes, StackAlign),
10068                             VA1.getLocVT(), CCValAssign::Full));
10069     State.addLoc(CCValAssign::getMem(
10070         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
10071         LocVT2, CCValAssign::Full));
10072     return false;
10073   }
10074 
10075   if (Register Reg = State.AllocateReg(ArgGPRs)) {
10076     // The second half can also be passed via register.
10077     State.addLoc(
10078         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
10079   } else {
10080     // The second half is passed via the stack, without additional alignment.
10081     State.addLoc(CCValAssign::getMem(
10082         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
10083         LocVT2, CCValAssign::Full));
10084   }
10085 
10086   return false;
10087 }
10088 
10089 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
10090                                Optional<unsigned> FirstMaskArgument,
10091                                CCState &State, const RISCVTargetLowering &TLI) {
10092   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
10093   if (RC == &RISCV::VRRegClass) {
10094     // Assign the first mask argument to V0.
10095     // This is an interim calling convention and it may be changed in the
10096     // future.
10097     if (FirstMaskArgument && ValNo == *FirstMaskArgument)
10098       return State.AllocateReg(RISCV::V0);
10099     return State.AllocateReg(ArgVRs);
10100   }
10101   if (RC == &RISCV::VRM2RegClass)
10102     return State.AllocateReg(ArgVRM2s);
10103   if (RC == &RISCV::VRM4RegClass)
10104     return State.AllocateReg(ArgVRM4s);
10105   if (RC == &RISCV::VRM8RegClass)
10106     return State.AllocateReg(ArgVRM8s);
10107   llvm_unreachable("Unhandled register class for ValueType");
10108 }
10109 
10110 // Implements the RISC-V calling convention. Returns true upon failure.
10111 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
10112                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
10113                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
10114                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
10115                      Optional<unsigned> FirstMaskArgument) {
10116   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
10117   assert(XLen == 32 || XLen == 64);
10118   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
10119 
10120   // Any return value split in to more than two values can't be returned
10121   // directly. Vectors are returned via the available vector registers.
10122   if (!LocVT.isVector() && IsRet && ValNo > 1)
10123     return true;
10124 
10125   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
10126   // variadic argument, or if no F16/F32 argument registers are available.
10127   bool UseGPRForF16_F32 = true;
10128   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
10129   // variadic argument, or if no F64 argument registers are available.
10130   bool UseGPRForF64 = true;
10131 
10132   switch (ABI) {
10133   default:
10134     llvm_unreachable("Unexpected ABI");
10135   case RISCVABI::ABI_ILP32:
10136   case RISCVABI::ABI_LP64:
10137     break;
10138   case RISCVABI::ABI_ILP32F:
10139   case RISCVABI::ABI_LP64F:
10140     UseGPRForF16_F32 = !IsFixed;
10141     break;
10142   case RISCVABI::ABI_ILP32D:
10143   case RISCVABI::ABI_LP64D:
10144     UseGPRForF16_F32 = !IsFixed;
10145     UseGPRForF64 = !IsFixed;
10146     break;
10147   }
10148 
10149   // FPR16, FPR32, and FPR64 alias each other.
10150   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
10151     UseGPRForF16_F32 = true;
10152     UseGPRForF64 = true;
10153   }
10154 
10155   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
10156   // similar local variables rather than directly checking against the target
10157   // ABI.
10158 
10159   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
10160     LocVT = XLenVT;
10161     LocInfo = CCValAssign::BCvt;
10162   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
10163     LocVT = MVT::i64;
10164     LocInfo = CCValAssign::BCvt;
10165   }
10166 
10167   // If this is a variadic argument, the RISC-V calling convention requires
10168   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
10169   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
10170   // be used regardless of whether the original argument was split during
10171   // legalisation or not. The argument will not be passed by registers if the
10172   // original type is larger than 2*XLEN, so the register alignment rule does
10173   // not apply.
10174   unsigned TwoXLenInBytes = (2 * XLen) / 8;
10175   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
10176       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
10177     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
10178     // Skip 'odd' register if necessary.
10179     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
10180       State.AllocateReg(ArgGPRs);
10181   }
10182 
10183   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
10184   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
10185       State.getPendingArgFlags();
10186 
10187   assert(PendingLocs.size() == PendingArgFlags.size() &&
10188          "PendingLocs and PendingArgFlags out of sync");
10189 
10190   // Handle passing f64 on RV32D with a soft float ABI or when floating point
10191   // registers are exhausted.
10192   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
10193     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
10194            "Can't lower f64 if it is split");
10195     // Depending on available argument GPRS, f64 may be passed in a pair of
10196     // GPRs, split between a GPR and the stack, or passed completely on the
10197     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
10198     // cases.
10199     Register Reg = State.AllocateReg(ArgGPRs);
10200     LocVT = MVT::i32;
10201     if (!Reg) {
10202       unsigned StackOffset = State.AllocateStack(8, Align(8));
10203       State.addLoc(
10204           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10205       return false;
10206     }
10207     if (!State.AllocateReg(ArgGPRs))
10208       State.AllocateStack(4, Align(4));
10209     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10210     return false;
10211   }
10212 
10213   // Fixed-length vectors are located in the corresponding scalable-vector
10214   // container types.
10215   if (ValVT.isFixedLengthVector())
10216     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10217 
10218   // Split arguments might be passed indirectly, so keep track of the pending
10219   // values. Split vectors are passed via a mix of registers and indirectly, so
10220   // treat them as we would any other argument.
10221   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
10222     LocVT = XLenVT;
10223     LocInfo = CCValAssign::Indirect;
10224     PendingLocs.push_back(
10225         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
10226     PendingArgFlags.push_back(ArgFlags);
10227     if (!ArgFlags.isSplitEnd()) {
10228       return false;
10229     }
10230   }
10231 
10232   // If the split argument only had two elements, it should be passed directly
10233   // in registers or on the stack.
10234   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
10235       PendingLocs.size() <= 2) {
10236     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
10237     // Apply the normal calling convention rules to the first half of the
10238     // split argument.
10239     CCValAssign VA = PendingLocs[0];
10240     ISD::ArgFlagsTy AF = PendingArgFlags[0];
10241     PendingLocs.clear();
10242     PendingArgFlags.clear();
10243     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
10244                                ArgFlags);
10245   }
10246 
10247   // Allocate to a register if possible, or else a stack slot.
10248   Register Reg;
10249   unsigned StoreSizeBytes = XLen / 8;
10250   Align StackAlign = Align(XLen / 8);
10251 
10252   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
10253     Reg = State.AllocateReg(ArgFPR16s);
10254   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
10255     Reg = State.AllocateReg(ArgFPR32s);
10256   else if (ValVT == MVT::f64 && !UseGPRForF64)
10257     Reg = State.AllocateReg(ArgFPR64s);
10258   else if (ValVT.isVector()) {
10259     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
10260     if (!Reg) {
10261       // For return values, the vector must be passed fully via registers or
10262       // via the stack.
10263       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
10264       // but we're using all of them.
10265       if (IsRet)
10266         return true;
10267       // Try using a GPR to pass the address
10268       if ((Reg = State.AllocateReg(ArgGPRs))) {
10269         LocVT = XLenVT;
10270         LocInfo = CCValAssign::Indirect;
10271       } else if (ValVT.isScalableVector()) {
10272         LocVT = XLenVT;
10273         LocInfo = CCValAssign::Indirect;
10274       } else {
10275         // Pass fixed-length vectors on the stack.
10276         LocVT = ValVT;
10277         StoreSizeBytes = ValVT.getStoreSize();
10278         // Align vectors to their element sizes, being careful for vXi1
10279         // vectors.
10280         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10281       }
10282     }
10283   } else {
10284     Reg = State.AllocateReg(ArgGPRs);
10285   }
10286 
10287   unsigned StackOffset =
10288       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
10289 
10290   // If we reach this point and PendingLocs is non-empty, we must be at the
10291   // end of a split argument that must be passed indirectly.
10292   if (!PendingLocs.empty()) {
10293     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
10294     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
10295 
10296     for (auto &It : PendingLocs) {
10297       if (Reg)
10298         It.convertToReg(Reg);
10299       else
10300         It.convertToMem(StackOffset);
10301       State.addLoc(It);
10302     }
10303     PendingLocs.clear();
10304     PendingArgFlags.clear();
10305     return false;
10306   }
10307 
10308   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
10309           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
10310          "Expected an XLenVT or vector types at this stage");
10311 
10312   if (Reg) {
10313     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10314     return false;
10315   }
10316 
10317   // When a floating-point value is passed on the stack, no bit-conversion is
10318   // needed.
10319   if (ValVT.isFloatingPoint()) {
10320     LocVT = ValVT;
10321     LocInfo = CCValAssign::Full;
10322   }
10323   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10324   return false;
10325 }
10326 
10327 template <typename ArgTy>
10328 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
10329   for (const auto &ArgIdx : enumerate(Args)) {
10330     MVT ArgVT = ArgIdx.value().VT;
10331     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
10332       return ArgIdx.index();
10333   }
10334   return None;
10335 }
10336 
10337 void RISCVTargetLowering::analyzeInputArgs(
10338     MachineFunction &MF, CCState &CCInfo,
10339     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
10340     RISCVCCAssignFn Fn) const {
10341   unsigned NumArgs = Ins.size();
10342   FunctionType *FType = MF.getFunction().getFunctionType();
10343 
10344   Optional<unsigned> FirstMaskArgument;
10345   if (Subtarget.hasVInstructions())
10346     FirstMaskArgument = preAssignMask(Ins);
10347 
10348   for (unsigned i = 0; i != NumArgs; ++i) {
10349     MVT ArgVT = Ins[i].VT;
10350     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
10351 
10352     Type *ArgTy = nullptr;
10353     if (IsRet)
10354       ArgTy = FType->getReturnType();
10355     else if (Ins[i].isOrigArg())
10356       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
10357 
10358     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10359     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10360            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
10361            FirstMaskArgument)) {
10362       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
10363                         << EVT(ArgVT).getEVTString() << '\n');
10364       llvm_unreachable(nullptr);
10365     }
10366   }
10367 }
10368 
10369 void RISCVTargetLowering::analyzeOutputArgs(
10370     MachineFunction &MF, CCState &CCInfo,
10371     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
10372     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
10373   unsigned NumArgs = Outs.size();
10374 
10375   Optional<unsigned> FirstMaskArgument;
10376   if (Subtarget.hasVInstructions())
10377     FirstMaskArgument = preAssignMask(Outs);
10378 
10379   for (unsigned i = 0; i != NumArgs; i++) {
10380     MVT ArgVT = Outs[i].VT;
10381     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10382     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
10383 
10384     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10385     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10386            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
10387            FirstMaskArgument)) {
10388       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
10389                         << EVT(ArgVT).getEVTString() << "\n");
10390       llvm_unreachable(nullptr);
10391     }
10392   }
10393 }
10394 
10395 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
10396 // values.
10397 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
10398                                    const CCValAssign &VA, const SDLoc &DL,
10399                                    const RISCVSubtarget &Subtarget) {
10400   switch (VA.getLocInfo()) {
10401   default:
10402     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10403   case CCValAssign::Full:
10404     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
10405       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
10406     break;
10407   case CCValAssign::BCvt:
10408     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10409       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
10410     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10411       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
10412     else
10413       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
10414     break;
10415   }
10416   return Val;
10417 }
10418 
10419 // The caller is responsible for loading the full value if the argument is
10420 // passed with CCValAssign::Indirect.
10421 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
10422                                 const CCValAssign &VA, const SDLoc &DL,
10423                                 const RISCVTargetLowering &TLI) {
10424   MachineFunction &MF = DAG.getMachineFunction();
10425   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10426   EVT LocVT = VA.getLocVT();
10427   SDValue Val;
10428   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
10429   Register VReg = RegInfo.createVirtualRegister(RC);
10430   RegInfo.addLiveIn(VA.getLocReg(), VReg);
10431   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
10432 
10433   if (VA.getLocInfo() == CCValAssign::Indirect)
10434     return Val;
10435 
10436   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
10437 }
10438 
10439 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
10440                                    const CCValAssign &VA, const SDLoc &DL,
10441                                    const RISCVSubtarget &Subtarget) {
10442   EVT LocVT = VA.getLocVT();
10443 
10444   switch (VA.getLocInfo()) {
10445   default:
10446     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10447   case CCValAssign::Full:
10448     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
10449       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
10450     break;
10451   case CCValAssign::BCvt:
10452     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10453       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
10454     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10455       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
10456     else
10457       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
10458     break;
10459   }
10460   return Val;
10461 }
10462 
10463 // The caller is responsible for loading the full value if the argument is
10464 // passed with CCValAssign::Indirect.
10465 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
10466                                 const CCValAssign &VA, const SDLoc &DL) {
10467   MachineFunction &MF = DAG.getMachineFunction();
10468   MachineFrameInfo &MFI = MF.getFrameInfo();
10469   EVT LocVT = VA.getLocVT();
10470   EVT ValVT = VA.getValVT();
10471   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
10472   if (ValVT.isScalableVector()) {
10473     // When the value is a scalable vector, we save the pointer which points to
10474     // the scalable vector value in the stack. The ValVT will be the pointer
10475     // type, instead of the scalable vector type.
10476     ValVT = LocVT;
10477   }
10478   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
10479                                  /*IsImmutable=*/true);
10480   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
10481   SDValue Val;
10482 
10483   ISD::LoadExtType ExtType;
10484   switch (VA.getLocInfo()) {
10485   default:
10486     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10487   case CCValAssign::Full:
10488   case CCValAssign::Indirect:
10489   case CCValAssign::BCvt:
10490     ExtType = ISD::NON_EXTLOAD;
10491     break;
10492   }
10493   Val = DAG.getExtLoad(
10494       ExtType, DL, LocVT, Chain, FIN,
10495       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
10496   return Val;
10497 }
10498 
10499 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
10500                                        const CCValAssign &VA, const SDLoc &DL) {
10501   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
10502          "Unexpected VA");
10503   MachineFunction &MF = DAG.getMachineFunction();
10504   MachineFrameInfo &MFI = MF.getFrameInfo();
10505   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10506 
10507   if (VA.isMemLoc()) {
10508     // f64 is passed on the stack.
10509     int FI =
10510         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
10511     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10512     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
10513                        MachinePointerInfo::getFixedStack(MF, FI));
10514   }
10515 
10516   assert(VA.isRegLoc() && "Expected register VA assignment");
10517 
10518   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10519   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
10520   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
10521   SDValue Hi;
10522   if (VA.getLocReg() == RISCV::X17) {
10523     // Second half of f64 is passed on the stack.
10524     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
10525     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10526     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10527                      MachinePointerInfo::getFixedStack(MF, FI));
10528   } else {
10529     // Second half of f64 is passed in another GPR.
10530     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10531     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10532     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10533   }
10534   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10535 }
10536 
10537 // FastCC has less than 1% performance improvement for some particular
10538 // benchmark. But theoretically, it may has benenfit for some cases.
10539 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10540                             unsigned ValNo, MVT ValVT, MVT LocVT,
10541                             CCValAssign::LocInfo LocInfo,
10542                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10543                             bool IsFixed, bool IsRet, Type *OrigTy,
10544                             const RISCVTargetLowering &TLI,
10545                             Optional<unsigned> FirstMaskArgument) {
10546 
10547   // X5 and X6 might be used for save-restore libcall.
10548   static const MCPhysReg GPRList[] = {
10549       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10550       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10551       RISCV::X29, RISCV::X30, RISCV::X31};
10552 
10553   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10554     if (unsigned Reg = State.AllocateReg(GPRList)) {
10555       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10556       return false;
10557     }
10558   }
10559 
10560   if (LocVT == MVT::f16) {
10561     static const MCPhysReg FPR16List[] = {
10562         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10563         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10564         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10565         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10566     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10567       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10568       return false;
10569     }
10570   }
10571 
10572   if (LocVT == MVT::f32) {
10573     static const MCPhysReg FPR32List[] = {
10574         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10575         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10576         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10577         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10578     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10579       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10580       return false;
10581     }
10582   }
10583 
10584   if (LocVT == MVT::f64) {
10585     static const MCPhysReg FPR64List[] = {
10586         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10587         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10588         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10589         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10590     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10591       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10592       return false;
10593     }
10594   }
10595 
10596   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10597     unsigned Offset4 = State.AllocateStack(4, Align(4));
10598     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10599     return false;
10600   }
10601 
10602   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10603     unsigned Offset5 = State.AllocateStack(8, Align(8));
10604     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10605     return false;
10606   }
10607 
10608   if (LocVT.isVector()) {
10609     if (unsigned Reg =
10610             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10611       // Fixed-length vectors are located in the corresponding scalable-vector
10612       // container types.
10613       if (ValVT.isFixedLengthVector())
10614         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10615       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10616     } else {
10617       // Try and pass the address via a "fast" GPR.
10618       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10619         LocInfo = CCValAssign::Indirect;
10620         LocVT = TLI.getSubtarget().getXLenVT();
10621         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10622       } else if (ValVT.isFixedLengthVector()) {
10623         auto StackAlign =
10624             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10625         unsigned StackOffset =
10626             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10627         State.addLoc(
10628             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10629       } else {
10630         // Can't pass scalable vectors on the stack.
10631         return true;
10632       }
10633     }
10634 
10635     return false;
10636   }
10637 
10638   return true; // CC didn't match.
10639 }
10640 
10641 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10642                          CCValAssign::LocInfo LocInfo,
10643                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10644 
10645   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10646     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10647     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10648     static const MCPhysReg GPRList[] = {
10649         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10650         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10651     if (unsigned Reg = State.AllocateReg(GPRList)) {
10652       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10653       return false;
10654     }
10655   }
10656 
10657   if (LocVT == MVT::f32) {
10658     // Pass in STG registers: F1, ..., F6
10659     //                        fs0 ... fs5
10660     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10661                                           RISCV::F18_F, RISCV::F19_F,
10662                                           RISCV::F20_F, RISCV::F21_F};
10663     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10664       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10665       return false;
10666     }
10667   }
10668 
10669   if (LocVT == MVT::f64) {
10670     // Pass in STG registers: D1, ..., D6
10671     //                        fs6 ... fs11
10672     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10673                                           RISCV::F24_D, RISCV::F25_D,
10674                                           RISCV::F26_D, RISCV::F27_D};
10675     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10676       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10677       return false;
10678     }
10679   }
10680 
10681   report_fatal_error("No registers left in GHC calling convention");
10682   return true;
10683 }
10684 
10685 // Transform physical registers into virtual registers.
10686 SDValue RISCVTargetLowering::LowerFormalArguments(
10687     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10688     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10689     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10690 
10691   MachineFunction &MF = DAG.getMachineFunction();
10692 
10693   switch (CallConv) {
10694   default:
10695     report_fatal_error("Unsupported calling convention");
10696   case CallingConv::C:
10697   case CallingConv::Fast:
10698     break;
10699   case CallingConv::GHC:
10700     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10701         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10702       report_fatal_error(
10703         "GHC calling convention requires the F and D instruction set extensions");
10704   }
10705 
10706   const Function &Func = MF.getFunction();
10707   if (Func.hasFnAttribute("interrupt")) {
10708     if (!Func.arg_empty())
10709       report_fatal_error(
10710         "Functions with the interrupt attribute cannot have arguments!");
10711 
10712     StringRef Kind =
10713       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10714 
10715     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10716       report_fatal_error(
10717         "Function interrupt attribute argument not supported!");
10718   }
10719 
10720   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10721   MVT XLenVT = Subtarget.getXLenVT();
10722   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10723   // Used with vargs to acumulate store chains.
10724   std::vector<SDValue> OutChains;
10725 
10726   // Assign locations to all of the incoming arguments.
10727   SmallVector<CCValAssign, 16> ArgLocs;
10728   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10729 
10730   if (CallConv == CallingConv::GHC)
10731     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10732   else
10733     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10734                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10735                                                    : CC_RISCV);
10736 
10737   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10738     CCValAssign &VA = ArgLocs[i];
10739     SDValue ArgValue;
10740     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10741     // case.
10742     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10743       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10744     else if (VA.isRegLoc())
10745       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10746     else
10747       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10748 
10749     if (VA.getLocInfo() == CCValAssign::Indirect) {
10750       // If the original argument was split and passed by reference (e.g. i128
10751       // on RV32), we need to load all parts of it here (using the same
10752       // address). Vectors may be partly split to registers and partly to the
10753       // stack, in which case the base address is partly offset and subsequent
10754       // stores are relative to that.
10755       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10756                                    MachinePointerInfo()));
10757       unsigned ArgIndex = Ins[i].OrigArgIndex;
10758       unsigned ArgPartOffset = Ins[i].PartOffset;
10759       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10760       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10761         CCValAssign &PartVA = ArgLocs[i + 1];
10762         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10763         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10764         if (PartVA.getValVT().isScalableVector())
10765           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10766         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10767         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10768                                      MachinePointerInfo()));
10769         ++i;
10770       }
10771       continue;
10772     }
10773     InVals.push_back(ArgValue);
10774   }
10775 
10776   if (IsVarArg) {
10777     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10778     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10779     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10780     MachineFrameInfo &MFI = MF.getFrameInfo();
10781     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10782     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10783 
10784     // Offset of the first variable argument from stack pointer, and size of
10785     // the vararg save area. For now, the varargs save area is either zero or
10786     // large enough to hold a0-a7.
10787     int VaArgOffset, VarArgsSaveSize;
10788 
10789     // If all registers are allocated, then all varargs must be passed on the
10790     // stack and we don't need to save any argregs.
10791     if (ArgRegs.size() == Idx) {
10792       VaArgOffset = CCInfo.getNextStackOffset();
10793       VarArgsSaveSize = 0;
10794     } else {
10795       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10796       VaArgOffset = -VarArgsSaveSize;
10797     }
10798 
10799     // Record the frame index of the first variable argument
10800     // which is a value necessary to VASTART.
10801     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10802     RVFI->setVarArgsFrameIndex(FI);
10803 
10804     // If saving an odd number of registers then create an extra stack slot to
10805     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10806     // offsets to even-numbered registered remain 2*XLEN-aligned.
10807     if (Idx % 2) {
10808       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10809       VarArgsSaveSize += XLenInBytes;
10810     }
10811 
10812     // Copy the integer registers that may have been used for passing varargs
10813     // to the vararg save area.
10814     for (unsigned I = Idx; I < ArgRegs.size();
10815          ++I, VaArgOffset += XLenInBytes) {
10816       const Register Reg = RegInfo.createVirtualRegister(RC);
10817       RegInfo.addLiveIn(ArgRegs[I], Reg);
10818       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10819       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10820       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10821       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10822                                    MachinePointerInfo::getFixedStack(MF, FI));
10823       cast<StoreSDNode>(Store.getNode())
10824           ->getMemOperand()
10825           ->setValue((Value *)nullptr);
10826       OutChains.push_back(Store);
10827     }
10828     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10829   }
10830 
10831   // All stores are grouped in one node to allow the matching between
10832   // the size of Ins and InVals. This only happens for vararg functions.
10833   if (!OutChains.empty()) {
10834     OutChains.push_back(Chain);
10835     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10836   }
10837 
10838   return Chain;
10839 }
10840 
10841 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10842 /// for tail call optimization.
10843 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10844 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10845     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10846     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10847 
10848   auto &Callee = CLI.Callee;
10849   auto CalleeCC = CLI.CallConv;
10850   auto &Outs = CLI.Outs;
10851   auto &Caller = MF.getFunction();
10852   auto CallerCC = Caller.getCallingConv();
10853 
10854   // Exception-handling functions need a special set of instructions to
10855   // indicate a return to the hardware. Tail-calling another function would
10856   // probably break this.
10857   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10858   // should be expanded as new function attributes are introduced.
10859   if (Caller.hasFnAttribute("interrupt"))
10860     return false;
10861 
10862   // Do not tail call opt if the stack is used to pass parameters.
10863   if (CCInfo.getNextStackOffset() != 0)
10864     return false;
10865 
10866   // Do not tail call opt if any parameters need to be passed indirectly.
10867   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10868   // passed indirectly. So the address of the value will be passed in a
10869   // register, or if not available, then the address is put on the stack. In
10870   // order to pass indirectly, space on the stack often needs to be allocated
10871   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10872   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10873   // are passed CCValAssign::Indirect.
10874   for (auto &VA : ArgLocs)
10875     if (VA.getLocInfo() == CCValAssign::Indirect)
10876       return false;
10877 
10878   // Do not tail call opt if either caller or callee uses struct return
10879   // semantics.
10880   auto IsCallerStructRet = Caller.hasStructRetAttr();
10881   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10882   if (IsCallerStructRet || IsCalleeStructRet)
10883     return false;
10884 
10885   // Externally-defined functions with weak linkage should not be
10886   // tail-called. The behaviour of branch instructions in this situation (as
10887   // used for tail calls) is implementation-defined, so we cannot rely on the
10888   // linker replacing the tail call with a return.
10889   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10890     const GlobalValue *GV = G->getGlobal();
10891     if (GV->hasExternalWeakLinkage())
10892       return false;
10893   }
10894 
10895   // The callee has to preserve all registers the caller needs to preserve.
10896   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10897   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10898   if (CalleeCC != CallerCC) {
10899     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10900     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10901       return false;
10902   }
10903 
10904   // Byval parameters hand the function a pointer directly into the stack area
10905   // we want to reuse during a tail call. Working around this *is* possible
10906   // but less efficient and uglier in LowerCall.
10907   for (auto &Arg : Outs)
10908     if (Arg.Flags.isByVal())
10909       return false;
10910 
10911   return true;
10912 }
10913 
10914 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10915   return DAG.getDataLayout().getPrefTypeAlign(
10916       VT.getTypeForEVT(*DAG.getContext()));
10917 }
10918 
10919 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10920 // and output parameter nodes.
10921 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10922                                        SmallVectorImpl<SDValue> &InVals) const {
10923   SelectionDAG &DAG = CLI.DAG;
10924   SDLoc &DL = CLI.DL;
10925   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10926   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10927   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10928   SDValue Chain = CLI.Chain;
10929   SDValue Callee = CLI.Callee;
10930   bool &IsTailCall = CLI.IsTailCall;
10931   CallingConv::ID CallConv = CLI.CallConv;
10932   bool IsVarArg = CLI.IsVarArg;
10933   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10934   MVT XLenVT = Subtarget.getXLenVT();
10935 
10936   MachineFunction &MF = DAG.getMachineFunction();
10937 
10938   // Analyze the operands of the call, assigning locations to each operand.
10939   SmallVector<CCValAssign, 16> ArgLocs;
10940   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10941 
10942   if (CallConv == CallingConv::GHC)
10943     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10944   else
10945     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10946                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10947                                                     : CC_RISCV);
10948 
10949   // Check if it's really possible to do a tail call.
10950   if (IsTailCall)
10951     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10952 
10953   if (IsTailCall)
10954     ++NumTailCalls;
10955   else if (CLI.CB && CLI.CB->isMustTailCall())
10956     report_fatal_error("failed to perform tail call elimination on a call "
10957                        "site marked musttail");
10958 
10959   // Get a count of how many bytes are to be pushed on the stack.
10960   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10961 
10962   // Create local copies for byval args
10963   SmallVector<SDValue, 8> ByValArgs;
10964   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10965     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10966     if (!Flags.isByVal())
10967       continue;
10968 
10969     SDValue Arg = OutVals[i];
10970     unsigned Size = Flags.getByValSize();
10971     Align Alignment = Flags.getNonZeroByValAlign();
10972 
10973     int FI =
10974         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10975     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10976     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10977 
10978     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10979                           /*IsVolatile=*/false,
10980                           /*AlwaysInline=*/false, IsTailCall,
10981                           MachinePointerInfo(), MachinePointerInfo());
10982     ByValArgs.push_back(FIPtr);
10983   }
10984 
10985   if (!IsTailCall)
10986     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10987 
10988   // Copy argument values to their designated locations.
10989   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10990   SmallVector<SDValue, 8> MemOpChains;
10991   SDValue StackPtr;
10992   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10993     CCValAssign &VA = ArgLocs[i];
10994     SDValue ArgValue = OutVals[i];
10995     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10996 
10997     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10998     bool IsF64OnRV32DSoftABI =
10999         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
11000     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
11001       SDValue SplitF64 = DAG.getNode(
11002           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
11003       SDValue Lo = SplitF64.getValue(0);
11004       SDValue Hi = SplitF64.getValue(1);
11005 
11006       Register RegLo = VA.getLocReg();
11007       RegsToPass.push_back(std::make_pair(RegLo, Lo));
11008 
11009       if (RegLo == RISCV::X17) {
11010         // Second half of f64 is passed on the stack.
11011         // Work out the address of the stack slot.
11012         if (!StackPtr.getNode())
11013           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
11014         // Emit the store.
11015         MemOpChains.push_back(
11016             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
11017       } else {
11018         // Second half of f64 is passed in another GPR.
11019         assert(RegLo < RISCV::X31 && "Invalid register pair");
11020         Register RegHigh = RegLo + 1;
11021         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
11022       }
11023       continue;
11024     }
11025 
11026     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
11027     // as any other MemLoc.
11028 
11029     // Promote the value if needed.
11030     // For now, only handle fully promoted and indirect arguments.
11031     if (VA.getLocInfo() == CCValAssign::Indirect) {
11032       // Store the argument in a stack slot and pass its address.
11033       Align StackAlign =
11034           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
11035                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
11036       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
11037       // If the original argument was split (e.g. i128), we need
11038       // to store the required parts of it here (and pass just one address).
11039       // Vectors may be partly split to registers and partly to the stack, in
11040       // which case the base address is partly offset and subsequent stores are
11041       // relative to that.
11042       unsigned ArgIndex = Outs[i].OrigArgIndex;
11043       unsigned ArgPartOffset = Outs[i].PartOffset;
11044       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
11045       // Calculate the total size to store. We don't have access to what we're
11046       // actually storing other than performing the loop and collecting the
11047       // info.
11048       SmallVector<std::pair<SDValue, SDValue>> Parts;
11049       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
11050         SDValue PartValue = OutVals[i + 1];
11051         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
11052         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
11053         EVT PartVT = PartValue.getValueType();
11054         if (PartVT.isScalableVector())
11055           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
11056         StoredSize += PartVT.getStoreSize();
11057         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
11058         Parts.push_back(std::make_pair(PartValue, Offset));
11059         ++i;
11060       }
11061       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
11062       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
11063       MemOpChains.push_back(
11064           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
11065                        MachinePointerInfo::getFixedStack(MF, FI)));
11066       for (const auto &Part : Parts) {
11067         SDValue PartValue = Part.first;
11068         SDValue PartOffset = Part.second;
11069         SDValue Address =
11070             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
11071         MemOpChains.push_back(
11072             DAG.getStore(Chain, DL, PartValue, Address,
11073                          MachinePointerInfo::getFixedStack(MF, FI)));
11074       }
11075       ArgValue = SpillSlot;
11076     } else {
11077       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
11078     }
11079 
11080     // Use local copy if it is a byval arg.
11081     if (Flags.isByVal())
11082       ArgValue = ByValArgs[j++];
11083 
11084     if (VA.isRegLoc()) {
11085       // Queue up the argument copies and emit them at the end.
11086       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
11087     } else {
11088       assert(VA.isMemLoc() && "Argument not register or memory");
11089       assert(!IsTailCall && "Tail call not allowed if stack is used "
11090                             "for passing parameters");
11091 
11092       // Work out the address of the stack slot.
11093       if (!StackPtr.getNode())
11094         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
11095       SDValue Address =
11096           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
11097                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
11098 
11099       // Emit the store.
11100       MemOpChains.push_back(
11101           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
11102     }
11103   }
11104 
11105   // Join the stores, which are independent of one another.
11106   if (!MemOpChains.empty())
11107     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
11108 
11109   SDValue Glue;
11110 
11111   // Build a sequence of copy-to-reg nodes, chained and glued together.
11112   for (auto &Reg : RegsToPass) {
11113     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
11114     Glue = Chain.getValue(1);
11115   }
11116 
11117   // Validate that none of the argument registers have been marked as
11118   // reserved, if so report an error. Do the same for the return address if this
11119   // is not a tailcall.
11120   validateCCReservedRegs(RegsToPass, MF);
11121   if (!IsTailCall &&
11122       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
11123     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11124         MF.getFunction(),
11125         "Return address register required, but has been reserved."});
11126 
11127   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
11128   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
11129   // split it and then direct call can be matched by PseudoCALL.
11130   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
11131     const GlobalValue *GV = S->getGlobal();
11132 
11133     unsigned OpFlags = RISCVII::MO_CALL;
11134     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
11135       OpFlags = RISCVII::MO_PLT;
11136 
11137     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
11138   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
11139     unsigned OpFlags = RISCVII::MO_CALL;
11140 
11141     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
11142                                                  nullptr))
11143       OpFlags = RISCVII::MO_PLT;
11144 
11145     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
11146   }
11147 
11148   // The first call operand is the chain and the second is the target address.
11149   SmallVector<SDValue, 8> Ops;
11150   Ops.push_back(Chain);
11151   Ops.push_back(Callee);
11152 
11153   // Add argument registers to the end of the list so that they are
11154   // known live into the call.
11155   for (auto &Reg : RegsToPass)
11156     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
11157 
11158   if (!IsTailCall) {
11159     // Add a register mask operand representing the call-preserved registers.
11160     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
11161     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
11162     assert(Mask && "Missing call preserved mask for calling convention");
11163     Ops.push_back(DAG.getRegisterMask(Mask));
11164   }
11165 
11166   // Glue the call to the argument copies, if any.
11167   if (Glue.getNode())
11168     Ops.push_back(Glue);
11169 
11170   // Emit the call.
11171   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11172 
11173   if (IsTailCall) {
11174     MF.getFrameInfo().setHasTailCall();
11175     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
11176   }
11177 
11178   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
11179   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
11180   Glue = Chain.getValue(1);
11181 
11182   // Mark the end of the call, which is glued to the call itself.
11183   Chain = DAG.getCALLSEQ_END(Chain,
11184                              DAG.getConstant(NumBytes, DL, PtrVT, true),
11185                              DAG.getConstant(0, DL, PtrVT, true),
11186                              Glue, DL);
11187   Glue = Chain.getValue(1);
11188 
11189   // Assign locations to each value returned by this call.
11190   SmallVector<CCValAssign, 16> RVLocs;
11191   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
11192   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
11193 
11194   // Copy all of the result registers out of their specified physreg.
11195   for (auto &VA : RVLocs) {
11196     // Copy the value out
11197     SDValue RetValue =
11198         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
11199     // Glue the RetValue to the end of the call sequence
11200     Chain = RetValue.getValue(1);
11201     Glue = RetValue.getValue(2);
11202 
11203     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11204       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
11205       SDValue RetValue2 =
11206           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
11207       Chain = RetValue2.getValue(1);
11208       Glue = RetValue2.getValue(2);
11209       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
11210                              RetValue2);
11211     }
11212 
11213     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
11214 
11215     InVals.push_back(RetValue);
11216   }
11217 
11218   return Chain;
11219 }
11220 
11221 bool RISCVTargetLowering::CanLowerReturn(
11222     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
11223     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
11224   SmallVector<CCValAssign, 16> RVLocs;
11225   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
11226 
11227   Optional<unsigned> FirstMaskArgument;
11228   if (Subtarget.hasVInstructions())
11229     FirstMaskArgument = preAssignMask(Outs);
11230 
11231   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
11232     MVT VT = Outs[i].VT;
11233     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
11234     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
11235     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
11236                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
11237                  *this, FirstMaskArgument))
11238       return false;
11239   }
11240   return true;
11241 }
11242 
11243 SDValue
11244 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
11245                                  bool IsVarArg,
11246                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
11247                                  const SmallVectorImpl<SDValue> &OutVals,
11248                                  const SDLoc &DL, SelectionDAG &DAG) const {
11249   const MachineFunction &MF = DAG.getMachineFunction();
11250   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11251 
11252   // Stores the assignment of the return value to a location.
11253   SmallVector<CCValAssign, 16> RVLocs;
11254 
11255   // Info about the registers and stack slot.
11256   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
11257                  *DAG.getContext());
11258 
11259   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
11260                     nullptr, CC_RISCV);
11261 
11262   if (CallConv == CallingConv::GHC && !RVLocs.empty())
11263     report_fatal_error("GHC functions return void only");
11264 
11265   SDValue Glue;
11266   SmallVector<SDValue, 4> RetOps(1, Chain);
11267 
11268   // Copy the result values into the output registers.
11269   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
11270     SDValue Val = OutVals[i];
11271     CCValAssign &VA = RVLocs[i];
11272     assert(VA.isRegLoc() && "Can only return in registers!");
11273 
11274     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11275       // Handle returning f64 on RV32D with a soft float ABI.
11276       assert(VA.isRegLoc() && "Expected return via registers");
11277       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
11278                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
11279       SDValue Lo = SplitF64.getValue(0);
11280       SDValue Hi = SplitF64.getValue(1);
11281       Register RegLo = VA.getLocReg();
11282       assert(RegLo < RISCV::X31 && "Invalid register pair");
11283       Register RegHi = RegLo + 1;
11284 
11285       if (STI.isRegisterReservedByUser(RegLo) ||
11286           STI.isRegisterReservedByUser(RegHi))
11287         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11288             MF.getFunction(),
11289             "Return value register required, but has been reserved."});
11290 
11291       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
11292       Glue = Chain.getValue(1);
11293       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
11294       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
11295       Glue = Chain.getValue(1);
11296       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
11297     } else {
11298       // Handle a 'normal' return.
11299       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
11300       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
11301 
11302       if (STI.isRegisterReservedByUser(VA.getLocReg()))
11303         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11304             MF.getFunction(),
11305             "Return value register required, but has been reserved."});
11306 
11307       // Guarantee that all emitted copies are stuck together.
11308       Glue = Chain.getValue(1);
11309       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
11310     }
11311   }
11312 
11313   RetOps[0] = Chain; // Update chain.
11314 
11315   // Add the glue node if we have it.
11316   if (Glue.getNode()) {
11317     RetOps.push_back(Glue);
11318   }
11319 
11320   unsigned RetOpc = RISCVISD::RET_FLAG;
11321   // Interrupt service routines use different return instructions.
11322   const Function &Func = DAG.getMachineFunction().getFunction();
11323   if (Func.hasFnAttribute("interrupt")) {
11324     if (!Func.getReturnType()->isVoidTy())
11325       report_fatal_error(
11326           "Functions with the interrupt attribute must have void return type!");
11327 
11328     MachineFunction &MF = DAG.getMachineFunction();
11329     StringRef Kind =
11330       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
11331 
11332     if (Kind == "user")
11333       RetOpc = RISCVISD::URET_FLAG;
11334     else if (Kind == "supervisor")
11335       RetOpc = RISCVISD::SRET_FLAG;
11336     else
11337       RetOpc = RISCVISD::MRET_FLAG;
11338   }
11339 
11340   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
11341 }
11342 
11343 void RISCVTargetLowering::validateCCReservedRegs(
11344     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
11345     MachineFunction &MF) const {
11346   const Function &F = MF.getFunction();
11347   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11348 
11349   if (llvm::any_of(Regs, [&STI](auto Reg) {
11350         return STI.isRegisterReservedByUser(Reg.first);
11351       }))
11352     F.getContext().diagnose(DiagnosticInfoUnsupported{
11353         F, "Argument register required, but has been reserved."});
11354 }
11355 
11356 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11357   return CI->isTailCall();
11358 }
11359 
11360 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
11361 #define NODE_NAME_CASE(NODE)                                                   \
11362   case RISCVISD::NODE:                                                         \
11363     return "RISCVISD::" #NODE;
11364   // clang-format off
11365   switch ((RISCVISD::NodeType)Opcode) {
11366   case RISCVISD::FIRST_NUMBER:
11367     break;
11368   NODE_NAME_CASE(RET_FLAG)
11369   NODE_NAME_CASE(URET_FLAG)
11370   NODE_NAME_CASE(SRET_FLAG)
11371   NODE_NAME_CASE(MRET_FLAG)
11372   NODE_NAME_CASE(CALL)
11373   NODE_NAME_CASE(SELECT_CC)
11374   NODE_NAME_CASE(BR_CC)
11375   NODE_NAME_CASE(BuildPairF64)
11376   NODE_NAME_CASE(SplitF64)
11377   NODE_NAME_CASE(TAIL)
11378   NODE_NAME_CASE(ADD_LO)
11379   NODE_NAME_CASE(HI)
11380   NODE_NAME_CASE(LLA)
11381   NODE_NAME_CASE(ADD_TPREL)
11382   NODE_NAME_CASE(LA)
11383   NODE_NAME_CASE(LA_TLS_IE)
11384   NODE_NAME_CASE(LA_TLS_GD)
11385   NODE_NAME_CASE(MULHSU)
11386   NODE_NAME_CASE(SLLW)
11387   NODE_NAME_CASE(SRAW)
11388   NODE_NAME_CASE(SRLW)
11389   NODE_NAME_CASE(DIVW)
11390   NODE_NAME_CASE(DIVUW)
11391   NODE_NAME_CASE(REMUW)
11392   NODE_NAME_CASE(ROLW)
11393   NODE_NAME_CASE(RORW)
11394   NODE_NAME_CASE(CLZW)
11395   NODE_NAME_CASE(CTZW)
11396   NODE_NAME_CASE(FSLW)
11397   NODE_NAME_CASE(FSRW)
11398   NODE_NAME_CASE(FSL)
11399   NODE_NAME_CASE(FSR)
11400   NODE_NAME_CASE(FMV_H_X)
11401   NODE_NAME_CASE(FMV_X_ANYEXTH)
11402   NODE_NAME_CASE(FMV_X_SIGNEXTH)
11403   NODE_NAME_CASE(FMV_W_X_RV64)
11404   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
11405   NODE_NAME_CASE(FCVT_X)
11406   NODE_NAME_CASE(FCVT_XU)
11407   NODE_NAME_CASE(FCVT_W_RV64)
11408   NODE_NAME_CASE(FCVT_WU_RV64)
11409   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
11410   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
11411   NODE_NAME_CASE(READ_CYCLE_WIDE)
11412   NODE_NAME_CASE(GREV)
11413   NODE_NAME_CASE(GREVW)
11414   NODE_NAME_CASE(GORC)
11415   NODE_NAME_CASE(GORCW)
11416   NODE_NAME_CASE(SHFL)
11417   NODE_NAME_CASE(SHFLW)
11418   NODE_NAME_CASE(UNSHFL)
11419   NODE_NAME_CASE(UNSHFLW)
11420   NODE_NAME_CASE(BFP)
11421   NODE_NAME_CASE(BFPW)
11422   NODE_NAME_CASE(BCOMPRESS)
11423   NODE_NAME_CASE(BCOMPRESSW)
11424   NODE_NAME_CASE(BDECOMPRESS)
11425   NODE_NAME_CASE(BDECOMPRESSW)
11426   NODE_NAME_CASE(VMV_V_X_VL)
11427   NODE_NAME_CASE(VFMV_V_F_VL)
11428   NODE_NAME_CASE(VMV_X_S)
11429   NODE_NAME_CASE(VMV_S_X_VL)
11430   NODE_NAME_CASE(VFMV_S_F_VL)
11431   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
11432   NODE_NAME_CASE(READ_VLENB)
11433   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
11434   NODE_NAME_CASE(VSLIDEUP_VL)
11435   NODE_NAME_CASE(VSLIDE1UP_VL)
11436   NODE_NAME_CASE(VSLIDEDOWN_VL)
11437   NODE_NAME_CASE(VSLIDE1DOWN_VL)
11438   NODE_NAME_CASE(VID_VL)
11439   NODE_NAME_CASE(VFNCVT_ROD_VL)
11440   NODE_NAME_CASE(VECREDUCE_ADD_VL)
11441   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
11442   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
11443   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
11444   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
11445   NODE_NAME_CASE(VECREDUCE_AND_VL)
11446   NODE_NAME_CASE(VECREDUCE_OR_VL)
11447   NODE_NAME_CASE(VECREDUCE_XOR_VL)
11448   NODE_NAME_CASE(VECREDUCE_FADD_VL)
11449   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
11450   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
11451   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
11452   NODE_NAME_CASE(ADD_VL)
11453   NODE_NAME_CASE(AND_VL)
11454   NODE_NAME_CASE(MUL_VL)
11455   NODE_NAME_CASE(OR_VL)
11456   NODE_NAME_CASE(SDIV_VL)
11457   NODE_NAME_CASE(SHL_VL)
11458   NODE_NAME_CASE(SREM_VL)
11459   NODE_NAME_CASE(SRA_VL)
11460   NODE_NAME_CASE(SRL_VL)
11461   NODE_NAME_CASE(SUB_VL)
11462   NODE_NAME_CASE(UDIV_VL)
11463   NODE_NAME_CASE(UREM_VL)
11464   NODE_NAME_CASE(XOR_VL)
11465   NODE_NAME_CASE(SADDSAT_VL)
11466   NODE_NAME_CASE(UADDSAT_VL)
11467   NODE_NAME_CASE(SSUBSAT_VL)
11468   NODE_NAME_CASE(USUBSAT_VL)
11469   NODE_NAME_CASE(FADD_VL)
11470   NODE_NAME_CASE(FSUB_VL)
11471   NODE_NAME_CASE(FMUL_VL)
11472   NODE_NAME_CASE(FDIV_VL)
11473   NODE_NAME_CASE(FNEG_VL)
11474   NODE_NAME_CASE(FABS_VL)
11475   NODE_NAME_CASE(FSQRT_VL)
11476   NODE_NAME_CASE(VFMADD_VL)
11477   NODE_NAME_CASE(VFNMADD_VL)
11478   NODE_NAME_CASE(VFMSUB_VL)
11479   NODE_NAME_CASE(VFNMSUB_VL)
11480   NODE_NAME_CASE(FCOPYSIGN_VL)
11481   NODE_NAME_CASE(SMIN_VL)
11482   NODE_NAME_CASE(SMAX_VL)
11483   NODE_NAME_CASE(UMIN_VL)
11484   NODE_NAME_CASE(UMAX_VL)
11485   NODE_NAME_CASE(FMINNUM_VL)
11486   NODE_NAME_CASE(FMAXNUM_VL)
11487   NODE_NAME_CASE(MULHS_VL)
11488   NODE_NAME_CASE(MULHU_VL)
11489   NODE_NAME_CASE(FP_TO_SINT_VL)
11490   NODE_NAME_CASE(FP_TO_UINT_VL)
11491   NODE_NAME_CASE(SINT_TO_FP_VL)
11492   NODE_NAME_CASE(UINT_TO_FP_VL)
11493   NODE_NAME_CASE(FP_EXTEND_VL)
11494   NODE_NAME_CASE(FP_ROUND_VL)
11495   NODE_NAME_CASE(VWMUL_VL)
11496   NODE_NAME_CASE(VWMULU_VL)
11497   NODE_NAME_CASE(VWMULSU_VL)
11498   NODE_NAME_CASE(VWADD_VL)
11499   NODE_NAME_CASE(VWADDU_VL)
11500   NODE_NAME_CASE(VWSUB_VL)
11501   NODE_NAME_CASE(VWSUBU_VL)
11502   NODE_NAME_CASE(VWADD_W_VL)
11503   NODE_NAME_CASE(VWADDU_W_VL)
11504   NODE_NAME_CASE(VWSUB_W_VL)
11505   NODE_NAME_CASE(VWSUBU_W_VL)
11506   NODE_NAME_CASE(SETCC_VL)
11507   NODE_NAME_CASE(VSELECT_VL)
11508   NODE_NAME_CASE(VP_MERGE_VL)
11509   NODE_NAME_CASE(VMAND_VL)
11510   NODE_NAME_CASE(VMOR_VL)
11511   NODE_NAME_CASE(VMXOR_VL)
11512   NODE_NAME_CASE(VMCLR_VL)
11513   NODE_NAME_CASE(VMSET_VL)
11514   NODE_NAME_CASE(VRGATHER_VX_VL)
11515   NODE_NAME_CASE(VRGATHER_VV_VL)
11516   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
11517   NODE_NAME_CASE(VSEXT_VL)
11518   NODE_NAME_CASE(VZEXT_VL)
11519   NODE_NAME_CASE(VCPOP_VL)
11520   NODE_NAME_CASE(READ_CSR)
11521   NODE_NAME_CASE(WRITE_CSR)
11522   NODE_NAME_CASE(SWAP_CSR)
11523   }
11524   // clang-format on
11525   return nullptr;
11526 #undef NODE_NAME_CASE
11527 }
11528 
11529 /// getConstraintType - Given a constraint letter, return the type of
11530 /// constraint it is for this target.
11531 RISCVTargetLowering::ConstraintType
11532 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
11533   if (Constraint.size() == 1) {
11534     switch (Constraint[0]) {
11535     default:
11536       break;
11537     case 'f':
11538       return C_RegisterClass;
11539     case 'I':
11540     case 'J':
11541     case 'K':
11542       return C_Immediate;
11543     case 'A':
11544       return C_Memory;
11545     case 'S': // A symbolic address
11546       return C_Other;
11547     }
11548   } else {
11549     if (Constraint == "vr" || Constraint == "vm")
11550       return C_RegisterClass;
11551   }
11552   return TargetLowering::getConstraintType(Constraint);
11553 }
11554 
11555 std::pair<unsigned, const TargetRegisterClass *>
11556 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11557                                                   StringRef Constraint,
11558                                                   MVT VT) const {
11559   // First, see if this is a constraint that directly corresponds to a
11560   // RISCV register class.
11561   if (Constraint.size() == 1) {
11562     switch (Constraint[0]) {
11563     case 'r':
11564       // TODO: Support fixed vectors up to XLen for P extension?
11565       if (VT.isVector())
11566         break;
11567       return std::make_pair(0U, &RISCV::GPRRegClass);
11568     case 'f':
11569       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11570         return std::make_pair(0U, &RISCV::FPR16RegClass);
11571       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11572         return std::make_pair(0U, &RISCV::FPR32RegClass);
11573       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11574         return std::make_pair(0U, &RISCV::FPR64RegClass);
11575       break;
11576     default:
11577       break;
11578     }
11579   } else if (Constraint == "vr") {
11580     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11581                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11582       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11583         return std::make_pair(0U, RC);
11584     }
11585   } else if (Constraint == "vm") {
11586     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11587       return std::make_pair(0U, &RISCV::VMV0RegClass);
11588   }
11589 
11590   // Clang will correctly decode the usage of register name aliases into their
11591   // official names. However, other frontends like `rustc` do not. This allows
11592   // users of these frontends to use the ABI names for registers in LLVM-style
11593   // register constraints.
11594   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11595                                .Case("{zero}", RISCV::X0)
11596                                .Case("{ra}", RISCV::X1)
11597                                .Case("{sp}", RISCV::X2)
11598                                .Case("{gp}", RISCV::X3)
11599                                .Case("{tp}", RISCV::X4)
11600                                .Case("{t0}", RISCV::X5)
11601                                .Case("{t1}", RISCV::X6)
11602                                .Case("{t2}", RISCV::X7)
11603                                .Cases("{s0}", "{fp}", RISCV::X8)
11604                                .Case("{s1}", RISCV::X9)
11605                                .Case("{a0}", RISCV::X10)
11606                                .Case("{a1}", RISCV::X11)
11607                                .Case("{a2}", RISCV::X12)
11608                                .Case("{a3}", RISCV::X13)
11609                                .Case("{a4}", RISCV::X14)
11610                                .Case("{a5}", RISCV::X15)
11611                                .Case("{a6}", RISCV::X16)
11612                                .Case("{a7}", RISCV::X17)
11613                                .Case("{s2}", RISCV::X18)
11614                                .Case("{s3}", RISCV::X19)
11615                                .Case("{s4}", RISCV::X20)
11616                                .Case("{s5}", RISCV::X21)
11617                                .Case("{s6}", RISCV::X22)
11618                                .Case("{s7}", RISCV::X23)
11619                                .Case("{s8}", RISCV::X24)
11620                                .Case("{s9}", RISCV::X25)
11621                                .Case("{s10}", RISCV::X26)
11622                                .Case("{s11}", RISCV::X27)
11623                                .Case("{t3}", RISCV::X28)
11624                                .Case("{t4}", RISCV::X29)
11625                                .Case("{t5}", RISCV::X30)
11626                                .Case("{t6}", RISCV::X31)
11627                                .Default(RISCV::NoRegister);
11628   if (XRegFromAlias != RISCV::NoRegister)
11629     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11630 
11631   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11632   // TableGen record rather than the AsmName to choose registers for InlineAsm
11633   // constraints, plus we want to match those names to the widest floating point
11634   // register type available, manually select floating point registers here.
11635   //
11636   // The second case is the ABI name of the register, so that frontends can also
11637   // use the ABI names in register constraint lists.
11638   if (Subtarget.hasStdExtF()) {
11639     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11640                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11641                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11642                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11643                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11644                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11645                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11646                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11647                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11648                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11649                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11650                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11651                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11652                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11653                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11654                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11655                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11656                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11657                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11658                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11659                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11660                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11661                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11662                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11663                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11664                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11665                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11666                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11667                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11668                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11669                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11670                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11671                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11672                         .Default(RISCV::NoRegister);
11673     if (FReg != RISCV::NoRegister) {
11674       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11675       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11676         unsigned RegNo = FReg - RISCV::F0_F;
11677         unsigned DReg = RISCV::F0_D + RegNo;
11678         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11679       }
11680       if (VT == MVT::f32 || VT == MVT::Other)
11681         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11682       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11683         unsigned RegNo = FReg - RISCV::F0_F;
11684         unsigned HReg = RISCV::F0_H + RegNo;
11685         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11686       }
11687     }
11688   }
11689 
11690   if (Subtarget.hasVInstructions()) {
11691     Register VReg = StringSwitch<Register>(Constraint.lower())
11692                         .Case("{v0}", RISCV::V0)
11693                         .Case("{v1}", RISCV::V1)
11694                         .Case("{v2}", RISCV::V2)
11695                         .Case("{v3}", RISCV::V3)
11696                         .Case("{v4}", RISCV::V4)
11697                         .Case("{v5}", RISCV::V5)
11698                         .Case("{v6}", RISCV::V6)
11699                         .Case("{v7}", RISCV::V7)
11700                         .Case("{v8}", RISCV::V8)
11701                         .Case("{v9}", RISCV::V9)
11702                         .Case("{v10}", RISCV::V10)
11703                         .Case("{v11}", RISCV::V11)
11704                         .Case("{v12}", RISCV::V12)
11705                         .Case("{v13}", RISCV::V13)
11706                         .Case("{v14}", RISCV::V14)
11707                         .Case("{v15}", RISCV::V15)
11708                         .Case("{v16}", RISCV::V16)
11709                         .Case("{v17}", RISCV::V17)
11710                         .Case("{v18}", RISCV::V18)
11711                         .Case("{v19}", RISCV::V19)
11712                         .Case("{v20}", RISCV::V20)
11713                         .Case("{v21}", RISCV::V21)
11714                         .Case("{v22}", RISCV::V22)
11715                         .Case("{v23}", RISCV::V23)
11716                         .Case("{v24}", RISCV::V24)
11717                         .Case("{v25}", RISCV::V25)
11718                         .Case("{v26}", RISCV::V26)
11719                         .Case("{v27}", RISCV::V27)
11720                         .Case("{v28}", RISCV::V28)
11721                         .Case("{v29}", RISCV::V29)
11722                         .Case("{v30}", RISCV::V30)
11723                         .Case("{v31}", RISCV::V31)
11724                         .Default(RISCV::NoRegister);
11725     if (VReg != RISCV::NoRegister) {
11726       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11727         return std::make_pair(VReg, &RISCV::VMRegClass);
11728       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11729         return std::make_pair(VReg, &RISCV::VRRegClass);
11730       for (const auto *RC :
11731            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11732         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11733           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11734           return std::make_pair(VReg, RC);
11735         }
11736       }
11737     }
11738   }
11739 
11740   std::pair<Register, const TargetRegisterClass *> Res =
11741       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11742 
11743   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11744   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11745   // Subtarget into account.
11746   if (Res.second == &RISCV::GPRF16RegClass ||
11747       Res.second == &RISCV::GPRF32RegClass ||
11748       Res.second == &RISCV::GPRF64RegClass)
11749     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11750 
11751   return Res;
11752 }
11753 
11754 unsigned
11755 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11756   // Currently only support length 1 constraints.
11757   if (ConstraintCode.size() == 1) {
11758     switch (ConstraintCode[0]) {
11759     case 'A':
11760       return InlineAsm::Constraint_A;
11761     default:
11762       break;
11763     }
11764   }
11765 
11766   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11767 }
11768 
11769 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11770     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11771     SelectionDAG &DAG) const {
11772   // Currently only support length 1 constraints.
11773   if (Constraint.length() == 1) {
11774     switch (Constraint[0]) {
11775     case 'I':
11776       // Validate & create a 12-bit signed immediate operand.
11777       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11778         uint64_t CVal = C->getSExtValue();
11779         if (isInt<12>(CVal))
11780           Ops.push_back(
11781               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11782       }
11783       return;
11784     case 'J':
11785       // Validate & create an integer zero operand.
11786       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11787         if (C->getZExtValue() == 0)
11788           Ops.push_back(
11789               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11790       return;
11791     case 'K':
11792       // Validate & create a 5-bit unsigned immediate operand.
11793       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11794         uint64_t CVal = C->getZExtValue();
11795         if (isUInt<5>(CVal))
11796           Ops.push_back(
11797               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11798       }
11799       return;
11800     case 'S':
11801       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11802         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11803                                                  GA->getValueType(0)));
11804       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11805         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11806                                                 BA->getValueType(0)));
11807       }
11808       return;
11809     default:
11810       break;
11811     }
11812   }
11813   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11814 }
11815 
11816 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11817                                                    Instruction *Inst,
11818                                                    AtomicOrdering Ord) const {
11819   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11820     return Builder.CreateFence(Ord);
11821   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11822     return Builder.CreateFence(AtomicOrdering::Release);
11823   return nullptr;
11824 }
11825 
11826 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11827                                                     Instruction *Inst,
11828                                                     AtomicOrdering Ord) const {
11829   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11830     return Builder.CreateFence(AtomicOrdering::Acquire);
11831   return nullptr;
11832 }
11833 
11834 TargetLowering::AtomicExpansionKind
11835 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11836   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11837   // point operations can't be used in an lr/sc sequence without breaking the
11838   // forward-progress guarantee.
11839   if (AI->isFloatingPointOperation())
11840     return AtomicExpansionKind::CmpXChg;
11841 
11842   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11843   if (Size == 8 || Size == 16)
11844     return AtomicExpansionKind::MaskedIntrinsic;
11845   return AtomicExpansionKind::None;
11846 }
11847 
11848 static Intrinsic::ID
11849 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11850   if (XLen == 32) {
11851     switch (BinOp) {
11852     default:
11853       llvm_unreachable("Unexpected AtomicRMW BinOp");
11854     case AtomicRMWInst::Xchg:
11855       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11856     case AtomicRMWInst::Add:
11857       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11858     case AtomicRMWInst::Sub:
11859       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11860     case AtomicRMWInst::Nand:
11861       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11862     case AtomicRMWInst::Max:
11863       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11864     case AtomicRMWInst::Min:
11865       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11866     case AtomicRMWInst::UMax:
11867       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11868     case AtomicRMWInst::UMin:
11869       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11870     }
11871   }
11872 
11873   if (XLen == 64) {
11874     switch (BinOp) {
11875     default:
11876       llvm_unreachable("Unexpected AtomicRMW BinOp");
11877     case AtomicRMWInst::Xchg:
11878       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11879     case AtomicRMWInst::Add:
11880       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11881     case AtomicRMWInst::Sub:
11882       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11883     case AtomicRMWInst::Nand:
11884       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11885     case AtomicRMWInst::Max:
11886       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11887     case AtomicRMWInst::Min:
11888       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11889     case AtomicRMWInst::UMax:
11890       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11891     case AtomicRMWInst::UMin:
11892       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11893     }
11894   }
11895 
11896   llvm_unreachable("Unexpected XLen\n");
11897 }
11898 
11899 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11900     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11901     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11902   unsigned XLen = Subtarget.getXLen();
11903   Value *Ordering =
11904       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11905   Type *Tys[] = {AlignedAddr->getType()};
11906   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11907       AI->getModule(),
11908       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11909 
11910   if (XLen == 64) {
11911     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11912     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11913     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11914   }
11915 
11916   Value *Result;
11917 
11918   // Must pass the shift amount needed to sign extend the loaded value prior
11919   // to performing a signed comparison for min/max. ShiftAmt is the number of
11920   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11921   // is the number of bits to left+right shift the value in order to
11922   // sign-extend.
11923   if (AI->getOperation() == AtomicRMWInst::Min ||
11924       AI->getOperation() == AtomicRMWInst::Max) {
11925     const DataLayout &DL = AI->getModule()->getDataLayout();
11926     unsigned ValWidth =
11927         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11928     Value *SextShamt =
11929         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11930     Result = Builder.CreateCall(LrwOpScwLoop,
11931                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11932   } else {
11933     Result =
11934         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11935   }
11936 
11937   if (XLen == 64)
11938     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11939   return Result;
11940 }
11941 
11942 TargetLowering::AtomicExpansionKind
11943 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11944     AtomicCmpXchgInst *CI) const {
11945   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11946   if (Size == 8 || Size == 16)
11947     return AtomicExpansionKind::MaskedIntrinsic;
11948   return AtomicExpansionKind::None;
11949 }
11950 
11951 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11952     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11953     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11954   unsigned XLen = Subtarget.getXLen();
11955   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11956   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11957   if (XLen == 64) {
11958     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11959     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11960     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11961     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11962   }
11963   Type *Tys[] = {AlignedAddr->getType()};
11964   Function *MaskedCmpXchg =
11965       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11966   Value *Result = Builder.CreateCall(
11967       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11968   if (XLen == 64)
11969     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11970   return Result;
11971 }
11972 
11973 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT,
11974                                                         EVT DataVT) const {
11975   return false;
11976 }
11977 
11978 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11979                                                EVT VT) const {
11980   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11981     return false;
11982 
11983   switch (FPVT.getSimpleVT().SimpleTy) {
11984   case MVT::f16:
11985     return Subtarget.hasStdExtZfh();
11986   case MVT::f32:
11987     return Subtarget.hasStdExtF();
11988   case MVT::f64:
11989     return Subtarget.hasStdExtD();
11990   default:
11991     return false;
11992   }
11993 }
11994 
11995 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11996   // If we are using the small code model, we can reduce size of jump table
11997   // entry to 4 bytes.
11998   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11999       getTargetMachine().getCodeModel() == CodeModel::Small) {
12000     return MachineJumpTableInfo::EK_Custom32;
12001   }
12002   return TargetLowering::getJumpTableEncoding();
12003 }
12004 
12005 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
12006     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
12007     unsigned uid, MCContext &Ctx) const {
12008   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
12009          getTargetMachine().getCodeModel() == CodeModel::Small);
12010   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
12011 }
12012 
12013 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
12014                                                      EVT VT) const {
12015   VT = VT.getScalarType();
12016 
12017   if (!VT.isSimple())
12018     return false;
12019 
12020   switch (VT.getSimpleVT().SimpleTy) {
12021   case MVT::f16:
12022     return Subtarget.hasStdExtZfh();
12023   case MVT::f32:
12024     return Subtarget.hasStdExtF();
12025   case MVT::f64:
12026     return Subtarget.hasStdExtD();
12027   default:
12028     break;
12029   }
12030 
12031   return false;
12032 }
12033 
12034 Register RISCVTargetLowering::getExceptionPointerRegister(
12035     const Constant *PersonalityFn) const {
12036   return RISCV::X10;
12037 }
12038 
12039 Register RISCVTargetLowering::getExceptionSelectorRegister(
12040     const Constant *PersonalityFn) const {
12041   return RISCV::X11;
12042 }
12043 
12044 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
12045   // Return false to suppress the unnecessary extensions if the LibCall
12046   // arguments or return value is f32 type for LP64 ABI.
12047   RISCVABI::ABI ABI = Subtarget.getTargetABI();
12048   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
12049     return false;
12050 
12051   return true;
12052 }
12053 
12054 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
12055   if (Subtarget.is64Bit() && Type == MVT::i32)
12056     return true;
12057 
12058   return IsSigned;
12059 }
12060 
12061 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
12062                                                  SDValue C) const {
12063   // Check integral scalar types.
12064   if (VT.isScalarInteger()) {
12065     // Omit the optimization if the sub target has the M extension and the data
12066     // size exceeds XLen.
12067     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
12068       return false;
12069     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
12070       // Break the MUL to a SLLI and an ADD/SUB.
12071       const APInt &Imm = ConstNode->getAPIntValue();
12072       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
12073           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
12074         return true;
12075       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
12076       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
12077           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
12078            (Imm - 8).isPowerOf2()))
12079         return true;
12080       // Omit the following optimization if the sub target has the M extension
12081       // and the data size >= XLen.
12082       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
12083         return false;
12084       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
12085       // a pair of LUI/ADDI.
12086       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
12087         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
12088         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
12089             (1 - ImmS).isPowerOf2())
12090           return true;
12091       }
12092     }
12093   }
12094 
12095   return false;
12096 }
12097 
12098 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
12099                                                       SDValue ConstNode) const {
12100   // Let the DAGCombiner decide for vectors.
12101   EVT VT = AddNode.getValueType();
12102   if (VT.isVector())
12103     return true;
12104 
12105   // Let the DAGCombiner decide for larger types.
12106   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
12107     return true;
12108 
12109   // It is worse if c1 is simm12 while c1*c2 is not.
12110   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
12111   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
12112   const APInt &C1 = C1Node->getAPIntValue();
12113   const APInt &C2 = C2Node->getAPIntValue();
12114   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
12115     return false;
12116 
12117   // Default to true and let the DAGCombiner decide.
12118   return true;
12119 }
12120 
12121 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
12122     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
12123     bool *Fast) const {
12124   if (!VT.isVector()) {
12125     if (Fast)
12126       *Fast = false;
12127     return Subtarget.enableUnalignedScalarMem();
12128   }
12129 
12130   // All vector implementations must support element alignment
12131   EVT ElemVT = VT.getVectorElementType();
12132   if (Alignment >= ElemVT.getStoreSize()) {
12133     if (Fast)
12134       *Fast = true;
12135     return true;
12136   }
12137 
12138   return false;
12139 }
12140 
12141 bool RISCVTargetLowering::splitValueIntoRegisterParts(
12142     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
12143     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
12144   bool IsABIRegCopy = CC.has_value();
12145   EVT ValueVT = Val.getValueType();
12146   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
12147     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
12148     // and cast to f32.
12149     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
12150     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
12151     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
12152                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
12153     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
12154     Parts[0] = Val;
12155     return true;
12156   }
12157 
12158   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
12159     LLVMContext &Context = *DAG.getContext();
12160     EVT ValueEltVT = ValueVT.getVectorElementType();
12161     EVT PartEltVT = PartVT.getVectorElementType();
12162     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
12163     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
12164     if (PartVTBitSize % ValueVTBitSize == 0) {
12165       assert(PartVTBitSize >= ValueVTBitSize);
12166       // If the element types are different, bitcast to the same element type of
12167       // PartVT first.
12168       // Give an example here, we want copy a <vscale x 1 x i8> value to
12169       // <vscale x 4 x i16>.
12170       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
12171       // subvector, then we can bitcast to <vscale x 4 x i16>.
12172       if (ValueEltVT != PartEltVT) {
12173         if (PartVTBitSize > ValueVTBitSize) {
12174           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
12175           assert(Count != 0 && "The number of element should not be zero.");
12176           EVT SameEltTypeVT =
12177               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
12178           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
12179                             DAG.getUNDEF(SameEltTypeVT), Val,
12180                             DAG.getVectorIdxConstant(0, DL));
12181         }
12182         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
12183       } else {
12184         Val =
12185             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
12186                         Val, DAG.getVectorIdxConstant(0, DL));
12187       }
12188       Parts[0] = Val;
12189       return true;
12190     }
12191   }
12192   return false;
12193 }
12194 
12195 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
12196     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
12197     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
12198   bool IsABIRegCopy = CC.has_value();
12199   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
12200     SDValue Val = Parts[0];
12201 
12202     // Cast the f32 to i32, truncate to i16, and cast back to f16.
12203     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
12204     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
12205     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
12206     return Val;
12207   }
12208 
12209   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
12210     LLVMContext &Context = *DAG.getContext();
12211     SDValue Val = Parts[0];
12212     EVT ValueEltVT = ValueVT.getVectorElementType();
12213     EVT PartEltVT = PartVT.getVectorElementType();
12214     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
12215     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
12216     if (PartVTBitSize % ValueVTBitSize == 0) {
12217       assert(PartVTBitSize >= ValueVTBitSize);
12218       EVT SameEltTypeVT = ValueVT;
12219       // If the element types are different, convert it to the same element type
12220       // of PartVT.
12221       // Give an example here, we want copy a <vscale x 1 x i8> value from
12222       // <vscale x 4 x i16>.
12223       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
12224       // then we can extract <vscale x 1 x i8>.
12225       if (ValueEltVT != PartEltVT) {
12226         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
12227         assert(Count != 0 && "The number of element should not be zero.");
12228         SameEltTypeVT =
12229             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
12230         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
12231       }
12232       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
12233                         DAG.getVectorIdxConstant(0, DL));
12234       return Val;
12235     }
12236   }
12237   return SDValue();
12238 }
12239 
12240 SDValue
12241 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12242                                    SelectionDAG &DAG,
12243                                    SmallVectorImpl<SDNode *> &Created) const {
12244   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
12245   if (isIntDivCheap(N->getValueType(0), Attr))
12246     return SDValue(N, 0); // Lower SDIV as SDIV
12247 
12248   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
12249          "Unexpected divisor!");
12250 
12251   // Conditional move is needed, so do the transformation iff Zbt is enabled.
12252   if (!Subtarget.hasStdExtZbt())
12253     return SDValue();
12254 
12255   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
12256   // Besides, more critical path instructions will be generated when dividing
12257   // by 2. So we keep using the original DAGs for these cases.
12258   unsigned Lg2 = Divisor.countTrailingZeros();
12259   if (Lg2 == 1 || Lg2 >= 12)
12260     return SDValue();
12261 
12262   // fold (sdiv X, pow2)
12263   EVT VT = N->getValueType(0);
12264   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
12265     return SDValue();
12266 
12267   SDLoc DL(N);
12268   SDValue N0 = N->getOperand(0);
12269   SDValue Zero = DAG.getConstant(0, DL, VT);
12270   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
12271 
12272   // Add (N0 < 0) ? Pow2 - 1 : 0;
12273   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
12274   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
12275   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
12276 
12277   Created.push_back(Cmp.getNode());
12278   Created.push_back(Add.getNode());
12279   Created.push_back(Sel.getNode());
12280 
12281   // Divide by pow2.
12282   SDValue SRA =
12283       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
12284 
12285   // If we're dividing by a positive value, we're done.  Otherwise, we must
12286   // negate the result.
12287   if (Divisor.isNonNegative())
12288     return SRA;
12289 
12290   Created.push_back(SRA.getNode());
12291   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
12292 }
12293 
12294 #define GET_REGISTER_MATCHER
12295 #include "RISCVGenAsmMatcher.inc"
12296 
12297 Register
12298 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
12299                                        const MachineFunction &MF) const {
12300   Register Reg = MatchRegisterAltName(RegName);
12301   if (Reg == RISCV::NoRegister)
12302     Reg = MatchRegisterName(RegName);
12303   if (Reg == RISCV::NoRegister)
12304     report_fatal_error(
12305         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
12306   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
12307   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
12308     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
12309                              StringRef(RegName) + "\"."));
12310   return Reg;
12311 }
12312 
12313 namespace llvm {
12314 namespace RISCVVIntrinsicsTable {
12315 
12316 #define GET_RISCVVIntrinsicsTable_IMPL
12317 #include "RISCVGenSearchableTables.inc"
12318 
12319 } // namespace RISCVVIntrinsicsTable
12320 
12321 } // namespace llvm
12322