1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/DiagnosticPrinter.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/IntrinsicsRISCV.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/KnownBits.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "riscv-lower"
45 
46 STATISTIC(NumTailCalls, "Number of tail calls");
47 
48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
49                                          const RISCVSubtarget &STI)
50     : TargetLowering(TM), Subtarget(STI) {
51 
52   if (Subtarget.isRV32E())
53     report_fatal_error("Codegen not yet implemented for RV32E");
54 
55   RISCVABI::ABI ABI = Subtarget.getTargetABI();
56   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
57 
58   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
59       !Subtarget.hasStdExtF()) {
60     errs() << "Hard-float 'f' ABI can't be used for a target that "
61                 "doesn't support the F instruction set extension (ignoring "
62                           "target-abi)\n";
63     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
64   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
65              !Subtarget.hasStdExtD()) {
66     errs() << "Hard-float 'd' ABI can't be used for a target that "
67               "doesn't support the D instruction set extension (ignoring "
68               "target-abi)\n";
69     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
70   }
71 
72   switch (ABI) {
73   default:
74     report_fatal_error("Don't know how to lower this ABI");
75   case RISCVABI::ABI_ILP32:
76   case RISCVABI::ABI_ILP32F:
77   case RISCVABI::ABI_ILP32D:
78   case RISCVABI::ABI_LP64:
79   case RISCVABI::ABI_LP64F:
80   case RISCVABI::ABI_LP64D:
81     break;
82   }
83 
84   MVT XLenVT = Subtarget.getXLenVT();
85 
86   // Set up the register classes.
87   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
88 
89   if (Subtarget.hasStdExtZfh())
90     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
91   if (Subtarget.hasStdExtF())
92     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
93   if (Subtarget.hasStdExtD())
94     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
95 
96   static const MVT::SimpleValueType BoolVecVTs[] = {
97       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
98       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
99   static const MVT::SimpleValueType IntVecVTs[] = {
100       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
101       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
102       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
103       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
104       MVT::nxv4i64, MVT::nxv8i64};
105   static const MVT::SimpleValueType F16VecVTs[] = {
106       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
107       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
108   static const MVT::SimpleValueType F32VecVTs[] = {
109       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
110   static const MVT::SimpleValueType F64VecVTs[] = {
111       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
112 
113   if (Subtarget.hasVInstructions()) {
114     auto addRegClassForRVV = [this](MVT VT) {
115       unsigned Size = VT.getSizeInBits().getKnownMinValue();
116       const TargetRegisterClass *RC;
117       if (Size <= RISCV::RVVBitsPerBlock)
118         RC = &RISCV::VRRegClass;
119       else if (Size == 2 * RISCV::RVVBitsPerBlock)
120         RC = &RISCV::VRM2RegClass;
121       else if (Size == 4 * RISCV::RVVBitsPerBlock)
122         RC = &RISCV::VRM4RegClass;
123       else if (Size == 8 * RISCV::RVVBitsPerBlock)
124         RC = &RISCV::VRM8RegClass;
125       else
126         llvm_unreachable("Unexpected size");
127 
128       addRegisterClass(VT, RC);
129     };
130 
131     for (MVT VT : BoolVecVTs)
132       addRegClassForRVV(VT);
133     for (MVT VT : IntVecVTs) {
134       if (VT.getVectorElementType() == MVT::i64 &&
135           !Subtarget.hasVInstructionsI64())
136         continue;
137       addRegClassForRVV(VT);
138     }
139 
140     if (Subtarget.hasVInstructionsF16())
141       for (MVT VT : F16VecVTs)
142         addRegClassForRVV(VT);
143 
144     if (Subtarget.hasVInstructionsF32())
145       for (MVT VT : F32VecVTs)
146         addRegClassForRVV(VT);
147 
148     if (Subtarget.hasVInstructionsF64())
149       for (MVT VT : F64VecVTs)
150         addRegClassForRVV(VT);
151 
152     if (Subtarget.useRVVForFixedLengthVectors()) {
153       auto addRegClassForFixedVectors = [this](MVT VT) {
154         MVT ContainerVT = getContainerForFixedLengthVector(VT);
155         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
156         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
157         addRegisterClass(VT, TRI.getRegClass(RCID));
158       };
159       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
160         if (useRVVForFixedLengthVectorVT(VT))
161           addRegClassForFixedVectors(VT);
162 
163       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
164         if (useRVVForFixedLengthVectorVT(VT))
165           addRegClassForFixedVectors(VT);
166     }
167   }
168 
169   // Compute derived properties from the register classes.
170   computeRegisterProperties(STI.getRegisterInfo());
171 
172   setStackPointerRegisterToSaveRestore(RISCV::X2);
173 
174   setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, XLenVT,
175                    MVT::i1, Promote);
176 
177   // TODO: add all necessary setOperationAction calls.
178   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
179 
180   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
181   setOperationAction(ISD::BR_CC, XLenVT, Expand);
182   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
183   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
184 
185   setOperationAction({ISD::STACKSAVE, ISD::STACKRESTORE}, MVT::Other, Expand);
186 
187   setOperationAction(ISD::VASTART, MVT::Other, Custom);
188   setOperationAction({ISD::VAARG, ISD::VACOPY, ISD::VAEND}, MVT::Other, Expand);
189 
190   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
191 
192   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
193 
194   if (!Subtarget.hasStdExtZbb())
195     setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand);
196 
197   if (Subtarget.is64Bit()) {
198     setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
199 
200     setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL},
201                        MVT::i32, Custom);
202 
203     setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT},
204                        MVT::i32, Custom);
205   } else {
206     setLibcallName(
207         {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128},
208         nullptr);
209     setLibcallName(RTLIB::MULO_I64, nullptr);
210   }
211 
212   if (!Subtarget.hasStdExtM()) {
213     setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::SDIV, ISD::UDIV,
214                         ISD::SREM, ISD::UREM},
215                        XLenVT, Expand);
216   } else {
217     if (Subtarget.is64Bit()) {
218       setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom);
219 
220       setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM},
221                          {MVT::i8, MVT::i16, MVT::i32}, Custom);
222     } else {
223       setOperationAction(ISD::MUL, MVT::i64, Custom);
224     }
225   }
226 
227   setOperationAction(
228       {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT,
229       Expand);
230 
231   setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT,
232                      Custom);
233 
234   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
235       Subtarget.hasStdExtZbkb()) {
236     if (Subtarget.is64Bit())
237       setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom);
238   } else {
239     setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand);
240   }
241 
242   if (Subtarget.hasStdExtZbp()) {
243     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
244     // more combining.
245     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom);
246 
247     // BSWAP i8 doesn't exist.
248     setOperationAction(ISD::BITREVERSE, MVT::i8, Custom);
249 
250     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom);
251 
252     if (Subtarget.is64Bit())
253       setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom);
254   } else {
255     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
256     // pattern match it directly in isel.
257     setOperationAction(ISD::BSWAP, XLenVT,
258                        (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
259                            ? Legal
260                            : Expand);
261     // Zbkb can use rev8+brev8 to implement bitreverse.
262     setOperationAction(ISD::BITREVERSE, XLenVT,
263                        Subtarget.hasStdExtZbkb() ? Custom : Expand);
264   }
265 
266   if (Subtarget.hasStdExtZbb()) {
267     setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT,
268                        Legal);
269 
270     if (Subtarget.is64Bit())
271       setOperationAction(
272           {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF},
273           MVT::i32, Custom);
274   } else {
275     setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand);
276 
277     if (Subtarget.is64Bit())
278       setOperationAction(ISD::ABS, MVT::i32, Custom);
279   }
280 
281   if (Subtarget.hasStdExtZbt()) {
282     setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom);
283     setOperationAction(ISD::SELECT, XLenVT, Legal);
284 
285     if (Subtarget.is64Bit())
286       setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom);
287   } else {
288     setOperationAction(ISD::SELECT, XLenVT, Custom);
289   }
290 
291   static constexpr ISD::NodeType FPLegalNodeTypes[] = {
292       ISD::FMINNUM,        ISD::FMAXNUM,       ISD::LRINT,
293       ISD::LLRINT,         ISD::LROUND,        ISD::LLROUND,
294       ISD::STRICT_LRINT,   ISD::STRICT_LLRINT, ISD::STRICT_LROUND,
295       ISD::STRICT_LLROUND, ISD::STRICT_FMA,    ISD::STRICT_FADD,
296       ISD::STRICT_FSUB,    ISD::STRICT_FMUL,   ISD::STRICT_FDIV,
297       ISD::STRICT_FSQRT,   ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS};
298 
299   static const ISD::CondCode FPCCToExpand[] = {
300       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
301       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
302       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
303 
304   static const ISD::NodeType FPOpToExpand[] = {
305       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
306       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
307 
308   if (Subtarget.hasStdExtZfh())
309     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
310 
311   if (Subtarget.hasStdExtZfh()) {
312     for (auto NT : FPLegalNodeTypes)
313       setOperationAction(NT, MVT::f16, Legal);
314     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
315     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
316     setCondCodeAction(FPCCToExpand, MVT::f16, Expand);
317     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
318     setOperationAction(ISD::SELECT, MVT::f16, Custom);
319     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
320 
321     setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT,
322                         ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC,
323                         ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN,
324                         ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG,
325                         ISD::FLOG2, ISD::FLOG10},
326                        MVT::f16, Promote);
327 
328     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
329     // complete support for all operations in LegalizeDAG.
330 
331     // We need to custom promote this.
332     if (Subtarget.is64Bit())
333       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
334   }
335 
336   if (Subtarget.hasStdExtF()) {
337     for (auto NT : FPLegalNodeTypes)
338       setOperationAction(NT, MVT::f32, Legal);
339     setCondCodeAction(FPCCToExpand, MVT::f32, Expand);
340     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
341     setOperationAction(ISD::SELECT, MVT::f32, Custom);
342     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
343     for (auto Op : FPOpToExpand)
344       setOperationAction(Op, MVT::f32, Expand);
345     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
346     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
347   }
348 
349   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
350     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
351 
352   if (Subtarget.hasStdExtD()) {
353     for (auto NT : FPLegalNodeTypes)
354       setOperationAction(NT, MVT::f64, Legal);
355     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
356     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
357     setCondCodeAction(FPCCToExpand, MVT::f64, Expand);
358     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
359     setOperationAction(ISD::SELECT, MVT::f64, Custom);
360     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
361     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
362     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
363     for (auto Op : FPOpToExpand)
364       setOperationAction(Op, MVT::f64, Expand);
365     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
366     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
367   }
368 
369   if (Subtarget.is64Bit())
370     setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT,
371                         ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT},
372                        MVT::i32, Custom);
373 
374   if (Subtarget.hasStdExtF()) {
375     setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT,
376                        Custom);
377 
378     setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT,
379                         ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP},
380                        XLenVT, Legal);
381 
382     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
383     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
384   }
385 
386   setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool,
387                       ISD::JumpTable},
388                      XLenVT, Custom);
389 
390   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
391 
392   if (Subtarget.is64Bit())
393     setOperationAction(ISD::Constant, MVT::i64, Custom);
394 
395   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
396   // Unfortunately this can't be determined just from the ISA naming string.
397   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
398                      Subtarget.is64Bit() ? Legal : Custom);
399 
400   setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal);
401   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
402   if (Subtarget.is64Bit())
403     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
404 
405   if (Subtarget.hasStdExtA()) {
406     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
407     setMinCmpXchgSizeInBits(32);
408   } else {
409     setMaxAtomicSizeInBitsSupported(0);
410   }
411 
412   setBooleanContents(ZeroOrOneBooleanContent);
413 
414   if (Subtarget.hasVInstructions()) {
415     setBooleanVectorContents(ZeroOrOneBooleanContent);
416 
417     setOperationAction(ISD::VSCALE, XLenVT, Custom);
418 
419     // RVV intrinsics may have illegal operands.
420     // We also need to custom legalize vmv.x.s.
421     setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
422                        {MVT::i8, MVT::i16}, Custom);
423     if (Subtarget.is64Bit())
424       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
425     else
426       setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
427                          MVT::i64, Custom);
428 
429     setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID},
430                        MVT::Other, Custom);
431 
432     static const unsigned IntegerVPOps[] = {
433         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
434         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
435         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
436         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
437         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
438         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
439         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
440         ISD::VP_MERGE,       ISD::VP_SELECT,      ISD::VP_FPTOSI,
441         ISD::VP_FPTOUI,      ISD::VP_SETCC,       ISD::VP_SIGN_EXTEND,
442         ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE};
443 
444     static const unsigned FloatingPointVPOps[] = {
445         ISD::VP_FADD,        ISD::VP_FSUB,
446         ISD::VP_FMUL,        ISD::VP_FDIV,
447         ISD::VP_FNEG,        ISD::VP_FMA,
448         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
449         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX,
450         ISD::VP_MERGE,       ISD::VP_SELECT,
451         ISD::VP_SITOFP,      ISD::VP_UITOFP,
452         ISD::VP_SETCC,       ISD::VP_FP_ROUND,
453         ISD::VP_FP_EXTEND};
454 
455     if (!Subtarget.is64Bit()) {
456       // We must custom-lower certain vXi64 operations on RV32 due to the vector
457       // element type being illegal.
458       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
459                          MVT::i64, Custom);
460 
461       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
462                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
463                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
464                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
465                          MVT::i64, Custom);
466 
467       setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND,
468                           ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR,
469                           ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN,
470                           ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN},
471                          MVT::i64, Custom);
472     }
473 
474     for (MVT VT : BoolVecVTs) {
475       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
476 
477       // Mask VTs are custom-expanded into a series of standard nodes
478       setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS,
479                           ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
480                          VT, Custom);
481 
482       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
483                          Custom);
484 
485       setOperationAction(ISD::SELECT, VT, Custom);
486       setOperationAction(
487           {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT,
488           Expand);
489 
490       setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom);
491 
492       setOperationAction(
493           {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
494           Custom);
495 
496       setOperationAction(
497           {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
498           Custom);
499 
500       // RVV has native int->float & float->int conversions where the
501       // element type sizes are within one power-of-two of each other. Any
502       // wider distances between type sizes have to be lowered as sequences
503       // which progressively narrow the gap in stages.
504       setOperationAction(
505           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
506           VT, Custom);
507 
508       // Expand all extending loads to types larger than this, and truncating
509       // stores from types larger than this.
510       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
511         setTruncStoreAction(OtherVT, VT, Expand);
512         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
513                          VT, Expand);
514       }
515 
516       setOperationAction(
517           {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT,
518           Custom);
519     }
520 
521     for (MVT VT : IntVecVTs) {
522       if (VT.getVectorElementType() == MVT::i64 &&
523           !Subtarget.hasVInstructionsI64())
524         continue;
525 
526       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
527       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
528 
529       // Vectors implement MULHS/MULHU.
530       setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand);
531 
532       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
533       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV())
534         setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand);
535 
536       setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT,
537                          Legal);
538 
539       setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand);
540 
541       setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT,
542                          Expand);
543 
544       setOperationAction(ISD::BSWAP, VT, Expand);
545 
546       // Custom-lower extensions and truncations from/to mask types.
547       setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND},
548                          VT, Custom);
549 
550       // RVV has native int->float & float->int conversions where the
551       // element type sizes are within one power-of-two of each other. Any
552       // wider distances between type sizes have to be lowered as sequences
553       // which progressively narrow the gap in stages.
554       setOperationAction(
555           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
556           VT, Custom);
557 
558       setOperationAction(
559           {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal);
560 
561       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
562       // nodes which truncate by one power of two at a time.
563       setOperationAction(ISD::TRUNCATE, VT, Custom);
564 
565       // Custom-lower insert/extract operations to simplify patterns.
566       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
567                          Custom);
568 
569       // Custom-lower reduction operations to set up the corresponding custom
570       // nodes' operands.
571       setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND,
572                           ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR,
573                           ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
574                           ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN},
575                          VT, Custom);
576 
577       setOperationAction(IntegerVPOps, VT, Custom);
578 
579       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
580 
581       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
582                          VT, Custom);
583 
584       setOperationAction(
585           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
586           Custom);
587 
588       setOperationAction(
589           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
590           VT, Custom);
591 
592       setOperationAction(ISD::SELECT, VT, Custom);
593       setOperationAction(ISD::SELECT_CC, VT, Expand);
594 
595       setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom);
596 
597       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
598         setTruncStoreAction(VT, OtherVT, Expand);
599         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
600                          VT, Expand);
601       }
602 
603       // Splice
604       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
605 
606       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
607       // type that can represent the value exactly.
608       if (VT.getVectorElementType() != MVT::i64) {
609         MVT FloatEltVT =
610             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
611         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
612         if (isTypeLegal(FloatVT)) {
613           setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
614                              Custom);
615         }
616       }
617     }
618 
619     // Expand various CCs to best match the RVV ISA, which natively supports UNE
620     // but no other unordered comparisons, and supports all ordered comparisons
621     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
622     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
623     // and we pattern-match those back to the "original", swapping operands once
624     // more. This way we catch both operations and both "vf" and "fv" forms with
625     // fewer patterns.
626     static const ISD::CondCode VFPCCToExpand[] = {
627         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
628         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
629         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
630     };
631 
632     // Sets common operation actions on RVV floating-point vector types.
633     const auto SetCommonVFPActions = [&](MVT VT) {
634       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
635       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
636       // sizes are within one power-of-two of each other. Therefore conversions
637       // between vXf16 and vXf64 must be lowered as sequences which convert via
638       // vXf32.
639       setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
640       // Custom-lower insert/extract operations to simplify patterns.
641       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
642                          Custom);
643       // Expand various condition codes (explained above).
644       setCondCodeAction(VFPCCToExpand, VT, Expand);
645 
646       setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal);
647 
648       setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
649                          VT, Custom);
650 
651       setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
652                           ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
653                          VT, Custom);
654 
655       // Expand FP operations that need libcalls.
656       setOperationAction(ISD::FREM, VT, Expand);
657       setOperationAction(ISD::FPOW, VT, Expand);
658       setOperationAction(ISD::FCOS, VT, Expand);
659       setOperationAction(ISD::FSIN, VT, Expand);
660       setOperationAction(ISD::FSINCOS, VT, Expand);
661       setOperationAction(ISD::FEXP, VT, Expand);
662       setOperationAction(ISD::FEXP2, VT, Expand);
663       setOperationAction(ISD::FLOG, VT, Expand);
664       setOperationAction(ISD::FLOG2, VT, Expand);
665       setOperationAction(ISD::FLOG10, VT, Expand);
666       setOperationAction(ISD::FRINT, VT, Expand);
667       setOperationAction(ISD::FNEARBYINT, VT, Expand);
668 
669       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
670       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
671       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
672       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
673 
674       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
675 
676       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
677 
678       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
679                          VT, Custom);
680 
681       setOperationAction(
682           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
683           Custom);
684 
685       setOperationAction(ISD::SELECT, VT, Custom);
686       setOperationAction(ISD::SELECT_CC, VT, Expand);
687 
688       setOperationAction(
689           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
690           VT, Custom);
691 
692       setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom);
693 
694       setOperationAction(FloatingPointVPOps, VT, Custom);
695     };
696 
697     // Sets common extload/truncstore actions on RVV floating-point vector
698     // types.
699     const auto SetCommonVFPExtLoadTruncStoreActions =
700         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
701           for (auto SmallVT : SmallerVTs) {
702             setTruncStoreAction(VT, SmallVT, Expand);
703             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
704           }
705         };
706 
707     if (Subtarget.hasVInstructionsF16())
708       for (MVT VT : F16VecVTs)
709         SetCommonVFPActions(VT);
710 
711     for (MVT VT : F32VecVTs) {
712       if (Subtarget.hasVInstructionsF32())
713         SetCommonVFPActions(VT);
714       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
715     }
716 
717     for (MVT VT : F64VecVTs) {
718       if (Subtarget.hasVInstructionsF64())
719         SetCommonVFPActions(VT);
720       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
721       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
722     }
723 
724     if (Subtarget.useRVVForFixedLengthVectors()) {
725       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
726         if (!useRVVForFixedLengthVectorVT(VT))
727           continue;
728 
729         // By default everything must be expanded.
730         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
731           setOperationAction(Op, VT, Expand);
732         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
733           setTruncStoreAction(VT, OtherVT, Expand);
734           setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD},
735                            OtherVT, VT, Expand);
736         }
737 
738         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
739         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
740                            Custom);
741 
742         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT,
743                            Custom);
744 
745         setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
746                            VT, Custom);
747 
748         setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
749 
750         setOperationAction(ISD::SETCC, VT, Custom);
751 
752         setOperationAction(ISD::SELECT, VT, Custom);
753 
754         setOperationAction(ISD::TRUNCATE, VT, Custom);
755 
756         setOperationAction(ISD::BITCAST, VT, Custom);
757 
758         setOperationAction(
759             {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
760             Custom);
761 
762         setOperationAction(
763             {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
764             Custom);
765 
766         setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT,
767                             ISD::FP_TO_UINT},
768                            VT, Custom);
769 
770         // Operations below are different for between masks and other vectors.
771         if (VT.getVectorElementType() == MVT::i1) {
772           setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND,
773                               ISD::OR, ISD::XOR},
774                              VT, Custom);
775 
776           setOperationAction(
777               {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE},
778               VT, Custom);
779           continue;
780         }
781 
782         // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
783         // it before type legalization for i64 vectors on RV32. It will then be
784         // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
785         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
786         // improvements first.
787         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
788           setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
789           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
790         }
791 
792         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
793         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
794 
795         setOperationAction(
796             {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom);
797 
798         setOperationAction(
799             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
800             Custom);
801 
802         setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR,
803                             ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV,
804                             ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL},
805                            VT, Custom);
806 
807         setOperationAction(
808             {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom);
809 
810         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
811         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV())
812           setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom);
813 
814         setOperationAction(
815             {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT,
816             Custom);
817 
818         setOperationAction(ISD::VSELECT, VT, Custom);
819         setOperationAction(ISD::SELECT_CC, VT, Expand);
820 
821         setOperationAction(
822             {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom);
823 
824         // Custom-lower reduction operations to set up the corresponding custom
825         // nodes' operands.
826         setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX,
827                             ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX,
828                             ISD::VECREDUCE_UMIN},
829                            VT, Custom);
830 
831         setOperationAction(IntegerVPOps, VT, Custom);
832 
833         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
834         // type that can represent the value exactly.
835         if (VT.getVectorElementType() != MVT::i64) {
836           MVT FloatEltVT =
837               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
838           EVT FloatVT =
839               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
840           if (isTypeLegal(FloatVT))
841             setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
842                                Custom);
843         }
844       }
845 
846       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
847         if (!useRVVForFixedLengthVectorVT(VT))
848           continue;
849 
850         // By default everything must be expanded.
851         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
852           setOperationAction(Op, VT, Expand);
853         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
854           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
855           setTruncStoreAction(VT, OtherVT, Expand);
856         }
857 
858         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
859         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
860                            Custom);
861 
862         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS,
863                             ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT,
864                             ISD::EXTRACT_VECTOR_ELT},
865                            VT, Custom);
866 
867         setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE,
868                             ISD::MGATHER, ISD::MSCATTER},
869                            VT, Custom);
870 
871         setOperationAction(
872             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
873             Custom);
874 
875         setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV,
876                             ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT,
877                             ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM},
878                            VT, Custom);
879 
880         setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
881 
882         setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
883                            VT, Custom);
884 
885         for (auto CC : VFPCCToExpand)
886           setCondCodeAction(CC, VT, Expand);
887 
888         setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom);
889         setOperationAction(ISD::SELECT_CC, VT, Expand);
890 
891         setOperationAction(ISD::BITCAST, VT, Custom);
892 
893         setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD,
894                             ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX},
895                            VT, Custom);
896 
897         setOperationAction(FloatingPointVPOps, VT, Custom);
898       }
899 
900       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
901       setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64},
902                          Custom);
903       if (Subtarget.hasStdExtZfh())
904         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
905       if (Subtarget.hasStdExtF())
906         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
907       if (Subtarget.hasStdExtD())
908         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
909     }
910   }
911 
912   // Function alignments.
913   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
914   setMinFunctionAlignment(FunctionAlignment);
915   setPrefFunctionAlignment(FunctionAlignment);
916 
917   setMinimumJumpTableEntries(5);
918 
919   // Jumps are expensive, compared to logic
920   setJumpIsExpensive();
921 
922   setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND,
923                        ISD::OR, ISD::XOR});
924 
925   if (Subtarget.hasStdExtF())
926     setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM});
927 
928   if (Subtarget.hasStdExtZbp())
929     setTargetDAGCombine({ISD::ROTL, ISD::ROTR});
930 
931   if (Subtarget.hasStdExtZbb())
932     setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN});
933 
934   if (Subtarget.hasStdExtZbkb())
935     setTargetDAGCombine(ISD::BITREVERSE);
936   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
937     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
938   if (Subtarget.hasStdExtF())
939     setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
940                          ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT});
941   if (Subtarget.hasVInstructions())
942     setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER,
943                          ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL,
944                          ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR});
945   if (Subtarget.useRVVForFixedLengthVectors())
946     setTargetDAGCombine(ISD::BITCAST);
947 
948   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
949   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
950 }
951 
952 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
953                                             LLVMContext &Context,
954                                             EVT VT) const {
955   if (!VT.isVector())
956     return getPointerTy(DL);
957   if (Subtarget.hasVInstructions() &&
958       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
959     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
960   return VT.changeVectorElementTypeToInteger();
961 }
962 
963 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
964   return Subtarget.getXLenVT();
965 }
966 
967 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
968                                              const CallInst &I,
969                                              MachineFunction &MF,
970                                              unsigned Intrinsic) const {
971   auto &DL = I.getModule()->getDataLayout();
972   switch (Intrinsic) {
973   default:
974     return false;
975   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
976   case Intrinsic::riscv_masked_atomicrmw_add_i32:
977   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
978   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
979   case Intrinsic::riscv_masked_atomicrmw_max_i32:
980   case Intrinsic::riscv_masked_atomicrmw_min_i32:
981   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
982   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
983   case Intrinsic::riscv_masked_cmpxchg_i32:
984     Info.opc = ISD::INTRINSIC_W_CHAIN;
985     Info.memVT = MVT::i32;
986     Info.ptrVal = I.getArgOperand(0);
987     Info.offset = 0;
988     Info.align = Align(4);
989     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
990                  MachineMemOperand::MOVolatile;
991     return true;
992   case Intrinsic::riscv_masked_strided_load:
993     Info.opc = ISD::INTRINSIC_W_CHAIN;
994     Info.ptrVal = I.getArgOperand(1);
995     Info.memVT = getValueType(DL, I.getType()->getScalarType());
996     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
997     Info.size = MemoryLocation::UnknownSize;
998     Info.flags |= MachineMemOperand::MOLoad;
999     return true;
1000   case Intrinsic::riscv_masked_strided_store:
1001     Info.opc = ISD::INTRINSIC_VOID;
1002     Info.ptrVal = I.getArgOperand(1);
1003     Info.memVT =
1004         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1005     Info.align = Align(
1006         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1007         8);
1008     Info.size = MemoryLocation::UnknownSize;
1009     Info.flags |= MachineMemOperand::MOStore;
1010     return true;
1011   case Intrinsic::riscv_seg2_load:
1012   case Intrinsic::riscv_seg3_load:
1013   case Intrinsic::riscv_seg4_load:
1014   case Intrinsic::riscv_seg5_load:
1015   case Intrinsic::riscv_seg6_load:
1016   case Intrinsic::riscv_seg7_load:
1017   case Intrinsic::riscv_seg8_load:
1018     Info.opc = ISD::INTRINSIC_W_CHAIN;
1019     Info.ptrVal = I.getArgOperand(0);
1020     Info.memVT =
1021         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
1022     Info.align =
1023         Align(DL.getTypeSizeInBits(
1024                   I.getType()->getStructElementType(0)->getScalarType()) /
1025               8);
1026     Info.size = MemoryLocation::UnknownSize;
1027     Info.flags |= MachineMemOperand::MOLoad;
1028     return true;
1029   }
1030 }
1031 
1032 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1033                                                 const AddrMode &AM, Type *Ty,
1034                                                 unsigned AS,
1035                                                 Instruction *I) const {
1036   // No global is ever allowed as a base.
1037   if (AM.BaseGV)
1038     return false;
1039 
1040   // RVV instructions only support register addressing.
1041   if (Subtarget.hasVInstructions() && isa<VectorType>(Ty))
1042     return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs;
1043 
1044   // Require a 12-bit signed offset.
1045   if (!isInt<12>(AM.BaseOffs))
1046     return false;
1047 
1048   switch (AM.Scale) {
1049   case 0: // "r+i" or just "i", depending on HasBaseReg.
1050     break;
1051   case 1:
1052     if (!AM.HasBaseReg) // allow "r+i".
1053       break;
1054     return false; // disallow "r+r" or "r+r+i".
1055   default:
1056     return false;
1057   }
1058 
1059   return true;
1060 }
1061 
1062 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1063   return isInt<12>(Imm);
1064 }
1065 
1066 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1067   return isInt<12>(Imm);
1068 }
1069 
1070 // On RV32, 64-bit integers are split into their high and low parts and held
1071 // in two different registers, so the trunc is free since the low register can
1072 // just be used.
1073 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1074   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1075     return false;
1076   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1077   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1078   return (SrcBits == 64 && DestBits == 32);
1079 }
1080 
1081 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1082   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1083       !SrcVT.isInteger() || !DstVT.isInteger())
1084     return false;
1085   unsigned SrcBits = SrcVT.getSizeInBits();
1086   unsigned DestBits = DstVT.getSizeInBits();
1087   return (SrcBits == 64 && DestBits == 32);
1088 }
1089 
1090 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1091   // Zexts are free if they can be combined with a load.
1092   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1093   // poorly with type legalization of compares preferring sext.
1094   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1095     EVT MemVT = LD->getMemoryVT();
1096     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1097         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1098          LD->getExtensionType() == ISD::ZEXTLOAD))
1099       return true;
1100   }
1101 
1102   return TargetLowering::isZExtFree(Val, VT2);
1103 }
1104 
1105 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1106   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1107 }
1108 
1109 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const {
1110   return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
1111 }
1112 
1113 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1114   return Subtarget.hasStdExtZbb();
1115 }
1116 
1117 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1118   return Subtarget.hasStdExtZbb();
1119 }
1120 
1121 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1122   EVT VT = Y.getValueType();
1123 
1124   // FIXME: Support vectors once we have tests.
1125   if (VT.isVector())
1126     return false;
1127 
1128   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1129           Subtarget.hasStdExtZbkb()) &&
1130          !isa<ConstantSDNode>(Y);
1131 }
1132 
1133 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
1134   // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1135   auto *C = dyn_cast<ConstantSDNode>(Y);
1136   return C && C->getAPIntValue().ule(10);
1137 }
1138 
1139 bool RISCVTargetLowering::
1140     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
1141         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
1142         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
1143         SelectionDAG &DAG) const {
1144   // One interesting pattern that we'd want to form is 'bit extract':
1145   //   ((1 >> Y) & 1) ==/!= 0
1146   // But we also need to be careful not to try to reverse that fold.
1147 
1148   // Is this '((1 >> Y) & 1)'?
1149   if (XC && OldShiftOpcode == ISD::SRL && XC->isOne())
1150     return false; // Keep the 'bit extract' pattern.
1151 
1152   // Will this be '((1 >> Y) & 1)' after the transform?
1153   if (NewShiftOpcode == ISD::SRL && CC->isOne())
1154     return true; // Do form the 'bit extract' pattern.
1155 
1156   // If 'X' is a constant, and we transform, then we will immediately
1157   // try to undo the fold, thus causing endless combine loop.
1158   // So only do the transform if X is not a constant. This matches the default
1159   // implementation of this function.
1160   return !XC;
1161 }
1162 
1163 /// Check if sinking \p I's operands to I's basic block is profitable, because
1164 /// the operands can be folded into a target instruction, e.g.
1165 /// splats of scalars can fold into vector instructions.
1166 bool RISCVTargetLowering::shouldSinkOperands(
1167     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1168   using namespace llvm::PatternMatch;
1169 
1170   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1171     return false;
1172 
1173   auto IsSinker = [&](Instruction *I, int Operand) {
1174     switch (I->getOpcode()) {
1175     case Instruction::Add:
1176     case Instruction::Sub:
1177     case Instruction::Mul:
1178     case Instruction::And:
1179     case Instruction::Or:
1180     case Instruction::Xor:
1181     case Instruction::FAdd:
1182     case Instruction::FSub:
1183     case Instruction::FMul:
1184     case Instruction::FDiv:
1185     case Instruction::ICmp:
1186     case Instruction::FCmp:
1187       return true;
1188     case Instruction::Shl:
1189     case Instruction::LShr:
1190     case Instruction::AShr:
1191     case Instruction::UDiv:
1192     case Instruction::SDiv:
1193     case Instruction::URem:
1194     case Instruction::SRem:
1195       return Operand == 1;
1196     case Instruction::Call:
1197       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1198         switch (II->getIntrinsicID()) {
1199         case Intrinsic::fma:
1200         case Intrinsic::vp_fma:
1201           return Operand == 0 || Operand == 1;
1202         // FIXME: Our patterns can only match vx/vf instructions when the splat
1203         // it on the RHS, because TableGen doesn't recognize our VP operations
1204         // as commutative.
1205         case Intrinsic::vp_add:
1206         case Intrinsic::vp_mul:
1207         case Intrinsic::vp_and:
1208         case Intrinsic::vp_or:
1209         case Intrinsic::vp_xor:
1210         case Intrinsic::vp_fadd:
1211         case Intrinsic::vp_fmul:
1212         case Intrinsic::vp_shl:
1213         case Intrinsic::vp_lshr:
1214         case Intrinsic::vp_ashr:
1215         case Intrinsic::vp_udiv:
1216         case Intrinsic::vp_sdiv:
1217         case Intrinsic::vp_urem:
1218         case Intrinsic::vp_srem:
1219           return Operand == 1;
1220         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1221         // explicit patterns for both LHS and RHS (as 'vr' versions).
1222         case Intrinsic::vp_sub:
1223         case Intrinsic::vp_fsub:
1224         case Intrinsic::vp_fdiv:
1225           return Operand == 0 || Operand == 1;
1226         default:
1227           return false;
1228         }
1229       }
1230       return false;
1231     default:
1232       return false;
1233     }
1234   };
1235 
1236   for (auto OpIdx : enumerate(I->operands())) {
1237     if (!IsSinker(I, OpIdx.index()))
1238       continue;
1239 
1240     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1241     // Make sure we are not already sinking this operand
1242     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1243       continue;
1244 
1245     // We are looking for a splat that can be sunk.
1246     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1247                              m_Undef(), m_ZeroMask())))
1248       continue;
1249 
1250     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1251     // and vector registers
1252     for (Use &U : Op->uses()) {
1253       Instruction *Insn = cast<Instruction>(U.getUser());
1254       if (!IsSinker(Insn, U.getOperandNo()))
1255         return false;
1256     }
1257 
1258     Ops.push_back(&Op->getOperandUse(0));
1259     Ops.push_back(&OpIdx.value());
1260   }
1261   return true;
1262 }
1263 
1264 bool RISCVTargetLowering::isOffsetFoldingLegal(
1265     const GlobalAddressSDNode *GA) const {
1266   // In order to maximise the opportunity for common subexpression elimination,
1267   // keep a separate ADD node for the global address offset instead of folding
1268   // it in the global address node. Later peephole optimisations may choose to
1269   // fold it back in when profitable.
1270   return false;
1271 }
1272 
1273 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1274                                        bool ForCodeSize) const {
1275   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1276   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1277     return false;
1278   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1279     return false;
1280   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1281     return false;
1282   return Imm.isZero();
1283 }
1284 
1285 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1286   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1287          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1288          (VT == MVT::f64 && Subtarget.hasStdExtD());
1289 }
1290 
1291 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1292                                                       CallingConv::ID CC,
1293                                                       EVT VT) const {
1294   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1295   // We might still end up using a GPR but that will be decided based on ABI.
1296   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1297   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1298     return MVT::f32;
1299 
1300   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1301 }
1302 
1303 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1304                                                            CallingConv::ID CC,
1305                                                            EVT VT) const {
1306   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1307   // We might still end up using a GPR but that will be decided based on ABI.
1308   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1309   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1310     return 1;
1311 
1312   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1313 }
1314 
1315 // Changes the condition code and swaps operands if necessary, so the SetCC
1316 // operation matches one of the comparisons supported directly by branches
1317 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1318 // with 1/-1.
1319 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1320                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1321   // Convert X > -1 to X >= 0.
1322   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1323     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1324     CC = ISD::SETGE;
1325     return;
1326   }
1327   // Convert X < 1 to 0 >= X.
1328   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1329     RHS = LHS;
1330     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1331     CC = ISD::SETGE;
1332     return;
1333   }
1334 
1335   switch (CC) {
1336   default:
1337     break;
1338   case ISD::SETGT:
1339   case ISD::SETLE:
1340   case ISD::SETUGT:
1341   case ISD::SETULE:
1342     CC = ISD::getSetCCSwappedOperands(CC);
1343     std::swap(LHS, RHS);
1344     break;
1345   }
1346 }
1347 
1348 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1349   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1350   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1351   if (VT.getVectorElementType() == MVT::i1)
1352     KnownSize *= 8;
1353 
1354   switch (KnownSize) {
1355   default:
1356     llvm_unreachable("Invalid LMUL.");
1357   case 8:
1358     return RISCVII::VLMUL::LMUL_F8;
1359   case 16:
1360     return RISCVII::VLMUL::LMUL_F4;
1361   case 32:
1362     return RISCVII::VLMUL::LMUL_F2;
1363   case 64:
1364     return RISCVII::VLMUL::LMUL_1;
1365   case 128:
1366     return RISCVII::VLMUL::LMUL_2;
1367   case 256:
1368     return RISCVII::VLMUL::LMUL_4;
1369   case 512:
1370     return RISCVII::VLMUL::LMUL_8;
1371   }
1372 }
1373 
1374 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1375   switch (LMul) {
1376   default:
1377     llvm_unreachable("Invalid LMUL.");
1378   case RISCVII::VLMUL::LMUL_F8:
1379   case RISCVII::VLMUL::LMUL_F4:
1380   case RISCVII::VLMUL::LMUL_F2:
1381   case RISCVII::VLMUL::LMUL_1:
1382     return RISCV::VRRegClassID;
1383   case RISCVII::VLMUL::LMUL_2:
1384     return RISCV::VRM2RegClassID;
1385   case RISCVII::VLMUL::LMUL_4:
1386     return RISCV::VRM4RegClassID;
1387   case RISCVII::VLMUL::LMUL_8:
1388     return RISCV::VRM8RegClassID;
1389   }
1390 }
1391 
1392 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1393   RISCVII::VLMUL LMUL = getLMUL(VT);
1394   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1395       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1396       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1397       LMUL == RISCVII::VLMUL::LMUL_1) {
1398     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1399                   "Unexpected subreg numbering");
1400     return RISCV::sub_vrm1_0 + Index;
1401   }
1402   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1403     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1404                   "Unexpected subreg numbering");
1405     return RISCV::sub_vrm2_0 + Index;
1406   }
1407   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1408     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1409                   "Unexpected subreg numbering");
1410     return RISCV::sub_vrm4_0 + Index;
1411   }
1412   llvm_unreachable("Invalid vector type.");
1413 }
1414 
1415 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1416   if (VT.getVectorElementType() == MVT::i1)
1417     return RISCV::VRRegClassID;
1418   return getRegClassIDForLMUL(getLMUL(VT));
1419 }
1420 
1421 // Attempt to decompose a subvector insert/extract between VecVT and
1422 // SubVecVT via subregister indices. Returns the subregister index that
1423 // can perform the subvector insert/extract with the given element index, as
1424 // well as the index corresponding to any leftover subvectors that must be
1425 // further inserted/extracted within the register class for SubVecVT.
1426 std::pair<unsigned, unsigned>
1427 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1428     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1429     const RISCVRegisterInfo *TRI) {
1430   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1431                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1432                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1433                 "Register classes not ordered");
1434   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1435   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1436   // Try to compose a subregister index that takes us from the incoming
1437   // LMUL>1 register class down to the outgoing one. At each step we half
1438   // the LMUL:
1439   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1440   // Note that this is not guaranteed to find a subregister index, such as
1441   // when we are extracting from one VR type to another.
1442   unsigned SubRegIdx = RISCV::NoSubRegister;
1443   for (const unsigned RCID :
1444        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1445     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1446       VecVT = VecVT.getHalfNumVectorElementsVT();
1447       bool IsHi =
1448           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1449       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1450                                             getSubregIndexByMVT(VecVT, IsHi));
1451       if (IsHi)
1452         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1453     }
1454   return {SubRegIdx, InsertExtractIdx};
1455 }
1456 
1457 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1458 // stores for those types.
1459 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1460   return !Subtarget.useRVVForFixedLengthVectors() ||
1461          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1462 }
1463 
1464 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1465   if (ScalarTy->isPointerTy())
1466     return true;
1467 
1468   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1469       ScalarTy->isIntegerTy(32))
1470     return true;
1471 
1472   if (ScalarTy->isIntegerTy(64))
1473     return Subtarget.hasVInstructionsI64();
1474 
1475   if (ScalarTy->isHalfTy())
1476     return Subtarget.hasVInstructionsF16();
1477   if (ScalarTy->isFloatTy())
1478     return Subtarget.hasVInstructionsF32();
1479   if (ScalarTy->isDoubleTy())
1480     return Subtarget.hasVInstructionsF64();
1481 
1482   return false;
1483 }
1484 
1485 static SDValue getVLOperand(SDValue Op) {
1486   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1487           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1488          "Unexpected opcode");
1489   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1490   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1491   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1492       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1493   if (!II)
1494     return SDValue();
1495   return Op.getOperand(II->VLOperand + 1 + HasChain);
1496 }
1497 
1498 static bool useRVVForFixedLengthVectorVT(MVT VT,
1499                                          const RISCVSubtarget &Subtarget) {
1500   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1501   if (!Subtarget.useRVVForFixedLengthVectors())
1502     return false;
1503 
1504   // We only support a set of vector types with a consistent maximum fixed size
1505   // across all supported vector element types to avoid legalization issues.
1506   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1507   // fixed-length vector type we support is 1024 bytes.
1508   if (VT.getFixedSizeInBits() > 1024 * 8)
1509     return false;
1510 
1511   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1512 
1513   MVT EltVT = VT.getVectorElementType();
1514 
1515   // Don't use RVV for vectors we cannot scalarize if required.
1516   switch (EltVT.SimpleTy) {
1517   // i1 is supported but has different rules.
1518   default:
1519     return false;
1520   case MVT::i1:
1521     // Masks can only use a single register.
1522     if (VT.getVectorNumElements() > MinVLen)
1523       return false;
1524     MinVLen /= 8;
1525     break;
1526   case MVT::i8:
1527   case MVT::i16:
1528   case MVT::i32:
1529     break;
1530   case MVT::i64:
1531     if (!Subtarget.hasVInstructionsI64())
1532       return false;
1533     break;
1534   case MVT::f16:
1535     if (!Subtarget.hasVInstructionsF16())
1536       return false;
1537     break;
1538   case MVT::f32:
1539     if (!Subtarget.hasVInstructionsF32())
1540       return false;
1541     break;
1542   case MVT::f64:
1543     if (!Subtarget.hasVInstructionsF64())
1544       return false;
1545     break;
1546   }
1547 
1548   // Reject elements larger than ELEN.
1549   if (EltVT.getSizeInBits() > Subtarget.getELEN())
1550     return false;
1551 
1552   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1553   // Don't use RVV for types that don't fit.
1554   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1555     return false;
1556 
1557   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1558   // the base fixed length RVV support in place.
1559   if (!VT.isPow2VectorType())
1560     return false;
1561 
1562   return true;
1563 }
1564 
1565 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1566   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1567 }
1568 
1569 // Return the largest legal scalable vector type that matches VT's element type.
1570 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1571                                             const RISCVSubtarget &Subtarget) {
1572   // This may be called before legal types are setup.
1573   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1574           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1575          "Expected legal fixed length vector!");
1576 
1577   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1578   unsigned MaxELen = Subtarget.getELEN();
1579 
1580   MVT EltVT = VT.getVectorElementType();
1581   switch (EltVT.SimpleTy) {
1582   default:
1583     llvm_unreachable("unexpected element type for RVV container");
1584   case MVT::i1:
1585   case MVT::i8:
1586   case MVT::i16:
1587   case MVT::i32:
1588   case MVT::i64:
1589   case MVT::f16:
1590   case MVT::f32:
1591   case MVT::f64: {
1592     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1593     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1594     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1595     unsigned NumElts =
1596         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1597     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1598     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1599     return MVT::getScalableVectorVT(EltVT, NumElts);
1600   }
1601   }
1602 }
1603 
1604 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1605                                             const RISCVSubtarget &Subtarget) {
1606   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1607                                           Subtarget);
1608 }
1609 
1610 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1611   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1612 }
1613 
1614 // Grow V to consume an entire RVV register.
1615 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1616                                        const RISCVSubtarget &Subtarget) {
1617   assert(VT.isScalableVector() &&
1618          "Expected to convert into a scalable vector!");
1619   assert(V.getValueType().isFixedLengthVector() &&
1620          "Expected a fixed length vector operand!");
1621   SDLoc DL(V);
1622   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1623   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1624 }
1625 
1626 // Shrink V so it's just big enough to maintain a VT's worth of data.
1627 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1628                                          const RISCVSubtarget &Subtarget) {
1629   assert(VT.isFixedLengthVector() &&
1630          "Expected to convert into a fixed length vector!");
1631   assert(V.getValueType().isScalableVector() &&
1632          "Expected a scalable vector operand!");
1633   SDLoc DL(V);
1634   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1635   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1636 }
1637 
1638 /// Return the type of the mask type suitable for masking the provided
1639 /// vector type.  This is simply an i1 element type vector of the same
1640 /// (possibly scalable) length.
1641 static MVT getMaskTypeFor(EVT VecVT) {
1642   assert(VecVT.isVector());
1643   ElementCount EC = VecVT.getVectorElementCount();
1644   return MVT::getVectorVT(MVT::i1, EC);
1645 }
1646 
1647 /// Creates an all ones mask suitable for masking a vector of type VecTy with
1648 /// vector length VL.  .
1649 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL,
1650                               SelectionDAG &DAG) {
1651   MVT MaskVT = getMaskTypeFor(VecVT);
1652   return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1653 }
1654 
1655 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1656 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1657 // the vector type that it is contained in.
1658 static std::pair<SDValue, SDValue>
1659 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1660                 const RISCVSubtarget &Subtarget) {
1661   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1662   MVT XLenVT = Subtarget.getXLenVT();
1663   SDValue VL = VecVT.isFixedLengthVector()
1664                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1665                    : DAG.getRegister(RISCV::X0, XLenVT);
1666   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
1667   return {Mask, VL};
1668 }
1669 
1670 // As above but assuming the given type is a scalable vector type.
1671 static std::pair<SDValue, SDValue>
1672 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1673                         const RISCVSubtarget &Subtarget) {
1674   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1675   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1676 }
1677 
1678 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1679 // of either is (currently) supported. This can get us into an infinite loop
1680 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1681 // as a ..., etc.
1682 // Until either (or both) of these can reliably lower any node, reporting that
1683 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1684 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1685 // which is not desirable.
1686 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1687     EVT VT, unsigned DefinedValues) const {
1688   return false;
1689 }
1690 
1691 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1692                                   const RISCVSubtarget &Subtarget) {
1693   // RISCV FP-to-int conversions saturate to the destination register size, but
1694   // don't produce 0 for nan. We can use a conversion instruction and fix the
1695   // nan case with a compare and a select.
1696   SDValue Src = Op.getOperand(0);
1697 
1698   EVT DstVT = Op.getValueType();
1699   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1700 
1701   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1702   unsigned Opc;
1703   if (SatVT == DstVT)
1704     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1705   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1706     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1707   else
1708     return SDValue();
1709   // FIXME: Support other SatVTs by clamping before or after the conversion.
1710 
1711   SDLoc DL(Op);
1712   SDValue FpToInt = DAG.getNode(
1713       Opc, DL, DstVT, Src,
1714       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1715 
1716   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1717   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1718 }
1719 
1720 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1721 // and back. Taking care to avoid converting values that are nan or already
1722 // correct.
1723 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1724 // have FRM dependencies modeled yet.
1725 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1726   MVT VT = Op.getSimpleValueType();
1727   assert(VT.isVector() && "Unexpected type");
1728 
1729   SDLoc DL(Op);
1730 
1731   // Freeze the source since we are increasing the number of uses.
1732   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1733 
1734   // Truncate to integer and convert back to FP.
1735   MVT IntVT = VT.changeVectorElementTypeToInteger();
1736   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1737   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1738 
1739   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1740 
1741   if (Op.getOpcode() == ISD::FCEIL) {
1742     // If the truncated value is the greater than or equal to the original
1743     // value, we've computed the ceil. Otherwise, we went the wrong way and
1744     // need to increase by 1.
1745     // FIXME: This should use a masked operation. Handle here or in isel?
1746     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1747                                  DAG.getConstantFP(1.0, DL, VT));
1748     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1749     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1750   } else if (Op.getOpcode() == ISD::FFLOOR) {
1751     // If the truncated value is the less than or equal to the original value,
1752     // we've computed the floor. Otherwise, we went the wrong way and need to
1753     // decrease by 1.
1754     // FIXME: This should use a masked operation. Handle here or in isel?
1755     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1756                                  DAG.getConstantFP(1.0, DL, VT));
1757     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1758     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1759   }
1760 
1761   // Restore the original sign so that -0.0 is preserved.
1762   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1763 
1764   // Determine the largest integer that can be represented exactly. This and
1765   // values larger than it don't have any fractional bits so don't need to
1766   // be converted.
1767   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1768   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1769   APFloat MaxVal = APFloat(FltSem);
1770   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1771                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1772   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1773 
1774   // If abs(Src) was larger than MaxVal or nan, keep it.
1775   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1776   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1777   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1778 }
1779 
1780 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1781 // This mode isn't supported in vector hardware on RISCV. But as long as we
1782 // aren't compiling with trapping math, we can emulate this with
1783 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1784 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1785 // dependencies modeled yet.
1786 // FIXME: Use masked operations to avoid final merge.
1787 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1788   MVT VT = Op.getSimpleValueType();
1789   assert(VT.isVector() && "Unexpected type");
1790 
1791   SDLoc DL(Op);
1792 
1793   // Freeze the source since we are increasing the number of uses.
1794   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1795 
1796   // We do the conversion on the absolute value and fix the sign at the end.
1797   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1798 
1799   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1800   bool Ignored;
1801   APFloat Point5Pred = APFloat(0.5f);
1802   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1803   Point5Pred.next(/*nextDown*/ true);
1804 
1805   // Add the adjustment.
1806   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1807                                DAG.getConstantFP(Point5Pred, DL, VT));
1808 
1809   // Truncate to integer and convert back to fp.
1810   MVT IntVT = VT.changeVectorElementTypeToInteger();
1811   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1812   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1813 
1814   // Restore the original sign.
1815   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1816 
1817   // Determine the largest integer that can be represented exactly. This and
1818   // values larger than it don't have any fractional bits so don't need to
1819   // be converted.
1820   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1821   APFloat MaxVal = APFloat(FltSem);
1822   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1823                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1824   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1825 
1826   // If abs(Src) was larger than MaxVal or nan, keep it.
1827   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1828   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1829   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1830 }
1831 
1832 struct VIDSequence {
1833   int64_t StepNumerator;
1834   unsigned StepDenominator;
1835   int64_t Addend;
1836 };
1837 
1838 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1839 // to the (non-zero) step S and start value X. This can be then lowered as the
1840 // RVV sequence (VID * S) + X, for example.
1841 // The step S is represented as an integer numerator divided by a positive
1842 // denominator. Note that the implementation currently only identifies
1843 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1844 // cannot detect 2/3, for example.
1845 // Note that this method will also match potentially unappealing index
1846 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1847 // determine whether this is worth generating code for.
1848 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1849   unsigned NumElts = Op.getNumOperands();
1850   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1851   if (!Op.getValueType().isInteger())
1852     return None;
1853 
1854   Optional<unsigned> SeqStepDenom;
1855   Optional<int64_t> SeqStepNum, SeqAddend;
1856   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1857   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1858   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1859     // Assume undef elements match the sequence; we just have to be careful
1860     // when interpolating across them.
1861     if (Op.getOperand(Idx).isUndef())
1862       continue;
1863     // The BUILD_VECTOR must be all constants.
1864     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1865       return None;
1866 
1867     uint64_t Val = Op.getConstantOperandVal(Idx) &
1868                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1869 
1870     if (PrevElt) {
1871       // Calculate the step since the last non-undef element, and ensure
1872       // it's consistent across the entire sequence.
1873       unsigned IdxDiff = Idx - PrevElt->second;
1874       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1875 
1876       // A zero-value value difference means that we're somewhere in the middle
1877       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1878       // step change before evaluating the sequence.
1879       if (ValDiff == 0)
1880         continue;
1881 
1882       int64_t Remainder = ValDiff % IdxDiff;
1883       // Normalize the step if it's greater than 1.
1884       if (Remainder != ValDiff) {
1885         // The difference must cleanly divide the element span.
1886         if (Remainder != 0)
1887           return None;
1888         ValDiff /= IdxDiff;
1889         IdxDiff = 1;
1890       }
1891 
1892       if (!SeqStepNum)
1893         SeqStepNum = ValDiff;
1894       else if (ValDiff != SeqStepNum)
1895         return None;
1896 
1897       if (!SeqStepDenom)
1898         SeqStepDenom = IdxDiff;
1899       else if (IdxDiff != *SeqStepDenom)
1900         return None;
1901     }
1902 
1903     // Record this non-undef element for later.
1904     if (!PrevElt || PrevElt->first != Val)
1905       PrevElt = std::make_pair(Val, Idx);
1906   }
1907 
1908   // We need to have logged a step for this to count as a legal index sequence.
1909   if (!SeqStepNum || !SeqStepDenom)
1910     return None;
1911 
1912   // Loop back through the sequence and validate elements we might have skipped
1913   // while waiting for a valid step. While doing this, log any sequence addend.
1914   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1915     if (Op.getOperand(Idx).isUndef())
1916       continue;
1917     uint64_t Val = Op.getConstantOperandVal(Idx) &
1918                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1919     uint64_t ExpectedVal =
1920         (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1921     int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1922     if (!SeqAddend)
1923       SeqAddend = Addend;
1924     else if (Addend != SeqAddend)
1925       return None;
1926   }
1927 
1928   assert(SeqAddend && "Must have an addend if we have a step");
1929 
1930   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1931 }
1932 
1933 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1934 // and lower it as a VRGATHER_VX_VL from the source vector.
1935 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
1936                                   SelectionDAG &DAG,
1937                                   const RISCVSubtarget &Subtarget) {
1938   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1939     return SDValue();
1940   SDValue Vec = SplatVal.getOperand(0);
1941   // Only perform this optimization on vectors of the same size for simplicity.
1942   // Don't perform this optimization for i1 vectors.
1943   // FIXME: Support i1 vectors, maybe by promoting to i8?
1944   if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1)
1945     return SDValue();
1946   SDValue Idx = SplatVal.getOperand(1);
1947   // The index must be a legal type.
1948   if (Idx.getValueType() != Subtarget.getXLenVT())
1949     return SDValue();
1950 
1951   MVT ContainerVT = VT;
1952   if (VT.isFixedLengthVector()) {
1953     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1954     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
1955   }
1956 
1957   SDValue Mask, VL;
1958   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1959 
1960   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
1961                                Idx, Mask, DAG.getUNDEF(ContainerVT), VL);
1962 
1963   if (!VT.isFixedLengthVector())
1964     return Gather;
1965 
1966   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
1967 }
1968 
1969 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1970                                  const RISCVSubtarget &Subtarget) {
1971   MVT VT = Op.getSimpleValueType();
1972   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1973 
1974   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1975 
1976   SDLoc DL(Op);
1977   SDValue Mask, VL;
1978   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1979 
1980   MVT XLenVT = Subtarget.getXLenVT();
1981   unsigned NumElts = Op.getNumOperands();
1982 
1983   if (VT.getVectorElementType() == MVT::i1) {
1984     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1985       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1986       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1987     }
1988 
1989     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1990       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1991       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1992     }
1993 
1994     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1995     // scalar integer chunks whose bit-width depends on the number of mask
1996     // bits and XLEN.
1997     // First, determine the most appropriate scalar integer type to use. This
1998     // is at most XLenVT, but may be shrunk to a smaller vector element type
1999     // according to the size of the final vector - use i8 chunks rather than
2000     // XLenVT if we're producing a v8i1. This results in more consistent
2001     // codegen across RV32 and RV64.
2002     unsigned NumViaIntegerBits =
2003         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2004     NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN());
2005     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2006       // If we have to use more than one INSERT_VECTOR_ELT then this
2007       // optimization is likely to increase code size; avoid peforming it in
2008       // such a case. We can use a load from a constant pool in this case.
2009       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2010         return SDValue();
2011       // Now we can create our integer vector type. Note that it may be larger
2012       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2013       MVT IntegerViaVecVT =
2014           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2015                            divideCeil(NumElts, NumViaIntegerBits));
2016 
2017       uint64_t Bits = 0;
2018       unsigned BitPos = 0, IntegerEltIdx = 0;
2019       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2020 
2021       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2022         // Once we accumulate enough bits to fill our scalar type, insert into
2023         // our vector and clear our accumulated data.
2024         if (I != 0 && I % NumViaIntegerBits == 0) {
2025           if (NumViaIntegerBits <= 32)
2026             Bits = SignExtend64<32>(Bits);
2027           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2028           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2029                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2030           Bits = 0;
2031           BitPos = 0;
2032           IntegerEltIdx++;
2033         }
2034         SDValue V = Op.getOperand(I);
2035         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2036         Bits |= ((uint64_t)BitValue << BitPos);
2037       }
2038 
2039       // Insert the (remaining) scalar value into position in our integer
2040       // vector type.
2041       if (NumViaIntegerBits <= 32)
2042         Bits = SignExtend64<32>(Bits);
2043       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2044       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2045                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2046 
2047       if (NumElts < NumViaIntegerBits) {
2048         // If we're producing a smaller vector than our minimum legal integer
2049         // type, bitcast to the equivalent (known-legal) mask type, and extract
2050         // our final mask.
2051         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2052         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2053         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2054                           DAG.getConstant(0, DL, XLenVT));
2055       } else {
2056         // Else we must have produced an integer type with the same size as the
2057         // mask type; bitcast for the final result.
2058         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2059         Vec = DAG.getBitcast(VT, Vec);
2060       }
2061 
2062       return Vec;
2063     }
2064 
2065     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2066     // vector type, we have a legal equivalently-sized i8 type, so we can use
2067     // that.
2068     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2069     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2070 
2071     SDValue WideVec;
2072     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2073       // For a splat, perform a scalar truncate before creating the wider
2074       // vector.
2075       assert(Splat.getValueType() == XLenVT &&
2076              "Unexpected type for i1 splat value");
2077       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2078                           DAG.getConstant(1, DL, XLenVT));
2079       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2080     } else {
2081       SmallVector<SDValue, 8> Ops(Op->op_values());
2082       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2083       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2084       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2085     }
2086 
2087     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2088   }
2089 
2090   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2091     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2092       return Gather;
2093     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2094                                         : RISCVISD::VMV_V_X_VL;
2095     Splat =
2096         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2097     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2098   }
2099 
2100   // Try and match index sequences, which we can lower to the vid instruction
2101   // with optional modifications. An all-undef vector is matched by
2102   // getSplatValue, above.
2103   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2104     int64_t StepNumerator = SimpleVID->StepNumerator;
2105     unsigned StepDenominator = SimpleVID->StepDenominator;
2106     int64_t Addend = SimpleVID->Addend;
2107 
2108     assert(StepNumerator != 0 && "Invalid step");
2109     bool Negate = false;
2110     int64_t SplatStepVal = StepNumerator;
2111     unsigned StepOpcode = ISD::MUL;
2112     if (StepNumerator != 1) {
2113       if (isPowerOf2_64(std::abs(StepNumerator))) {
2114         Negate = StepNumerator < 0;
2115         StepOpcode = ISD::SHL;
2116         SplatStepVal = Log2_64(std::abs(StepNumerator));
2117       }
2118     }
2119 
2120     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2121     // threshold since it's the immediate value many RVV instructions accept.
2122     // There is no vmul.vi instruction so ensure multiply constant can fit in
2123     // a single addi instruction.
2124     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2125          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2126         isPowerOf2_32(StepDenominator) &&
2127         (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) {
2128       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2129       // Convert right out of the scalable type so we can use standard ISD
2130       // nodes for the rest of the computation. If we used scalable types with
2131       // these, we'd lose the fixed-length vector info and generate worse
2132       // vsetvli code.
2133       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2134       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2135           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2136         SDValue SplatStep = DAG.getSplatBuildVector(
2137             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2138         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2139       }
2140       if (StepDenominator != 1) {
2141         SDValue SplatStep = DAG.getSplatBuildVector(
2142             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2143         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2144       }
2145       if (Addend != 0 || Negate) {
2146         SDValue SplatAddend = DAG.getSplatBuildVector(
2147             VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2148         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2149       }
2150       return VID;
2151     }
2152   }
2153 
2154   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2155   // when re-interpreted as a vector with a larger element type. For example,
2156   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2157   // could be instead splat as
2158   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2159   // TODO: This optimization could also work on non-constant splats, but it
2160   // would require bit-manipulation instructions to construct the splat value.
2161   SmallVector<SDValue> Sequence;
2162   unsigned EltBitSize = VT.getScalarSizeInBits();
2163   const auto *BV = cast<BuildVectorSDNode>(Op);
2164   if (VT.isInteger() && EltBitSize < 64 &&
2165       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2166       BV->getRepeatedSequence(Sequence) &&
2167       (Sequence.size() * EltBitSize) <= 64) {
2168     unsigned SeqLen = Sequence.size();
2169     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2170     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2171     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2172             ViaIntVT == MVT::i64) &&
2173            "Unexpected sequence type");
2174 
2175     unsigned EltIdx = 0;
2176     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2177     uint64_t SplatValue = 0;
2178     // Construct the amalgamated value which can be splatted as this larger
2179     // vector type.
2180     for (const auto &SeqV : Sequence) {
2181       if (!SeqV.isUndef())
2182         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2183                        << (EltIdx * EltBitSize));
2184       EltIdx++;
2185     }
2186 
2187     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2188     // achieve better constant materializion.
2189     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2190       SplatValue = SignExtend64<32>(SplatValue);
2191 
2192     // Since we can't introduce illegal i64 types at this stage, we can only
2193     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2194     // way we can use RVV instructions to splat.
2195     assert((ViaIntVT.bitsLE(XLenVT) ||
2196             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2197            "Unexpected bitcast sequence");
2198     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2199       SDValue ViaVL =
2200           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2201       MVT ViaContainerVT =
2202           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2203       SDValue Splat =
2204           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2205                       DAG.getUNDEF(ViaContainerVT),
2206                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2207       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2208       return DAG.getBitcast(VT, Splat);
2209     }
2210   }
2211 
2212   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2213   // which constitute a large proportion of the elements. In such cases we can
2214   // splat a vector with the dominant element and make up the shortfall with
2215   // INSERT_VECTOR_ELTs.
2216   // Note that this includes vectors of 2 elements by association. The
2217   // upper-most element is the "dominant" one, allowing us to use a splat to
2218   // "insert" the upper element, and an insert of the lower element at position
2219   // 0, which improves codegen.
2220   SDValue DominantValue;
2221   unsigned MostCommonCount = 0;
2222   DenseMap<SDValue, unsigned> ValueCounts;
2223   unsigned NumUndefElts =
2224       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2225 
2226   // Track the number of scalar loads we know we'd be inserting, estimated as
2227   // any non-zero floating-point constant. Other kinds of element are either
2228   // already in registers or are materialized on demand. The threshold at which
2229   // a vector load is more desirable than several scalar materializion and
2230   // vector-insertion instructions is not known.
2231   unsigned NumScalarLoads = 0;
2232 
2233   for (SDValue V : Op->op_values()) {
2234     if (V.isUndef())
2235       continue;
2236 
2237     ValueCounts.insert(std::make_pair(V, 0));
2238     unsigned &Count = ValueCounts[V];
2239 
2240     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2241       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2242 
2243     // Is this value dominant? In case of a tie, prefer the highest element as
2244     // it's cheaper to insert near the beginning of a vector than it is at the
2245     // end.
2246     if (++Count >= MostCommonCount) {
2247       DominantValue = V;
2248       MostCommonCount = Count;
2249     }
2250   }
2251 
2252   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2253   unsigned NumDefElts = NumElts - NumUndefElts;
2254   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2255 
2256   // Don't perform this optimization when optimizing for size, since
2257   // materializing elements and inserting them tends to cause code bloat.
2258   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2259       ((MostCommonCount > DominantValueCountThreshold) ||
2260        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2261     // Start by splatting the most common element.
2262     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2263 
2264     DenseSet<SDValue> Processed{DominantValue};
2265     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2266     for (const auto &OpIdx : enumerate(Op->ops())) {
2267       const SDValue &V = OpIdx.value();
2268       if (V.isUndef() || !Processed.insert(V).second)
2269         continue;
2270       if (ValueCounts[V] == 1) {
2271         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2272                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2273       } else {
2274         // Blend in all instances of this value using a VSELECT, using a
2275         // mask where each bit signals whether that element is the one
2276         // we're after.
2277         SmallVector<SDValue> Ops;
2278         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2279           return DAG.getConstant(V == V1, DL, XLenVT);
2280         });
2281         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2282                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2283                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2284       }
2285     }
2286 
2287     return Vec;
2288   }
2289 
2290   return SDValue();
2291 }
2292 
2293 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2294                                    SDValue Lo, SDValue Hi, SDValue VL,
2295                                    SelectionDAG &DAG) {
2296   if (!Passthru)
2297     Passthru = DAG.getUNDEF(VT);
2298   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2299     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2300     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2301     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2302     // node in order to try and match RVV vector/scalar instructions.
2303     if ((LoC >> 31) == HiC)
2304       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2305 
2306     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2307     // vmv.v.x whose EEW = 32 to lower it.
2308     auto *Const = dyn_cast<ConstantSDNode>(VL);
2309     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2310       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2311       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2312       // access the subtarget here now.
2313       auto InterVec = DAG.getNode(
2314           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2315                                   DAG.getRegister(RISCV::X0, MVT::i32));
2316       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2317     }
2318   }
2319 
2320   // Fall back to a stack store and stride x0 vector load.
2321   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2322                      Hi, VL);
2323 }
2324 
2325 // Called by type legalization to handle splat of i64 on RV32.
2326 // FIXME: We can optimize this when the type has sign or zero bits in one
2327 // of the halves.
2328 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2329                                    SDValue Scalar, SDValue VL,
2330                                    SelectionDAG &DAG) {
2331   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2332   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2333                            DAG.getConstant(0, DL, MVT::i32));
2334   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2335                            DAG.getConstant(1, DL, MVT::i32));
2336   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2337 }
2338 
2339 // This function lowers a splat of a scalar operand Splat with the vector
2340 // length VL. It ensures the final sequence is type legal, which is useful when
2341 // lowering a splat after type legalization.
2342 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2343                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2344                                 const RISCVSubtarget &Subtarget) {
2345   bool HasPassthru = Passthru && !Passthru.isUndef();
2346   if (!HasPassthru && !Passthru)
2347     Passthru = DAG.getUNDEF(VT);
2348   if (VT.isFloatingPoint()) {
2349     // If VL is 1, we could use vfmv.s.f.
2350     if (isOneConstant(VL))
2351       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2352     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2353   }
2354 
2355   MVT XLenVT = Subtarget.getXLenVT();
2356 
2357   // Simplest case is that the operand needs to be promoted to XLenVT.
2358   if (Scalar.getValueType().bitsLE(XLenVT)) {
2359     // If the operand is a constant, sign extend to increase our chances
2360     // of being able to use a .vi instruction. ANY_EXTEND would become a
2361     // a zero extend and the simm5 check in isel would fail.
2362     // FIXME: Should we ignore the upper bits in isel instead?
2363     unsigned ExtOpc =
2364         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2365     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2366     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2367     // If VL is 1 and the scalar value won't benefit from immediate, we could
2368     // use vmv.s.x.
2369     if (isOneConstant(VL) &&
2370         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2371       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2372     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2373   }
2374 
2375   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2376          "Unexpected scalar for splat lowering!");
2377 
2378   if (isOneConstant(VL) && isNullConstant(Scalar))
2379     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2380                        DAG.getConstant(0, DL, XLenVT), VL);
2381 
2382   // Otherwise use the more complicated splatting algorithm.
2383   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2384 }
2385 
2386 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2387                                 const RISCVSubtarget &Subtarget) {
2388   // We need to be able to widen elements to the next larger integer type.
2389   if (VT.getScalarSizeInBits() >= Subtarget.getELEN())
2390     return false;
2391 
2392   int Size = Mask.size();
2393   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2394 
2395   int Srcs[] = {-1, -1};
2396   for (int i = 0; i != Size; ++i) {
2397     // Ignore undef elements.
2398     if (Mask[i] < 0)
2399       continue;
2400 
2401     // Is this an even or odd element.
2402     int Pol = i % 2;
2403 
2404     // Ensure we consistently use the same source for this element polarity.
2405     int Src = Mask[i] / Size;
2406     if (Srcs[Pol] < 0)
2407       Srcs[Pol] = Src;
2408     if (Srcs[Pol] != Src)
2409       return false;
2410 
2411     // Make sure the element within the source is appropriate for this element
2412     // in the destination.
2413     int Elt = Mask[i] % Size;
2414     if (Elt != i / 2)
2415       return false;
2416   }
2417 
2418   // We need to find a source for each polarity and they can't be the same.
2419   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2420     return false;
2421 
2422   // Swap the sources if the second source was in the even polarity.
2423   SwapSources = Srcs[0] > Srcs[1];
2424 
2425   return true;
2426 }
2427 
2428 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2429 /// and then extract the original number of elements from the rotated result.
2430 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2431 /// returned rotation amount is for a rotate right, where elements move from
2432 /// higher elements to lower elements. \p LoSrc indicates the first source
2433 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2434 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2435 /// 0 or 1 if a rotation is found.
2436 ///
2437 /// NOTE: We talk about rotate to the right which matches how bit shift and
2438 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2439 /// and the table below write vectors with the lowest elements on the left.
2440 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2441   int Size = Mask.size();
2442 
2443   // We need to detect various ways of spelling a rotation:
2444   //   [11, 12, 13, 14, 15,  0,  1,  2]
2445   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2446   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2447   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2448   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2449   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2450   int Rotation = 0;
2451   LoSrc = -1;
2452   HiSrc = -1;
2453   for (int i = 0; i != Size; ++i) {
2454     int M = Mask[i];
2455     if (M < 0)
2456       continue;
2457 
2458     // Determine where a rotate vector would have started.
2459     int StartIdx = i - (M % Size);
2460     // The identity rotation isn't interesting, stop.
2461     if (StartIdx == 0)
2462       return -1;
2463 
2464     // If we found the tail of a vector the rotation must be the missing
2465     // front. If we found the head of a vector, it must be how much of the
2466     // head.
2467     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2468 
2469     if (Rotation == 0)
2470       Rotation = CandidateRotation;
2471     else if (Rotation != CandidateRotation)
2472       // The rotations don't match, so we can't match this mask.
2473       return -1;
2474 
2475     // Compute which value this mask is pointing at.
2476     int MaskSrc = M < Size ? 0 : 1;
2477 
2478     // Compute which of the two target values this index should be assigned to.
2479     // This reflects whether the high elements are remaining or the low elemnts
2480     // are remaining.
2481     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2482 
2483     // Either set up this value if we've not encountered it before, or check
2484     // that it remains consistent.
2485     if (TargetSrc < 0)
2486       TargetSrc = MaskSrc;
2487     else if (TargetSrc != MaskSrc)
2488       // This may be a rotation, but it pulls from the inputs in some
2489       // unsupported interleaving.
2490       return -1;
2491   }
2492 
2493   // Check that we successfully analyzed the mask, and normalize the results.
2494   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2495   assert((LoSrc >= 0 || HiSrc >= 0) &&
2496          "Failed to find a rotated input vector!");
2497 
2498   return Rotation;
2499 }
2500 
2501 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2502                                    const RISCVSubtarget &Subtarget) {
2503   SDValue V1 = Op.getOperand(0);
2504   SDValue V2 = Op.getOperand(1);
2505   SDLoc DL(Op);
2506   MVT XLenVT = Subtarget.getXLenVT();
2507   MVT VT = Op.getSimpleValueType();
2508   unsigned NumElts = VT.getVectorNumElements();
2509   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2510 
2511   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2512 
2513   SDValue TrueMask, VL;
2514   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2515 
2516   if (SVN->isSplat()) {
2517     const int Lane = SVN->getSplatIndex();
2518     if (Lane >= 0) {
2519       MVT SVT = VT.getVectorElementType();
2520 
2521       // Turn splatted vector load into a strided load with an X0 stride.
2522       SDValue V = V1;
2523       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2524       // with undef.
2525       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2526       int Offset = Lane;
2527       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2528         int OpElements =
2529             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2530         V = V.getOperand(Offset / OpElements);
2531         Offset %= OpElements;
2532       }
2533 
2534       // We need to ensure the load isn't atomic or volatile.
2535       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2536         auto *Ld = cast<LoadSDNode>(V);
2537         Offset *= SVT.getStoreSize();
2538         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2539                                                    TypeSize::Fixed(Offset), DL);
2540 
2541         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2542         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2543           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2544           SDValue IntID =
2545               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2546           SDValue Ops[] = {Ld->getChain(),
2547                            IntID,
2548                            DAG.getUNDEF(ContainerVT),
2549                            NewAddr,
2550                            DAG.getRegister(RISCV::X0, XLenVT),
2551                            VL};
2552           SDValue NewLoad = DAG.getMemIntrinsicNode(
2553               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2554               DAG.getMachineFunction().getMachineMemOperand(
2555                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2556           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2557           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2558         }
2559 
2560         // Otherwise use a scalar load and splat. This will give the best
2561         // opportunity to fold a splat into the operation. ISel can turn it into
2562         // the x0 strided load if we aren't able to fold away the select.
2563         if (SVT.isFloatingPoint())
2564           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2565                           Ld->getPointerInfo().getWithOffset(Offset),
2566                           Ld->getOriginalAlign(),
2567                           Ld->getMemOperand()->getFlags());
2568         else
2569           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2570                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2571                              Ld->getOriginalAlign(),
2572                              Ld->getMemOperand()->getFlags());
2573         DAG.makeEquivalentMemoryOrdering(Ld, V);
2574 
2575         unsigned Opc =
2576             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2577         SDValue Splat =
2578             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2579         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2580       }
2581 
2582       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2583       assert(Lane < (int)NumElts && "Unexpected lane!");
2584       SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT,
2585                                    V1, DAG.getConstant(Lane, DL, XLenVT),
2586                                    TrueMask, DAG.getUNDEF(ContainerVT), VL);
2587       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2588     }
2589   }
2590 
2591   ArrayRef<int> Mask = SVN->getMask();
2592 
2593   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2594   // be undef which can be handled with a single SLIDEDOWN/UP.
2595   int LoSrc, HiSrc;
2596   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2597   if (Rotation > 0) {
2598     SDValue LoV, HiV;
2599     if (LoSrc >= 0) {
2600       LoV = LoSrc == 0 ? V1 : V2;
2601       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2602     }
2603     if (HiSrc >= 0) {
2604       HiV = HiSrc == 0 ? V1 : V2;
2605       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2606     }
2607 
2608     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2609     // to slide LoV up by (NumElts - Rotation).
2610     unsigned InvRotate = NumElts - Rotation;
2611 
2612     SDValue Res = DAG.getUNDEF(ContainerVT);
2613     if (HiV) {
2614       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2615       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2616       // causes multiple vsetvlis in some test cases such as lowering
2617       // reduce.mul
2618       SDValue DownVL = VL;
2619       if (LoV)
2620         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2621       Res =
2622           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2623                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2624     }
2625     if (LoV)
2626       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2627                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2628 
2629     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2630   }
2631 
2632   // Detect an interleave shuffle and lower to
2633   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2634   bool SwapSources;
2635   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2636     // Swap sources if needed.
2637     if (SwapSources)
2638       std::swap(V1, V2);
2639 
2640     // Extract the lower half of the vectors.
2641     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2642     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2643                      DAG.getConstant(0, DL, XLenVT));
2644     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2645                      DAG.getConstant(0, DL, XLenVT));
2646 
2647     // Double the element width and halve the number of elements in an int type.
2648     unsigned EltBits = VT.getScalarSizeInBits();
2649     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2650     MVT WideIntVT =
2651         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2652     // Convert this to a scalable vector. We need to base this on the
2653     // destination size to ensure there's always a type with a smaller LMUL.
2654     MVT WideIntContainerVT =
2655         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2656 
2657     // Convert sources to scalable vectors with the same element count as the
2658     // larger type.
2659     MVT HalfContainerVT = MVT::getVectorVT(
2660         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2661     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2662     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2663 
2664     // Cast sources to integer.
2665     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2666     MVT IntHalfVT =
2667         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2668     V1 = DAG.getBitcast(IntHalfVT, V1);
2669     V2 = DAG.getBitcast(IntHalfVT, V2);
2670 
2671     // Freeze V2 since we use it twice and we need to be sure that the add and
2672     // multiply see the same value.
2673     V2 = DAG.getFreeze(V2);
2674 
2675     // Recreate TrueMask using the widened type's element count.
2676     TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG);
2677 
2678     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2679     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2680                               V2, TrueMask, VL);
2681     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2682     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2683                                      DAG.getUNDEF(IntHalfVT),
2684                                      DAG.getAllOnesConstant(DL, XLenVT));
2685     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2686                                    V2, Multiplier, TrueMask, VL);
2687     // Add the new copies to our previous addition giving us 2^eltbits copies of
2688     // V2. This is equivalent to shifting V2 left by eltbits. This should
2689     // combine with the vwmulu.vv above to form vwmaccu.vv.
2690     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2691                       TrueMask, VL);
2692     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2693     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2694     // vector VT.
2695     ContainerVT =
2696         MVT::getVectorVT(VT.getVectorElementType(),
2697                          WideIntContainerVT.getVectorElementCount() * 2);
2698     Add = DAG.getBitcast(ContainerVT, Add);
2699     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2700   }
2701 
2702   // Detect shuffles which can be re-expressed as vector selects; these are
2703   // shuffles in which each element in the destination is taken from an element
2704   // at the corresponding index in either source vectors.
2705   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2706     int MaskIndex = MaskIdx.value();
2707     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2708   });
2709 
2710   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2711 
2712   SmallVector<SDValue> MaskVals;
2713   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2714   // merged with a second vrgather.
2715   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2716 
2717   // By default we preserve the original operand order, and use a mask to
2718   // select LHS as true and RHS as false. However, since RVV vector selects may
2719   // feature splats but only on the LHS, we may choose to invert our mask and
2720   // instead select between RHS and LHS.
2721   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2722   bool InvertMask = IsSelect == SwapOps;
2723 
2724   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2725   // half.
2726   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2727 
2728   // Now construct the mask that will be used by the vselect or blended
2729   // vrgather operation. For vrgathers, construct the appropriate indices into
2730   // each vector.
2731   for (int MaskIndex : Mask) {
2732     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2733     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2734     if (!IsSelect) {
2735       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2736       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2737                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2738                                      : DAG.getUNDEF(XLenVT));
2739       GatherIndicesRHS.push_back(
2740           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2741                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2742       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2743         ++LHSIndexCounts[MaskIndex];
2744       if (!IsLHSOrUndefIndex)
2745         ++RHSIndexCounts[MaskIndex - NumElts];
2746     }
2747   }
2748 
2749   if (SwapOps) {
2750     std::swap(V1, V2);
2751     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2752   }
2753 
2754   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2755   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2756   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2757 
2758   if (IsSelect)
2759     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2760 
2761   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2762     // On such a large vector we're unable to use i8 as the index type.
2763     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2764     // may involve vector splitting if we're already at LMUL=8, or our
2765     // user-supplied maximum fixed-length LMUL.
2766     return SDValue();
2767   }
2768 
2769   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2770   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2771   MVT IndexVT = VT.changeTypeToInteger();
2772   // Since we can't introduce illegal index types at this stage, use i16 and
2773   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2774   // than XLenVT.
2775   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2776     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2777     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2778   }
2779 
2780   MVT IndexContainerVT =
2781       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2782 
2783   SDValue Gather;
2784   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2785   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2786   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2787     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2788                               Subtarget);
2789   } else {
2790     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2791     // If only one index is used, we can use a "splat" vrgather.
2792     // TODO: We can splat the most-common index and fix-up any stragglers, if
2793     // that's beneficial.
2794     if (LHSIndexCounts.size() == 1) {
2795       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2796       Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2797                            DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask,
2798                            DAG.getUNDEF(ContainerVT), VL);
2799     } else {
2800       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2801       LHSIndices =
2802           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2803 
2804       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2805                            TrueMask, DAG.getUNDEF(ContainerVT), VL);
2806     }
2807   }
2808 
2809   // If a second vector operand is used by this shuffle, blend it in with an
2810   // additional vrgather.
2811   if (!V2.isUndef()) {
2812     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2813 
2814     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2815     SelectMask =
2816         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2817 
2818     // If only one index is used, we can use a "splat" vrgather.
2819     // TODO: We can splat the most-common index and fix-up any stragglers, if
2820     // that's beneficial.
2821     if (RHSIndexCounts.size() == 1) {
2822       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2823       Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2824                            DAG.getConstant(SplatIndex, DL, XLenVT), SelectMask,
2825                            Gather, VL);
2826     } else {
2827       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2828       RHSIndices =
2829           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2830       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices,
2831                            SelectMask, Gather, VL);
2832     }
2833   }
2834 
2835   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2836 }
2837 
2838 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2839   // Support splats for any type. These should type legalize well.
2840   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2841     return true;
2842 
2843   // Only support legal VTs for other shuffles for now.
2844   if (!isTypeLegal(VT))
2845     return false;
2846 
2847   MVT SVT = VT.getSimpleVT();
2848 
2849   bool SwapSources;
2850   int LoSrc, HiSrc;
2851   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2852          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2853 }
2854 
2855 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2856 // the exponent.
2857 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2858   MVT VT = Op.getSimpleValueType();
2859   unsigned EltSize = VT.getScalarSizeInBits();
2860   SDValue Src = Op.getOperand(0);
2861   SDLoc DL(Op);
2862 
2863   // We need a FP type that can represent the value.
2864   // TODO: Use f16 for i8 when possible?
2865   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2866   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2867 
2868   // Legal types should have been checked in the RISCVTargetLowering
2869   // constructor.
2870   // TODO: Splitting may make sense in some cases.
2871   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2872          "Expected legal float type!");
2873 
2874   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2875   // The trailing zero count is equal to log2 of this single bit value.
2876   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2877     SDValue Neg =
2878         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2879     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2880   }
2881 
2882   // We have a legal FP type, convert to it.
2883   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2884   // Bitcast to integer and shift the exponent to the LSB.
2885   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2886   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2887   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2888   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2889                               DAG.getConstant(ShiftAmt, DL, IntVT));
2890   // Truncate back to original type to allow vnsrl.
2891   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2892   // The exponent contains log2 of the value in biased form.
2893   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2894 
2895   // For trailing zeros, we just need to subtract the bias.
2896   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2897     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2898                        DAG.getConstant(ExponentBias, DL, VT));
2899 
2900   // For leading zeros, we need to remove the bias and convert from log2 to
2901   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2902   unsigned Adjust = ExponentBias + (EltSize - 1);
2903   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2904 }
2905 
2906 // While RVV has alignment restrictions, we should always be able to load as a
2907 // legal equivalently-sized byte-typed vector instead. This method is
2908 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2909 // the load is already correctly-aligned, it returns SDValue().
2910 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2911                                                     SelectionDAG &DAG) const {
2912   auto *Load = cast<LoadSDNode>(Op);
2913   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2914 
2915   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2916                                      Load->getMemoryVT(),
2917                                      *Load->getMemOperand()))
2918     return SDValue();
2919 
2920   SDLoc DL(Op);
2921   MVT VT = Op.getSimpleValueType();
2922   unsigned EltSizeBits = VT.getScalarSizeInBits();
2923   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2924          "Unexpected unaligned RVV load type");
2925   MVT NewVT =
2926       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2927   assert(NewVT.isValid() &&
2928          "Expecting equally-sized RVV vector types to be legal");
2929   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2930                           Load->getPointerInfo(), Load->getOriginalAlign(),
2931                           Load->getMemOperand()->getFlags());
2932   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2933 }
2934 
2935 // While RVV has alignment restrictions, we should always be able to store as a
2936 // legal equivalently-sized byte-typed vector instead. This method is
2937 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2938 // returns SDValue() if the store is already correctly aligned.
2939 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2940                                                      SelectionDAG &DAG) const {
2941   auto *Store = cast<StoreSDNode>(Op);
2942   assert(Store && Store->getValue().getValueType().isVector() &&
2943          "Expected vector store");
2944 
2945   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2946                                      Store->getMemoryVT(),
2947                                      *Store->getMemOperand()))
2948     return SDValue();
2949 
2950   SDLoc DL(Op);
2951   SDValue StoredVal = Store->getValue();
2952   MVT VT = StoredVal.getSimpleValueType();
2953   unsigned EltSizeBits = VT.getScalarSizeInBits();
2954   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2955          "Unexpected unaligned RVV store type");
2956   MVT NewVT =
2957       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2958   assert(NewVT.isValid() &&
2959          "Expecting equally-sized RVV vector types to be legal");
2960   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2961   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2962                       Store->getPointerInfo(), Store->getOriginalAlign(),
2963                       Store->getMemOperand()->getFlags());
2964 }
2965 
2966 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG,
2967                              const RISCVSubtarget &Subtarget) {
2968   assert(Op.getValueType() == MVT::i64 && "Unexpected VT");
2969 
2970   int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue();
2971 
2972   // All simm32 constants should be handled by isel.
2973   // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making
2974   // this check redundant, but small immediates are common so this check
2975   // should have better compile time.
2976   if (isInt<32>(Imm))
2977     return Op;
2978 
2979   // We only need to cost the immediate, if constant pool lowering is enabled.
2980   if (!Subtarget.useConstantPoolForLargeInts())
2981     return Op;
2982 
2983   RISCVMatInt::InstSeq Seq =
2984       RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits());
2985   if (Seq.size() <= Subtarget.getMaxBuildIntsCost())
2986     return Op;
2987 
2988   // Expand to a constant pool using the default expansion code.
2989   return SDValue();
2990 }
2991 
2992 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2993                                             SelectionDAG &DAG) const {
2994   switch (Op.getOpcode()) {
2995   default:
2996     report_fatal_error("unimplemented operand");
2997   case ISD::GlobalAddress:
2998     return lowerGlobalAddress(Op, DAG);
2999   case ISD::BlockAddress:
3000     return lowerBlockAddress(Op, DAG);
3001   case ISD::ConstantPool:
3002     return lowerConstantPool(Op, DAG);
3003   case ISD::JumpTable:
3004     return lowerJumpTable(Op, DAG);
3005   case ISD::GlobalTLSAddress:
3006     return lowerGlobalTLSAddress(Op, DAG);
3007   case ISD::Constant:
3008     return lowerConstant(Op, DAG, Subtarget);
3009   case ISD::SELECT:
3010     return lowerSELECT(Op, DAG);
3011   case ISD::BRCOND:
3012     return lowerBRCOND(Op, DAG);
3013   case ISD::VASTART:
3014     return lowerVASTART(Op, DAG);
3015   case ISD::FRAMEADDR:
3016     return lowerFRAMEADDR(Op, DAG);
3017   case ISD::RETURNADDR:
3018     return lowerRETURNADDR(Op, DAG);
3019   case ISD::SHL_PARTS:
3020     return lowerShiftLeftParts(Op, DAG);
3021   case ISD::SRA_PARTS:
3022     return lowerShiftRightParts(Op, DAG, true);
3023   case ISD::SRL_PARTS:
3024     return lowerShiftRightParts(Op, DAG, false);
3025   case ISD::BITCAST: {
3026     SDLoc DL(Op);
3027     EVT VT = Op.getValueType();
3028     SDValue Op0 = Op.getOperand(0);
3029     EVT Op0VT = Op0.getValueType();
3030     MVT XLenVT = Subtarget.getXLenVT();
3031     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3032       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3033       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3034       return FPConv;
3035     }
3036     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3037         Subtarget.hasStdExtF()) {
3038       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3039       SDValue FPConv =
3040           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3041       return FPConv;
3042     }
3043 
3044     // Consider other scalar<->scalar casts as legal if the types are legal.
3045     // Otherwise expand them.
3046     if (!VT.isVector() && !Op0VT.isVector()) {
3047       if (isTypeLegal(VT) && isTypeLegal(Op0VT))
3048         return Op;
3049       return SDValue();
3050     }
3051 
3052     assert(!VT.isScalableVector() && !Op0VT.isScalableVector() &&
3053            "Unexpected types");
3054 
3055     if (VT.isFixedLengthVector()) {
3056       // We can handle fixed length vector bitcasts with a simple replacement
3057       // in isel.
3058       if (Op0VT.isFixedLengthVector())
3059         return Op;
3060       // When bitcasting from scalar to fixed-length vector, insert the scalar
3061       // into a one-element vector of the result type, and perform a vector
3062       // bitcast.
3063       if (!Op0VT.isVector()) {
3064         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3065         if (!isTypeLegal(BVT))
3066           return SDValue();
3067         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3068                                               DAG.getUNDEF(BVT), Op0,
3069                                               DAG.getConstant(0, DL, XLenVT)));
3070       }
3071       return SDValue();
3072     }
3073     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3074     // thus: bitcast the vector to a one-element vector type whose element type
3075     // is the same as the result type, and extract the first element.
3076     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3077       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3078       if (!isTypeLegal(BVT))
3079         return SDValue();
3080       SDValue BVec = DAG.getBitcast(BVT, Op0);
3081       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3082                          DAG.getConstant(0, DL, XLenVT));
3083     }
3084     return SDValue();
3085   }
3086   case ISD::INTRINSIC_WO_CHAIN:
3087     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3088   case ISD::INTRINSIC_W_CHAIN:
3089     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3090   case ISD::INTRINSIC_VOID:
3091     return LowerINTRINSIC_VOID(Op, DAG);
3092   case ISD::BSWAP:
3093   case ISD::BITREVERSE: {
3094     MVT VT = Op.getSimpleValueType();
3095     SDLoc DL(Op);
3096     if (Subtarget.hasStdExtZbp()) {
3097       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3098       // Start with the maximum immediate value which is the bitwidth - 1.
3099       unsigned Imm = VT.getSizeInBits() - 1;
3100       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3101       if (Op.getOpcode() == ISD::BSWAP)
3102         Imm &= ~0x7U;
3103       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3104                          DAG.getConstant(Imm, DL, VT));
3105     }
3106     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3107     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3108     // Expand bitreverse to a bswap(rev8) followed by brev8.
3109     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3110     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3111     // as brev8 by an isel pattern.
3112     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3113                        DAG.getConstant(7, DL, VT));
3114   }
3115   case ISD::FSHL:
3116   case ISD::FSHR: {
3117     MVT VT = Op.getSimpleValueType();
3118     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3119     SDLoc DL(Op);
3120     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3121     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3122     // accidentally setting the extra bit.
3123     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3124     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3125                                 DAG.getConstant(ShAmtWidth, DL, VT));
3126     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3127     // instruction use different orders. fshl will return its first operand for
3128     // shift of zero, fshr will return its second operand. fsl and fsr both
3129     // return rs1 so the ISD nodes need to have different operand orders.
3130     // Shift amount is in rs2.
3131     SDValue Op0 = Op.getOperand(0);
3132     SDValue Op1 = Op.getOperand(1);
3133     unsigned Opc = RISCVISD::FSL;
3134     if (Op.getOpcode() == ISD::FSHR) {
3135       std::swap(Op0, Op1);
3136       Opc = RISCVISD::FSR;
3137     }
3138     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3139   }
3140   case ISD::TRUNCATE:
3141     // Only custom-lower vector truncates
3142     if (!Op.getSimpleValueType().isVector())
3143       return Op;
3144     return lowerVectorTruncLike(Op, DAG);
3145   case ISD::ANY_EXTEND:
3146   case ISD::ZERO_EXTEND:
3147     if (Op.getOperand(0).getValueType().isVector() &&
3148         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3149       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3150     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3151   case ISD::SIGN_EXTEND:
3152     if (Op.getOperand(0).getValueType().isVector() &&
3153         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3154       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3155     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3156   case ISD::SPLAT_VECTOR_PARTS:
3157     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3158   case ISD::INSERT_VECTOR_ELT:
3159     return lowerINSERT_VECTOR_ELT(Op, DAG);
3160   case ISD::EXTRACT_VECTOR_ELT:
3161     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3162   case ISD::VSCALE: {
3163     MVT VT = Op.getSimpleValueType();
3164     SDLoc DL(Op);
3165     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3166     // We define our scalable vector types for lmul=1 to use a 64 bit known
3167     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3168     // vscale as VLENB / 8.
3169     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3170     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3171       report_fatal_error("Support for VLEN==32 is incomplete.");
3172     // We assume VLENB is a multiple of 8. We manually choose the best shift
3173     // here because SimplifyDemandedBits isn't always able to simplify it.
3174     uint64_t Val = Op.getConstantOperandVal(0);
3175     if (isPowerOf2_64(Val)) {
3176       uint64_t Log2 = Log2_64(Val);
3177       if (Log2 < 3)
3178         return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3179                            DAG.getConstant(3 - Log2, DL, VT));
3180       if (Log2 > 3)
3181         return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3182                            DAG.getConstant(Log2 - 3, DL, VT));
3183       return VLENB;
3184     }
3185     // If the multiplier is a multiple of 8, scale it down to avoid needing
3186     // to shift the VLENB value.
3187     if ((Val % 8) == 0)
3188       return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3189                          DAG.getConstant(Val / 8, DL, VT));
3190 
3191     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3192                                  DAG.getConstant(3, DL, VT));
3193     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3194   }
3195   case ISD::FPOWI: {
3196     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3197     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3198     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3199         Op.getOperand(1).getValueType() == MVT::i32) {
3200       SDLoc DL(Op);
3201       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3202       SDValue Powi =
3203           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3204       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3205                          DAG.getIntPtrConstant(0, DL));
3206     }
3207     return SDValue();
3208   }
3209   case ISD::FP_EXTEND:
3210   case ISD::FP_ROUND:
3211     if (!Op.getValueType().isVector())
3212       return Op;
3213     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3214   case ISD::FP_TO_SINT:
3215   case ISD::FP_TO_UINT:
3216   case ISD::SINT_TO_FP:
3217   case ISD::UINT_TO_FP: {
3218     // RVV can only do fp<->int conversions to types half/double the size as
3219     // the source. We custom-lower any conversions that do two hops into
3220     // sequences.
3221     MVT VT = Op.getSimpleValueType();
3222     if (!VT.isVector())
3223       return Op;
3224     SDLoc DL(Op);
3225     SDValue Src = Op.getOperand(0);
3226     MVT EltVT = VT.getVectorElementType();
3227     MVT SrcVT = Src.getSimpleValueType();
3228     MVT SrcEltVT = SrcVT.getVectorElementType();
3229     unsigned EltSize = EltVT.getSizeInBits();
3230     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3231     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3232            "Unexpected vector element types");
3233 
3234     bool IsInt2FP = SrcEltVT.isInteger();
3235     // Widening conversions
3236     if (EltSize > (2 * SrcEltSize)) {
3237       if (IsInt2FP) {
3238         // Do a regular integer sign/zero extension then convert to float.
3239         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize),
3240                                       VT.getVectorElementCount());
3241         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3242                                  ? ISD::ZERO_EXTEND
3243                                  : ISD::SIGN_EXTEND;
3244         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3245         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3246       }
3247       // FP2Int
3248       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3249       // Do one doubling fp_extend then complete the operation by converting
3250       // to int.
3251       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3252       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3253       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3254     }
3255 
3256     // Narrowing conversions
3257     if (SrcEltSize > (2 * EltSize)) {
3258       if (IsInt2FP) {
3259         // One narrowing int_to_fp, then an fp_round.
3260         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3261         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3262         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3263         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3264       }
3265       // FP2Int
3266       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3267       // representable by the integer, the result is poison.
3268       MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
3269                                     VT.getVectorElementCount());
3270       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3271       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3272     }
3273 
3274     // Scalable vectors can exit here. Patterns will handle equally-sized
3275     // conversions halving/doubling ones.
3276     if (!VT.isFixedLengthVector())
3277       return Op;
3278 
3279     // For fixed-length vectors we lower to a custom "VL" node.
3280     unsigned RVVOpc = 0;
3281     switch (Op.getOpcode()) {
3282     default:
3283       llvm_unreachable("Impossible opcode");
3284     case ISD::FP_TO_SINT:
3285       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3286       break;
3287     case ISD::FP_TO_UINT:
3288       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3289       break;
3290     case ISD::SINT_TO_FP:
3291       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3292       break;
3293     case ISD::UINT_TO_FP:
3294       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3295       break;
3296     }
3297 
3298     MVT ContainerVT, SrcContainerVT;
3299     // Derive the reference container type from the larger vector type.
3300     if (SrcEltSize > EltSize) {
3301       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3302       ContainerVT =
3303           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3304     } else {
3305       ContainerVT = getContainerForFixedLengthVector(VT);
3306       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3307     }
3308 
3309     SDValue Mask, VL;
3310     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3311 
3312     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3313     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3314     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3315   }
3316   case ISD::FP_TO_SINT_SAT:
3317   case ISD::FP_TO_UINT_SAT:
3318     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3319   case ISD::FTRUNC:
3320   case ISD::FCEIL:
3321   case ISD::FFLOOR:
3322     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3323   case ISD::FROUND:
3324     return lowerFROUND(Op, DAG);
3325   case ISD::VECREDUCE_ADD:
3326   case ISD::VECREDUCE_UMAX:
3327   case ISD::VECREDUCE_SMAX:
3328   case ISD::VECREDUCE_UMIN:
3329   case ISD::VECREDUCE_SMIN:
3330     return lowerVECREDUCE(Op, DAG);
3331   case ISD::VECREDUCE_AND:
3332   case ISD::VECREDUCE_OR:
3333   case ISD::VECREDUCE_XOR:
3334     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3335       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3336     return lowerVECREDUCE(Op, DAG);
3337   case ISD::VECREDUCE_FADD:
3338   case ISD::VECREDUCE_SEQ_FADD:
3339   case ISD::VECREDUCE_FMIN:
3340   case ISD::VECREDUCE_FMAX:
3341     return lowerFPVECREDUCE(Op, DAG);
3342   case ISD::VP_REDUCE_ADD:
3343   case ISD::VP_REDUCE_UMAX:
3344   case ISD::VP_REDUCE_SMAX:
3345   case ISD::VP_REDUCE_UMIN:
3346   case ISD::VP_REDUCE_SMIN:
3347   case ISD::VP_REDUCE_FADD:
3348   case ISD::VP_REDUCE_SEQ_FADD:
3349   case ISD::VP_REDUCE_FMIN:
3350   case ISD::VP_REDUCE_FMAX:
3351     return lowerVPREDUCE(Op, DAG);
3352   case ISD::VP_REDUCE_AND:
3353   case ISD::VP_REDUCE_OR:
3354   case ISD::VP_REDUCE_XOR:
3355     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3356       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3357     return lowerVPREDUCE(Op, DAG);
3358   case ISD::INSERT_SUBVECTOR:
3359     return lowerINSERT_SUBVECTOR(Op, DAG);
3360   case ISD::EXTRACT_SUBVECTOR:
3361     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3362   case ISD::STEP_VECTOR:
3363     return lowerSTEP_VECTOR(Op, DAG);
3364   case ISD::VECTOR_REVERSE:
3365     return lowerVECTOR_REVERSE(Op, DAG);
3366   case ISD::VECTOR_SPLICE:
3367     return lowerVECTOR_SPLICE(Op, DAG);
3368   case ISD::BUILD_VECTOR:
3369     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3370   case ISD::SPLAT_VECTOR:
3371     if (Op.getValueType().getVectorElementType() == MVT::i1)
3372       return lowerVectorMaskSplat(Op, DAG);
3373     return SDValue();
3374   case ISD::VECTOR_SHUFFLE:
3375     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3376   case ISD::CONCAT_VECTORS: {
3377     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3378     // better than going through the stack, as the default expansion does.
3379     SDLoc DL(Op);
3380     MVT VT = Op.getSimpleValueType();
3381     unsigned NumOpElts =
3382         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3383     SDValue Vec = DAG.getUNDEF(VT);
3384     for (const auto &OpIdx : enumerate(Op->ops())) {
3385       SDValue SubVec = OpIdx.value();
3386       // Don't insert undef subvectors.
3387       if (SubVec.isUndef())
3388         continue;
3389       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3390                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3391     }
3392     return Vec;
3393   }
3394   case ISD::LOAD:
3395     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3396       return V;
3397     if (Op.getValueType().isFixedLengthVector())
3398       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3399     return Op;
3400   case ISD::STORE:
3401     if (auto V = expandUnalignedRVVStore(Op, DAG))
3402       return V;
3403     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3404       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3405     return Op;
3406   case ISD::MLOAD:
3407   case ISD::VP_LOAD:
3408     return lowerMaskedLoad(Op, DAG);
3409   case ISD::MSTORE:
3410   case ISD::VP_STORE:
3411     return lowerMaskedStore(Op, DAG);
3412   case ISD::SETCC:
3413     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3414   case ISD::ADD:
3415     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3416   case ISD::SUB:
3417     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3418   case ISD::MUL:
3419     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3420   case ISD::MULHS:
3421     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3422   case ISD::MULHU:
3423     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3424   case ISD::AND:
3425     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3426                                               RISCVISD::AND_VL);
3427   case ISD::OR:
3428     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3429                                               RISCVISD::OR_VL);
3430   case ISD::XOR:
3431     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3432                                               RISCVISD::XOR_VL);
3433   case ISD::SDIV:
3434     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3435   case ISD::SREM:
3436     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3437   case ISD::UDIV:
3438     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3439   case ISD::UREM:
3440     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3441   case ISD::SHL:
3442   case ISD::SRA:
3443   case ISD::SRL:
3444     if (Op.getSimpleValueType().isFixedLengthVector())
3445       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3446     // This can be called for an i32 shift amount that needs to be promoted.
3447     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3448            "Unexpected custom legalisation");
3449     return SDValue();
3450   case ISD::SADDSAT:
3451     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3452   case ISD::UADDSAT:
3453     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3454   case ISD::SSUBSAT:
3455     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3456   case ISD::USUBSAT:
3457     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3458   case ISD::FADD:
3459     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3460   case ISD::FSUB:
3461     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3462   case ISD::FMUL:
3463     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3464   case ISD::FDIV:
3465     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3466   case ISD::FNEG:
3467     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3468   case ISD::FABS:
3469     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3470   case ISD::FSQRT:
3471     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3472   case ISD::FMA:
3473     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3474   case ISD::SMIN:
3475     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3476   case ISD::SMAX:
3477     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3478   case ISD::UMIN:
3479     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3480   case ISD::UMAX:
3481     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3482   case ISD::FMINNUM:
3483     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3484   case ISD::FMAXNUM:
3485     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3486   case ISD::ABS:
3487     return lowerABS(Op, DAG);
3488   case ISD::CTLZ_ZERO_UNDEF:
3489   case ISD::CTTZ_ZERO_UNDEF:
3490     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3491   case ISD::VSELECT:
3492     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3493   case ISD::FCOPYSIGN:
3494     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3495   case ISD::MGATHER:
3496   case ISD::VP_GATHER:
3497     return lowerMaskedGather(Op, DAG);
3498   case ISD::MSCATTER:
3499   case ISD::VP_SCATTER:
3500     return lowerMaskedScatter(Op, DAG);
3501   case ISD::FLT_ROUNDS_:
3502     return lowerGET_ROUNDING(Op, DAG);
3503   case ISD::SET_ROUNDING:
3504     return lowerSET_ROUNDING(Op, DAG);
3505   case ISD::EH_DWARF_CFA:
3506     return lowerEH_DWARF_CFA(Op, DAG);
3507   case ISD::VP_SELECT:
3508     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3509   case ISD::VP_MERGE:
3510     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3511   case ISD::VP_ADD:
3512     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3513   case ISD::VP_SUB:
3514     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3515   case ISD::VP_MUL:
3516     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3517   case ISD::VP_SDIV:
3518     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3519   case ISD::VP_UDIV:
3520     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3521   case ISD::VP_SREM:
3522     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3523   case ISD::VP_UREM:
3524     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3525   case ISD::VP_AND:
3526     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3527   case ISD::VP_OR:
3528     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3529   case ISD::VP_XOR:
3530     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3531   case ISD::VP_ASHR:
3532     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3533   case ISD::VP_LSHR:
3534     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3535   case ISD::VP_SHL:
3536     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3537   case ISD::VP_FADD:
3538     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3539   case ISD::VP_FSUB:
3540     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3541   case ISD::VP_FMUL:
3542     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3543   case ISD::VP_FDIV:
3544     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3545   case ISD::VP_FNEG:
3546     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3547   case ISD::VP_FMA:
3548     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3549   case ISD::VP_SIGN_EXTEND:
3550   case ISD::VP_ZERO_EXTEND:
3551     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3552       return lowerVPExtMaskOp(Op, DAG);
3553     return lowerVPOp(Op, DAG,
3554                      Op.getOpcode() == ISD::VP_SIGN_EXTEND
3555                          ? RISCVISD::VSEXT_VL
3556                          : RISCVISD::VZEXT_VL);
3557   case ISD::VP_TRUNCATE:
3558     return lowerVectorTruncLike(Op, DAG);
3559   case ISD::VP_FP_EXTEND:
3560   case ISD::VP_FP_ROUND:
3561     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3562   case ISD::VP_FPTOSI:
3563     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL);
3564   case ISD::VP_FPTOUI:
3565     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL);
3566   case ISD::VP_SITOFP:
3567     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
3568   case ISD::VP_UITOFP:
3569     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL);
3570   case ISD::VP_SETCC:
3571     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3572       return lowerVPSetCCMaskOp(Op, DAG);
3573     return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL);
3574   }
3575 }
3576 
3577 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3578                              SelectionDAG &DAG, unsigned Flags) {
3579   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3580 }
3581 
3582 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3583                              SelectionDAG &DAG, unsigned Flags) {
3584   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3585                                    Flags);
3586 }
3587 
3588 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3589                              SelectionDAG &DAG, unsigned Flags) {
3590   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3591                                    N->getOffset(), Flags);
3592 }
3593 
3594 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3595                              SelectionDAG &DAG, unsigned Flags) {
3596   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3597 }
3598 
3599 template <class NodeTy>
3600 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3601                                      bool IsLocal) const {
3602   SDLoc DL(N);
3603   EVT Ty = getPointerTy(DAG.getDataLayout());
3604 
3605   if (isPositionIndependent()) {
3606     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3607     if (IsLocal)
3608       // Use PC-relative addressing to access the symbol. This generates the
3609       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3610       // %pcrel_lo(auipc)).
3611       return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
3612 
3613     // Use PC-relative addressing to access the GOT for this symbol, then load
3614     // the address from the GOT. This generates the pattern (PseudoLA sym),
3615     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3616     SDValue Load =
3617         SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3618     MachineFunction &MF = DAG.getMachineFunction();
3619     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3620         MachinePointerInfo::getGOT(MF),
3621         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3622             MachineMemOperand::MOInvariant,
3623         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3624     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3625     return Load;
3626   }
3627 
3628   switch (getTargetMachine().getCodeModel()) {
3629   default:
3630     report_fatal_error("Unsupported code model for lowering");
3631   case CodeModel::Small: {
3632     // Generate a sequence for accessing addresses within the first 2 GiB of
3633     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3634     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3635     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3636     SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
3637     return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo);
3638   }
3639   case CodeModel::Medium: {
3640     // Generate a sequence for accessing addresses within any 2GiB range within
3641     // the address space. This generates the pattern (PseudoLLA sym), which
3642     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3643     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3644     return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
3645   }
3646   }
3647 }
3648 
3649 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3650                                                 SelectionDAG &DAG) const {
3651   SDLoc DL(Op);
3652   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3653   assert(N->getOffset() == 0 && "unexpected offset in global node");
3654 
3655   const GlobalValue *GV = N->getGlobal();
3656   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3657   return getAddr(N, DAG, IsLocal);
3658 }
3659 
3660 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3661                                                SelectionDAG &DAG) const {
3662   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3663 
3664   return getAddr(N, DAG);
3665 }
3666 
3667 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3668                                                SelectionDAG &DAG) const {
3669   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3670 
3671   return getAddr(N, DAG);
3672 }
3673 
3674 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3675                                             SelectionDAG &DAG) const {
3676   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3677 
3678   return getAddr(N, DAG);
3679 }
3680 
3681 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3682                                               SelectionDAG &DAG,
3683                                               bool UseGOT) const {
3684   SDLoc DL(N);
3685   EVT Ty = getPointerTy(DAG.getDataLayout());
3686   const GlobalValue *GV = N->getGlobal();
3687   MVT XLenVT = Subtarget.getXLenVT();
3688 
3689   if (UseGOT) {
3690     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3691     // load the address from the GOT and add the thread pointer. This generates
3692     // the pattern (PseudoLA_TLS_IE sym), which expands to
3693     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3694     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3695     SDValue Load =
3696         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3697     MachineFunction &MF = DAG.getMachineFunction();
3698     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3699         MachinePointerInfo::getGOT(MF),
3700         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3701             MachineMemOperand::MOInvariant,
3702         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3703     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3704 
3705     // Add the thread pointer.
3706     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3707     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3708   }
3709 
3710   // Generate a sequence for accessing the address relative to the thread
3711   // pointer, with the appropriate adjustment for the thread pointer offset.
3712   // This generates the pattern
3713   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3714   SDValue AddrHi =
3715       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3716   SDValue AddrAdd =
3717       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3718   SDValue AddrLo =
3719       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3720 
3721   SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
3722   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3723   SDValue MNAdd =
3724       DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd);
3725   return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo);
3726 }
3727 
3728 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3729                                                SelectionDAG &DAG) const {
3730   SDLoc DL(N);
3731   EVT Ty = getPointerTy(DAG.getDataLayout());
3732   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3733   const GlobalValue *GV = N->getGlobal();
3734 
3735   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3736   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3737   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3738   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3739   SDValue Load =
3740       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3741 
3742   // Prepare argument list to generate call.
3743   ArgListTy Args;
3744   ArgListEntry Entry;
3745   Entry.Node = Load;
3746   Entry.Ty = CallTy;
3747   Args.push_back(Entry);
3748 
3749   // Setup call to __tls_get_addr.
3750   TargetLowering::CallLoweringInfo CLI(DAG);
3751   CLI.setDebugLoc(DL)
3752       .setChain(DAG.getEntryNode())
3753       .setLibCallee(CallingConv::C, CallTy,
3754                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3755                     std::move(Args));
3756 
3757   return LowerCallTo(CLI).first;
3758 }
3759 
3760 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3761                                                    SelectionDAG &DAG) const {
3762   SDLoc DL(Op);
3763   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3764   assert(N->getOffset() == 0 && "unexpected offset in global node");
3765 
3766   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3767 
3768   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3769       CallingConv::GHC)
3770     report_fatal_error("In GHC calling convention TLS is not supported");
3771 
3772   SDValue Addr;
3773   switch (Model) {
3774   case TLSModel::LocalExec:
3775     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3776     break;
3777   case TLSModel::InitialExec:
3778     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3779     break;
3780   case TLSModel::LocalDynamic:
3781   case TLSModel::GeneralDynamic:
3782     Addr = getDynamicTLSAddr(N, DAG);
3783     break;
3784   }
3785 
3786   return Addr;
3787 }
3788 
3789 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3790   SDValue CondV = Op.getOperand(0);
3791   SDValue TrueV = Op.getOperand(1);
3792   SDValue FalseV = Op.getOperand(2);
3793   SDLoc DL(Op);
3794   MVT VT = Op.getSimpleValueType();
3795   MVT XLenVT = Subtarget.getXLenVT();
3796 
3797   // Lower vector SELECTs to VSELECTs by splatting the condition.
3798   if (VT.isVector()) {
3799     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3800     SDValue CondSplat = VT.isScalableVector()
3801                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3802                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3803     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3804   }
3805 
3806   // If the result type is XLenVT and CondV is the output of a SETCC node
3807   // which also operated on XLenVT inputs, then merge the SETCC node into the
3808   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3809   // compare+branch instructions. i.e.:
3810   // (select (setcc lhs, rhs, cc), truev, falsev)
3811   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3812   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3813       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3814     SDValue LHS = CondV.getOperand(0);
3815     SDValue RHS = CondV.getOperand(1);
3816     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3817     ISD::CondCode CCVal = CC->get();
3818 
3819     // Special case for a select of 2 constants that have a diffence of 1.
3820     // Normally this is done by DAGCombine, but if the select is introduced by
3821     // type legalization or op legalization, we miss it. Restricting to SETLT
3822     // case for now because that is what signed saturating add/sub need.
3823     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3824     // but we would probably want to swap the true/false values if the condition
3825     // is SETGE/SETLE to avoid an XORI.
3826     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3827         CCVal == ISD::SETLT) {
3828       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3829       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3830       if (TrueVal - 1 == FalseVal)
3831         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3832       if (TrueVal + 1 == FalseVal)
3833         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3834     }
3835 
3836     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3837 
3838     SDValue TargetCC = DAG.getCondCode(CCVal);
3839     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3840     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3841   }
3842 
3843   // Otherwise:
3844   // (select condv, truev, falsev)
3845   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3846   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3847   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3848 
3849   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3850 
3851   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3852 }
3853 
3854 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3855   SDValue CondV = Op.getOperand(1);
3856   SDLoc DL(Op);
3857   MVT XLenVT = Subtarget.getXLenVT();
3858 
3859   if (CondV.getOpcode() == ISD::SETCC &&
3860       CondV.getOperand(0).getValueType() == XLenVT) {
3861     SDValue LHS = CondV.getOperand(0);
3862     SDValue RHS = CondV.getOperand(1);
3863     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3864 
3865     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3866 
3867     SDValue TargetCC = DAG.getCondCode(CCVal);
3868     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3869                        LHS, RHS, TargetCC, Op.getOperand(2));
3870   }
3871 
3872   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3873                      CondV, DAG.getConstant(0, DL, XLenVT),
3874                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3875 }
3876 
3877 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3878   MachineFunction &MF = DAG.getMachineFunction();
3879   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3880 
3881   SDLoc DL(Op);
3882   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3883                                  getPointerTy(MF.getDataLayout()));
3884 
3885   // vastart just stores the address of the VarArgsFrameIndex slot into the
3886   // memory location argument.
3887   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3888   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3889                       MachinePointerInfo(SV));
3890 }
3891 
3892 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3893                                             SelectionDAG &DAG) const {
3894   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3895   MachineFunction &MF = DAG.getMachineFunction();
3896   MachineFrameInfo &MFI = MF.getFrameInfo();
3897   MFI.setFrameAddressIsTaken(true);
3898   Register FrameReg = RI.getFrameRegister(MF);
3899   int XLenInBytes = Subtarget.getXLen() / 8;
3900 
3901   EVT VT = Op.getValueType();
3902   SDLoc DL(Op);
3903   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3904   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3905   while (Depth--) {
3906     int Offset = -(XLenInBytes * 2);
3907     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3908                               DAG.getIntPtrConstant(Offset, DL));
3909     FrameAddr =
3910         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3911   }
3912   return FrameAddr;
3913 }
3914 
3915 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3916                                              SelectionDAG &DAG) const {
3917   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3918   MachineFunction &MF = DAG.getMachineFunction();
3919   MachineFrameInfo &MFI = MF.getFrameInfo();
3920   MFI.setReturnAddressIsTaken(true);
3921   MVT XLenVT = Subtarget.getXLenVT();
3922   int XLenInBytes = Subtarget.getXLen() / 8;
3923 
3924   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3925     return SDValue();
3926 
3927   EVT VT = Op.getValueType();
3928   SDLoc DL(Op);
3929   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3930   if (Depth) {
3931     int Off = -XLenInBytes;
3932     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3933     SDValue Offset = DAG.getConstant(Off, DL, VT);
3934     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3935                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3936                        MachinePointerInfo());
3937   }
3938 
3939   // Return the value of the return address register, marking it an implicit
3940   // live-in.
3941   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3942   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3943 }
3944 
3945 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3946                                                  SelectionDAG &DAG) const {
3947   SDLoc DL(Op);
3948   SDValue Lo = Op.getOperand(0);
3949   SDValue Hi = Op.getOperand(1);
3950   SDValue Shamt = Op.getOperand(2);
3951   EVT VT = Lo.getValueType();
3952 
3953   // if Shamt-XLEN < 0: // Shamt < XLEN
3954   //   Lo = Lo << Shamt
3955   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
3956   // else:
3957   //   Lo = 0
3958   //   Hi = Lo << (Shamt-XLEN)
3959 
3960   SDValue Zero = DAG.getConstant(0, DL, VT);
3961   SDValue One = DAG.getConstant(1, DL, VT);
3962   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3963   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3964   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3965   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
3966 
3967   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3968   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3969   SDValue ShiftRightLo =
3970       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3971   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3972   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3973   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3974 
3975   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3976 
3977   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3978   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3979 
3980   SDValue Parts[2] = {Lo, Hi};
3981   return DAG.getMergeValues(Parts, DL);
3982 }
3983 
3984 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3985                                                   bool IsSRA) const {
3986   SDLoc DL(Op);
3987   SDValue Lo = Op.getOperand(0);
3988   SDValue Hi = Op.getOperand(1);
3989   SDValue Shamt = Op.getOperand(2);
3990   EVT VT = Lo.getValueType();
3991 
3992   // SRA expansion:
3993   //   if Shamt-XLEN < 0: // Shamt < XLEN
3994   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
3995   //     Hi = Hi >>s Shamt
3996   //   else:
3997   //     Lo = Hi >>s (Shamt-XLEN);
3998   //     Hi = Hi >>s (XLEN-1)
3999   //
4000   // SRL expansion:
4001   //   if Shamt-XLEN < 0: // Shamt < XLEN
4002   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4003   //     Hi = Hi >>u Shamt
4004   //   else:
4005   //     Lo = Hi >>u (Shamt-XLEN);
4006   //     Hi = 0;
4007 
4008   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4009 
4010   SDValue Zero = DAG.getConstant(0, DL, VT);
4011   SDValue One = DAG.getConstant(1, DL, VT);
4012   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4013   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4014   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4015   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4016 
4017   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4018   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4019   SDValue ShiftLeftHi =
4020       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4021   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4022   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4023   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4024   SDValue HiFalse =
4025       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4026 
4027   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4028 
4029   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4030   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4031 
4032   SDValue Parts[2] = {Lo, Hi};
4033   return DAG.getMergeValues(Parts, DL);
4034 }
4035 
4036 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4037 // legal equivalently-sized i8 type, so we can use that as a go-between.
4038 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4039                                                   SelectionDAG &DAG) const {
4040   SDLoc DL(Op);
4041   MVT VT = Op.getSimpleValueType();
4042   SDValue SplatVal = Op.getOperand(0);
4043   // All-zeros or all-ones splats are handled specially.
4044   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4045     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4046     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4047   }
4048   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4049     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4050     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4051   }
4052   MVT XLenVT = Subtarget.getXLenVT();
4053   assert(SplatVal.getValueType() == XLenVT &&
4054          "Unexpected type for i1 splat value");
4055   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4056   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4057                          DAG.getConstant(1, DL, XLenVT));
4058   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4059   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4060   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4061 }
4062 
4063 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4064 // illegal (currently only vXi64 RV32).
4065 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4066 // them to VMV_V_X_VL.
4067 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4068                                                      SelectionDAG &DAG) const {
4069   SDLoc DL(Op);
4070   MVT VecVT = Op.getSimpleValueType();
4071   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4072          "Unexpected SPLAT_VECTOR_PARTS lowering");
4073 
4074   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4075   SDValue Lo = Op.getOperand(0);
4076   SDValue Hi = Op.getOperand(1);
4077 
4078   if (VecVT.isFixedLengthVector()) {
4079     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4080     SDLoc DL(Op);
4081     SDValue Mask, VL;
4082     std::tie(Mask, VL) =
4083         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4084 
4085     SDValue Res =
4086         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4087     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4088   }
4089 
4090   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4091     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4092     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4093     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4094     // node in order to try and match RVV vector/scalar instructions.
4095     if ((LoC >> 31) == HiC)
4096       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4097                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4098   }
4099 
4100   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4101   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4102       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4103       Hi.getConstantOperandVal(1) == 31)
4104     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4105                        DAG.getRegister(RISCV::X0, MVT::i32));
4106 
4107   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4108   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4109                      DAG.getUNDEF(VecVT), Lo, Hi,
4110                      DAG.getRegister(RISCV::X0, MVT::i32));
4111 }
4112 
4113 // Custom-lower extensions from mask vectors by using a vselect either with 1
4114 // for zero/any-extension or -1 for sign-extension:
4115 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4116 // Note that any-extension is lowered identically to zero-extension.
4117 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4118                                                 int64_t ExtTrueVal) const {
4119   SDLoc DL(Op);
4120   MVT VecVT = Op.getSimpleValueType();
4121   SDValue Src = Op.getOperand(0);
4122   // Only custom-lower extensions from mask types
4123   assert(Src.getValueType().isVector() &&
4124          Src.getValueType().getVectorElementType() == MVT::i1);
4125 
4126   if (VecVT.isScalableVector()) {
4127     SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
4128     SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
4129     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4130   }
4131 
4132   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4133   MVT I1ContainerVT =
4134       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4135 
4136   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4137 
4138   SDValue Mask, VL;
4139   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4140 
4141   MVT XLenVT = Subtarget.getXLenVT();
4142   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4143   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4144 
4145   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4146                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4147   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4148                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4149   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4150                                SplatTrueVal, SplatZero, VL);
4151 
4152   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4153 }
4154 
4155 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4156     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4157   MVT ExtVT = Op.getSimpleValueType();
4158   // Only custom-lower extensions from fixed-length vector types.
4159   if (!ExtVT.isFixedLengthVector())
4160     return Op;
4161   MVT VT = Op.getOperand(0).getSimpleValueType();
4162   // Grab the canonical container type for the extended type. Infer the smaller
4163   // type from that to ensure the same number of vector elements, as we know
4164   // the LMUL will be sufficient to hold the smaller type.
4165   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4166   // Get the extended container type manually to ensure the same number of
4167   // vector elements between source and dest.
4168   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4169                                      ContainerExtVT.getVectorElementCount());
4170 
4171   SDValue Op1 =
4172       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4173 
4174   SDLoc DL(Op);
4175   SDValue Mask, VL;
4176   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4177 
4178   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4179 
4180   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4181 }
4182 
4183 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4184 // setcc operation:
4185 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4186 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op,
4187                                                       SelectionDAG &DAG) const {
4188   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4189   SDLoc DL(Op);
4190   EVT MaskVT = Op.getValueType();
4191   // Only expect to custom-lower truncations to mask types
4192   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4193          "Unexpected type for vector mask lowering");
4194   SDValue Src = Op.getOperand(0);
4195   MVT VecVT = Src.getSimpleValueType();
4196   SDValue Mask, VL;
4197   if (IsVPTrunc) {
4198     Mask = Op.getOperand(1);
4199     VL = Op.getOperand(2);
4200   }
4201   // If this is a fixed vector, we need to convert it to a scalable vector.
4202   MVT ContainerVT = VecVT;
4203 
4204   if (VecVT.isFixedLengthVector()) {
4205     ContainerVT = getContainerForFixedLengthVector(VecVT);
4206     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4207     if (IsVPTrunc) {
4208       MVT MaskContainerVT =
4209           getContainerForFixedLengthVector(Mask.getSimpleValueType());
4210       Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget);
4211     }
4212   }
4213 
4214   if (!IsVPTrunc) {
4215     std::tie(Mask, VL) =
4216         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4217   }
4218 
4219   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4220   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4221 
4222   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4223                          DAG.getUNDEF(ContainerVT), SplatOne, VL);
4224   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4225                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4226 
4227   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4228   SDValue Trunc =
4229       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4230   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4231                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4232   if (MaskVT.isFixedLengthVector())
4233     Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4234   return Trunc;
4235 }
4236 
4237 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op,
4238                                                   SelectionDAG &DAG) const {
4239   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4240   SDLoc DL(Op);
4241 
4242   MVT VT = Op.getSimpleValueType();
4243   // Only custom-lower vector truncates
4244   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4245 
4246   // Truncates to mask types are handled differently
4247   if (VT.getVectorElementType() == MVT::i1)
4248     return lowerVectorMaskTruncLike(Op, DAG);
4249 
4250   // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
4251   // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
4252   // truncate by one power of two at a time.
4253   MVT DstEltVT = VT.getVectorElementType();
4254 
4255   SDValue Src = Op.getOperand(0);
4256   MVT SrcVT = Src.getSimpleValueType();
4257   MVT SrcEltVT = SrcVT.getVectorElementType();
4258 
4259   assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) &&
4260          isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
4261          "Unexpected vector truncate lowering");
4262 
4263   MVT ContainerVT = SrcVT;
4264   SDValue Mask, VL;
4265   if (IsVPTrunc) {
4266     Mask = Op.getOperand(1);
4267     VL = Op.getOperand(2);
4268   }
4269   if (SrcVT.isFixedLengthVector()) {
4270     ContainerVT = getContainerForFixedLengthVector(SrcVT);
4271     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4272     if (IsVPTrunc) {
4273       MVT MaskVT = getMaskTypeFor(ContainerVT);
4274       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4275     }
4276   }
4277 
4278   SDValue Result = Src;
4279   if (!IsVPTrunc) {
4280     std::tie(Mask, VL) =
4281         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4282   }
4283 
4284   LLVMContext &Context = *DAG.getContext();
4285   const ElementCount Count = ContainerVT.getVectorElementCount();
4286   do {
4287     SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
4288     EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
4289     Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
4290                          Mask, VL);
4291   } while (SrcEltVT != DstEltVT);
4292 
4293   if (SrcVT.isFixedLengthVector())
4294     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4295 
4296   return Result;
4297 }
4298 
4299 SDValue
4300 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op,
4301                                                     SelectionDAG &DAG) const {
4302   bool IsVP =
4303       Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND;
4304   bool IsExtend =
4305       Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND;
4306   // RVV can only do truncate fp to types half the size as the source. We
4307   // custom-lower f64->f16 rounds via RVV's round-to-odd float
4308   // conversion instruction.
4309   SDLoc DL(Op);
4310   MVT VT = Op.getSimpleValueType();
4311 
4312   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4313 
4314   SDValue Src = Op.getOperand(0);
4315   MVT SrcVT = Src.getSimpleValueType();
4316 
4317   bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 ||
4318                                      SrcVT.getVectorElementType() != MVT::f16);
4319   bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 ||
4320                                      SrcVT.getVectorElementType() != MVT::f64);
4321 
4322   bool IsDirectConv = IsDirectExtend || IsDirectTrunc;
4323 
4324   // Prepare any fixed-length vector operands.
4325   MVT ContainerVT = VT;
4326   SDValue Mask, VL;
4327   if (IsVP) {
4328     Mask = Op.getOperand(1);
4329     VL = Op.getOperand(2);
4330   }
4331   if (VT.isFixedLengthVector()) {
4332     MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
4333     ContainerVT =
4334         SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
4335     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
4336     if (IsVP) {
4337       MVT MaskVT = getMaskTypeFor(ContainerVT);
4338       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4339     }
4340   }
4341 
4342   if (!IsVP)
4343     std::tie(Mask, VL) =
4344         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4345 
4346   unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL;
4347 
4348   if (IsDirectConv) {
4349     Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL);
4350     if (VT.isFixedLengthVector())
4351       Src = convertFromScalableVector(VT, Src, DAG, Subtarget);
4352     return Src;
4353   }
4354 
4355   unsigned InterConvOpc =
4356       IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL;
4357 
4358   MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
4359   SDValue IntermediateConv =
4360       DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL);
4361   SDValue Result =
4362       DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL);
4363   if (VT.isFixedLengthVector())
4364     return convertFromScalableVector(VT, Result, DAG, Subtarget);
4365   return Result;
4366 }
4367 
4368 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4369 // first position of a vector, and that vector is slid up to the insert index.
4370 // By limiting the active vector length to index+1 and merging with the
4371 // original vector (with an undisturbed tail policy for elements >= VL), we
4372 // achieve the desired result of leaving all elements untouched except the one
4373 // at VL-1, which is replaced with the desired value.
4374 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4375                                                     SelectionDAG &DAG) const {
4376   SDLoc DL(Op);
4377   MVT VecVT = Op.getSimpleValueType();
4378   SDValue Vec = Op.getOperand(0);
4379   SDValue Val = Op.getOperand(1);
4380   SDValue Idx = Op.getOperand(2);
4381 
4382   if (VecVT.getVectorElementType() == MVT::i1) {
4383     // FIXME: For now we just promote to an i8 vector and insert into that,
4384     // but this is probably not optimal.
4385     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4386     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4387     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4388     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4389   }
4390 
4391   MVT ContainerVT = VecVT;
4392   // If the operand is a fixed-length vector, convert to a scalable one.
4393   if (VecVT.isFixedLengthVector()) {
4394     ContainerVT = getContainerForFixedLengthVector(VecVT);
4395     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4396   }
4397 
4398   MVT XLenVT = Subtarget.getXLenVT();
4399 
4400   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4401   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4402   // Even i64-element vectors on RV32 can be lowered without scalar
4403   // legalization if the most-significant 32 bits of the value are not affected
4404   // by the sign-extension of the lower 32 bits.
4405   // TODO: We could also catch sign extensions of a 32-bit value.
4406   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4407     const auto *CVal = cast<ConstantSDNode>(Val);
4408     if (isInt<32>(CVal->getSExtValue())) {
4409       IsLegalInsert = true;
4410       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4411     }
4412   }
4413 
4414   SDValue Mask, VL;
4415   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4416 
4417   SDValue ValInVec;
4418 
4419   if (IsLegalInsert) {
4420     unsigned Opc =
4421         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4422     if (isNullConstant(Idx)) {
4423       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4424       if (!VecVT.isFixedLengthVector())
4425         return Vec;
4426       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4427     }
4428     ValInVec =
4429         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4430   } else {
4431     // On RV32, i64-element vectors must be specially handled to place the
4432     // value at element 0, by using two vslide1up instructions in sequence on
4433     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4434     // this.
4435     SDValue One = DAG.getConstant(1, DL, XLenVT);
4436     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4437     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4438     MVT I32ContainerVT =
4439         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4440     SDValue I32Mask =
4441         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4442     // Limit the active VL to two.
4443     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4444     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4445     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4446     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4447                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4448     // First slide in the hi value, then the lo in underneath it.
4449     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4450                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4451                            I32Mask, InsertI64VL);
4452     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4453                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4454                            I32Mask, InsertI64VL);
4455     // Bitcast back to the right container type.
4456     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4457   }
4458 
4459   // Now that the value is in a vector, slide it into position.
4460   SDValue InsertVL =
4461       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4462   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4463                                 ValInVec, Idx, Mask, InsertVL);
4464   if (!VecVT.isFixedLengthVector())
4465     return Slideup;
4466   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4467 }
4468 
4469 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4470 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4471 // types this is done using VMV_X_S to allow us to glean information about the
4472 // sign bits of the result.
4473 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4474                                                      SelectionDAG &DAG) const {
4475   SDLoc DL(Op);
4476   SDValue Idx = Op.getOperand(1);
4477   SDValue Vec = Op.getOperand(0);
4478   EVT EltVT = Op.getValueType();
4479   MVT VecVT = Vec.getSimpleValueType();
4480   MVT XLenVT = Subtarget.getXLenVT();
4481 
4482   if (VecVT.getVectorElementType() == MVT::i1) {
4483     if (VecVT.isFixedLengthVector()) {
4484       unsigned NumElts = VecVT.getVectorNumElements();
4485       if (NumElts >= 8) {
4486         MVT WideEltVT;
4487         unsigned WidenVecLen;
4488         SDValue ExtractElementIdx;
4489         SDValue ExtractBitIdx;
4490         unsigned MaxEEW = Subtarget.getELEN();
4491         MVT LargestEltVT = MVT::getIntegerVT(
4492             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4493         if (NumElts <= LargestEltVT.getSizeInBits()) {
4494           assert(isPowerOf2_32(NumElts) &&
4495                  "the number of elements should be power of 2");
4496           WideEltVT = MVT::getIntegerVT(NumElts);
4497           WidenVecLen = 1;
4498           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4499           ExtractBitIdx = Idx;
4500         } else {
4501           WideEltVT = LargestEltVT;
4502           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4503           // extract element index = index / element width
4504           ExtractElementIdx = DAG.getNode(
4505               ISD::SRL, DL, XLenVT, Idx,
4506               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4507           // mask bit index = index % element width
4508           ExtractBitIdx = DAG.getNode(
4509               ISD::AND, DL, XLenVT, Idx,
4510               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4511         }
4512         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4513         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4514         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4515                                          Vec, ExtractElementIdx);
4516         // Extract the bit from GPR.
4517         SDValue ShiftRight =
4518             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4519         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4520                            DAG.getConstant(1, DL, XLenVT));
4521       }
4522     }
4523     // Otherwise, promote to an i8 vector and extract from that.
4524     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4525     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4526     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4527   }
4528 
4529   // If this is a fixed vector, we need to convert it to a scalable vector.
4530   MVT ContainerVT = VecVT;
4531   if (VecVT.isFixedLengthVector()) {
4532     ContainerVT = getContainerForFixedLengthVector(VecVT);
4533     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4534   }
4535 
4536   // If the index is 0, the vector is already in the right position.
4537   if (!isNullConstant(Idx)) {
4538     // Use a VL of 1 to avoid processing more elements than we need.
4539     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4540     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
4541     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4542                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4543   }
4544 
4545   if (!EltVT.isInteger()) {
4546     // Floating-point extracts are handled in TableGen.
4547     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4548                        DAG.getConstant(0, DL, XLenVT));
4549   }
4550 
4551   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4552   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4553 }
4554 
4555 // Some RVV intrinsics may claim that they want an integer operand to be
4556 // promoted or expanded.
4557 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4558                                            const RISCVSubtarget &Subtarget) {
4559   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4560           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4561          "Unexpected opcode");
4562 
4563   if (!Subtarget.hasVInstructions())
4564     return SDValue();
4565 
4566   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4567   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4568   SDLoc DL(Op);
4569 
4570   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4571       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4572   if (!II || !II->hasScalarOperand())
4573     return SDValue();
4574 
4575   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4576   assert(SplatOp < Op.getNumOperands());
4577 
4578   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4579   SDValue &ScalarOp = Operands[SplatOp];
4580   MVT OpVT = ScalarOp.getSimpleValueType();
4581   MVT XLenVT = Subtarget.getXLenVT();
4582 
4583   // If this isn't a scalar, or its type is XLenVT we're done.
4584   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4585     return SDValue();
4586 
4587   // Simplest case is that the operand needs to be promoted to XLenVT.
4588   if (OpVT.bitsLT(XLenVT)) {
4589     // If the operand is a constant, sign extend to increase our chances
4590     // of being able to use a .vi instruction. ANY_EXTEND would become a
4591     // a zero extend and the simm5 check in isel would fail.
4592     // FIXME: Should we ignore the upper bits in isel instead?
4593     unsigned ExtOpc =
4594         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4595     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4596     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4597   }
4598 
4599   // Use the previous operand to get the vXi64 VT. The result might be a mask
4600   // VT for compares. Using the previous operand assumes that the previous
4601   // operand will never have a smaller element size than a scalar operand and
4602   // that a widening operation never uses SEW=64.
4603   // NOTE: If this fails the below assert, we can probably just find the
4604   // element count from any operand or result and use it to construct the VT.
4605   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4606   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4607 
4608   // The more complex case is when the scalar is larger than XLenVT.
4609   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4610          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4611 
4612   // If this is a sign-extended 32-bit value, we can truncate it and rely on the
4613   // instruction to sign-extend since SEW>XLEN.
4614   if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
4615     ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
4616     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4617   }
4618 
4619   switch (IntNo) {
4620   case Intrinsic::riscv_vslide1up:
4621   case Intrinsic::riscv_vslide1down:
4622   case Intrinsic::riscv_vslide1up_mask:
4623   case Intrinsic::riscv_vslide1down_mask: {
4624     // We need to special case these when the scalar is larger than XLen.
4625     unsigned NumOps = Op.getNumOperands();
4626     bool IsMasked = NumOps == 7;
4627 
4628     // Convert the vector source to the equivalent nxvXi32 vector.
4629     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4630     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4631 
4632     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4633                                    DAG.getConstant(0, DL, XLenVT));
4634     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4635                                    DAG.getConstant(1, DL, XLenVT));
4636 
4637     // Double the VL since we halved SEW.
4638     SDValue AVL = getVLOperand(Op);
4639     SDValue I32VL;
4640 
4641     // Optimize for constant AVL
4642     if (isa<ConstantSDNode>(AVL)) {
4643       unsigned EltSize = VT.getScalarSizeInBits();
4644       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4645 
4646       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4647       unsigned MaxVLMAX =
4648           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4649 
4650       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4651       unsigned MinVLMAX =
4652           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4653 
4654       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4655       if (AVLInt <= MinVLMAX) {
4656         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4657       } else if (AVLInt >= 2 * MaxVLMAX) {
4658         // Just set vl to VLMAX in this situation
4659         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4660         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4661         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4662         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4663         SDValue SETVLMAX = DAG.getTargetConstant(
4664             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4665         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4666                             LMUL);
4667       } else {
4668         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4669         // is related to the hardware implementation.
4670         // So let the following code handle
4671       }
4672     }
4673     if (!I32VL) {
4674       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4675       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4676       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4677       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4678       SDValue SETVL =
4679           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4680       // Using vsetvli instruction to get actually used length which related to
4681       // the hardware implementation
4682       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4683                                SEW, LMUL);
4684       I32VL =
4685           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4686     }
4687 
4688     SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG);
4689 
4690     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4691     // instructions.
4692     SDValue Passthru;
4693     if (IsMasked)
4694       Passthru = DAG.getUNDEF(I32VT);
4695     else
4696       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4697 
4698     if (IntNo == Intrinsic::riscv_vslide1up ||
4699         IntNo == Intrinsic::riscv_vslide1up_mask) {
4700       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4701                         ScalarHi, I32Mask, I32VL);
4702       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4703                         ScalarLo, I32Mask, I32VL);
4704     } else {
4705       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4706                         ScalarLo, I32Mask, I32VL);
4707       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4708                         ScalarHi, I32Mask, I32VL);
4709     }
4710 
4711     // Convert back to nxvXi64.
4712     Vec = DAG.getBitcast(VT, Vec);
4713 
4714     if (!IsMasked)
4715       return Vec;
4716     // Apply mask after the operation.
4717     SDValue Mask = Operands[NumOps - 3];
4718     SDValue MaskedOff = Operands[1];
4719     // Assume Policy operand is the last operand.
4720     uint64_t Policy =
4721         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4722     // We don't need to select maskedoff if it's undef.
4723     if (MaskedOff.isUndef())
4724       return Vec;
4725     // TAMU
4726     if (Policy == RISCVII::TAIL_AGNOSTIC)
4727       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4728                          AVL);
4729     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4730     // It's fine because vmerge does not care mask policy.
4731     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4732                        AVL);
4733   }
4734   }
4735 
4736   // We need to convert the scalar to a splat vector.
4737   SDValue VL = getVLOperand(Op);
4738   assert(VL.getValueType() == XLenVT);
4739   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4740   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4741 }
4742 
4743 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4744                                                      SelectionDAG &DAG) const {
4745   unsigned IntNo = Op.getConstantOperandVal(0);
4746   SDLoc DL(Op);
4747   MVT XLenVT = Subtarget.getXLenVT();
4748 
4749   switch (IntNo) {
4750   default:
4751     break; // Don't custom lower most intrinsics.
4752   case Intrinsic::thread_pointer: {
4753     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4754     return DAG.getRegister(RISCV::X4, PtrVT);
4755   }
4756   case Intrinsic::riscv_orc_b:
4757   case Intrinsic::riscv_brev8: {
4758     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4759     unsigned Opc =
4760         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4761     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4762                        DAG.getConstant(7, DL, XLenVT));
4763   }
4764   case Intrinsic::riscv_grev:
4765   case Intrinsic::riscv_gorc: {
4766     unsigned Opc =
4767         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4768     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4769   }
4770   case Intrinsic::riscv_zip:
4771   case Intrinsic::riscv_unzip: {
4772     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4773     // For i32 the immediate is 15. For i64 the immediate is 31.
4774     unsigned Opc =
4775         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4776     unsigned BitWidth = Op.getValueSizeInBits();
4777     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4778     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4779                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4780   }
4781   case Intrinsic::riscv_shfl:
4782   case Intrinsic::riscv_unshfl: {
4783     unsigned Opc =
4784         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4785     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4786   }
4787   case Intrinsic::riscv_bcompress:
4788   case Intrinsic::riscv_bdecompress: {
4789     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4790                                                        : RISCVISD::BDECOMPRESS;
4791     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4792   }
4793   case Intrinsic::riscv_bfp:
4794     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4795                        Op.getOperand(2));
4796   case Intrinsic::riscv_fsl:
4797     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4798                        Op.getOperand(2), Op.getOperand(3));
4799   case Intrinsic::riscv_fsr:
4800     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4801                        Op.getOperand(2), Op.getOperand(3));
4802   case Intrinsic::riscv_vmv_x_s:
4803     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4804     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4805                        Op.getOperand(1));
4806   case Intrinsic::riscv_vmv_v_x:
4807     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4808                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4809                             Subtarget);
4810   case Intrinsic::riscv_vfmv_v_f:
4811     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4812                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4813   case Intrinsic::riscv_vmv_s_x: {
4814     SDValue Scalar = Op.getOperand(2);
4815 
4816     if (Scalar.getValueType().bitsLE(XLenVT)) {
4817       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4818       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4819                          Op.getOperand(1), Scalar, Op.getOperand(3));
4820     }
4821 
4822     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4823 
4824     // This is an i64 value that lives in two scalar registers. We have to
4825     // insert this in a convoluted way. First we build vXi64 splat containing
4826     // the two values that we assemble using some bit math. Next we'll use
4827     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4828     // to merge element 0 from our splat into the source vector.
4829     // FIXME: This is probably not the best way to do this, but it is
4830     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4831     // point.
4832     //   sw lo, (a0)
4833     //   sw hi, 4(a0)
4834     //   vlse vX, (a0)
4835     //
4836     //   vid.v      vVid
4837     //   vmseq.vx   mMask, vVid, 0
4838     //   vmerge.vvm vDest, vSrc, vVal, mMask
4839     MVT VT = Op.getSimpleValueType();
4840     SDValue Vec = Op.getOperand(1);
4841     SDValue VL = getVLOperand(Op);
4842 
4843     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4844     if (Op.getOperand(1).isUndef())
4845       return SplattedVal;
4846     SDValue SplattedIdx =
4847         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4848                     DAG.getConstant(0, DL, MVT::i32), VL);
4849 
4850     MVT MaskVT = getMaskTypeFor(VT);
4851     SDValue Mask = getAllOnesMask(VT, VL, DL, DAG);
4852     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4853     SDValue SelectCond =
4854         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4855                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4856     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4857                        Vec, VL);
4858   }
4859   }
4860 
4861   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4862 }
4863 
4864 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4865                                                     SelectionDAG &DAG) const {
4866   unsigned IntNo = Op.getConstantOperandVal(1);
4867   switch (IntNo) {
4868   default:
4869     break;
4870   case Intrinsic::riscv_masked_strided_load: {
4871     SDLoc DL(Op);
4872     MVT XLenVT = Subtarget.getXLenVT();
4873 
4874     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4875     // the selection of the masked intrinsics doesn't do this for us.
4876     SDValue Mask = Op.getOperand(5);
4877     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4878 
4879     MVT VT = Op->getSimpleValueType(0);
4880     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4881 
4882     SDValue PassThru = Op.getOperand(2);
4883     if (!IsUnmasked) {
4884       MVT MaskVT = getMaskTypeFor(ContainerVT);
4885       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4886       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4887     }
4888 
4889     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4890 
4891     SDValue IntID = DAG.getTargetConstant(
4892         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4893         XLenVT);
4894 
4895     auto *Load = cast<MemIntrinsicSDNode>(Op);
4896     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4897     if (IsUnmasked)
4898       Ops.push_back(DAG.getUNDEF(ContainerVT));
4899     else
4900       Ops.push_back(PassThru);
4901     Ops.push_back(Op.getOperand(3)); // Ptr
4902     Ops.push_back(Op.getOperand(4)); // Stride
4903     if (!IsUnmasked)
4904       Ops.push_back(Mask);
4905     Ops.push_back(VL);
4906     if (!IsUnmasked) {
4907       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4908       Ops.push_back(Policy);
4909     }
4910 
4911     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4912     SDValue Result =
4913         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4914                                 Load->getMemoryVT(), Load->getMemOperand());
4915     SDValue Chain = Result.getValue(1);
4916     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4917     return DAG.getMergeValues({Result, Chain}, DL);
4918   }
4919   case Intrinsic::riscv_seg2_load:
4920   case Intrinsic::riscv_seg3_load:
4921   case Intrinsic::riscv_seg4_load:
4922   case Intrinsic::riscv_seg5_load:
4923   case Intrinsic::riscv_seg6_load:
4924   case Intrinsic::riscv_seg7_load:
4925   case Intrinsic::riscv_seg8_load: {
4926     SDLoc DL(Op);
4927     static const Intrinsic::ID VlsegInts[7] = {
4928         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
4929         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
4930         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
4931         Intrinsic::riscv_vlseg8};
4932     unsigned NF = Op->getNumValues() - 1;
4933     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
4934     MVT XLenVT = Subtarget.getXLenVT();
4935     MVT VT = Op->getSimpleValueType(0);
4936     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4937 
4938     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4939     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
4940     auto *Load = cast<MemIntrinsicSDNode>(Op);
4941     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
4942     ContainerVTs.push_back(MVT::Other);
4943     SDVTList VTs = DAG.getVTList(ContainerVTs);
4944     SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID};
4945     Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT));
4946     Ops.push_back(Op.getOperand(2));
4947     Ops.push_back(VL);
4948     SDValue Result =
4949         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4950                                 Load->getMemoryVT(), Load->getMemOperand());
4951     SmallVector<SDValue, 9> Results;
4952     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
4953       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
4954                                                   DAG, Subtarget));
4955     Results.push_back(Result.getValue(NF));
4956     return DAG.getMergeValues(Results, DL);
4957   }
4958   }
4959 
4960   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4961 }
4962 
4963 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4964                                                  SelectionDAG &DAG) const {
4965   unsigned IntNo = Op.getConstantOperandVal(1);
4966   switch (IntNo) {
4967   default:
4968     break;
4969   case Intrinsic::riscv_masked_strided_store: {
4970     SDLoc DL(Op);
4971     MVT XLenVT = Subtarget.getXLenVT();
4972 
4973     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4974     // the selection of the masked intrinsics doesn't do this for us.
4975     SDValue Mask = Op.getOperand(5);
4976     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4977 
4978     SDValue Val = Op.getOperand(2);
4979     MVT VT = Val.getSimpleValueType();
4980     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4981 
4982     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4983     if (!IsUnmasked) {
4984       MVT MaskVT = getMaskTypeFor(ContainerVT);
4985       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4986     }
4987 
4988     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4989 
4990     SDValue IntID = DAG.getTargetConstant(
4991         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4992         XLenVT);
4993 
4994     auto *Store = cast<MemIntrinsicSDNode>(Op);
4995     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4996     Ops.push_back(Val);
4997     Ops.push_back(Op.getOperand(3)); // Ptr
4998     Ops.push_back(Op.getOperand(4)); // Stride
4999     if (!IsUnmasked)
5000       Ops.push_back(Mask);
5001     Ops.push_back(VL);
5002 
5003     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
5004                                    Ops, Store->getMemoryVT(),
5005                                    Store->getMemOperand());
5006   }
5007   }
5008 
5009   return SDValue();
5010 }
5011 
5012 static MVT getLMUL1VT(MVT VT) {
5013   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
5014          "Unexpected vector MVT");
5015   return MVT::getScalableVectorVT(
5016       VT.getVectorElementType(),
5017       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
5018 }
5019 
5020 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
5021   switch (ISDOpcode) {
5022   default:
5023     llvm_unreachable("Unhandled reduction");
5024   case ISD::VECREDUCE_ADD:
5025     return RISCVISD::VECREDUCE_ADD_VL;
5026   case ISD::VECREDUCE_UMAX:
5027     return RISCVISD::VECREDUCE_UMAX_VL;
5028   case ISD::VECREDUCE_SMAX:
5029     return RISCVISD::VECREDUCE_SMAX_VL;
5030   case ISD::VECREDUCE_UMIN:
5031     return RISCVISD::VECREDUCE_UMIN_VL;
5032   case ISD::VECREDUCE_SMIN:
5033     return RISCVISD::VECREDUCE_SMIN_VL;
5034   case ISD::VECREDUCE_AND:
5035     return RISCVISD::VECREDUCE_AND_VL;
5036   case ISD::VECREDUCE_OR:
5037     return RISCVISD::VECREDUCE_OR_VL;
5038   case ISD::VECREDUCE_XOR:
5039     return RISCVISD::VECREDUCE_XOR_VL;
5040   }
5041 }
5042 
5043 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
5044                                                          SelectionDAG &DAG,
5045                                                          bool IsVP) const {
5046   SDLoc DL(Op);
5047   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5048   MVT VecVT = Vec.getSimpleValueType();
5049   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5050           Op.getOpcode() == ISD::VECREDUCE_OR ||
5051           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5052           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5053           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5054           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5055          "Unexpected reduction lowering");
5056 
5057   MVT XLenVT = Subtarget.getXLenVT();
5058   assert(Op.getValueType() == XLenVT &&
5059          "Expected reduction output to be legalized to XLenVT");
5060 
5061   MVT ContainerVT = VecVT;
5062   if (VecVT.isFixedLengthVector()) {
5063     ContainerVT = getContainerForFixedLengthVector(VecVT);
5064     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5065   }
5066 
5067   SDValue Mask, VL;
5068   if (IsVP) {
5069     Mask = Op.getOperand(2);
5070     VL = Op.getOperand(3);
5071   } else {
5072     std::tie(Mask, VL) =
5073         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5074   }
5075 
5076   unsigned BaseOpc;
5077   ISD::CondCode CC;
5078   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5079 
5080   switch (Op.getOpcode()) {
5081   default:
5082     llvm_unreachable("Unhandled reduction");
5083   case ISD::VECREDUCE_AND:
5084   case ISD::VP_REDUCE_AND: {
5085     // vcpop ~x == 0
5086     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5087     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5088     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5089     CC = ISD::SETEQ;
5090     BaseOpc = ISD::AND;
5091     break;
5092   }
5093   case ISD::VECREDUCE_OR:
5094   case ISD::VP_REDUCE_OR:
5095     // vcpop x != 0
5096     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5097     CC = ISD::SETNE;
5098     BaseOpc = ISD::OR;
5099     break;
5100   case ISD::VECREDUCE_XOR:
5101   case ISD::VP_REDUCE_XOR: {
5102     // ((vcpop x) & 1) != 0
5103     SDValue One = DAG.getConstant(1, DL, XLenVT);
5104     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5105     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5106     CC = ISD::SETNE;
5107     BaseOpc = ISD::XOR;
5108     break;
5109   }
5110   }
5111 
5112   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5113 
5114   if (!IsVP)
5115     return SetCC;
5116 
5117   // Now include the start value in the operation.
5118   // Note that we must return the start value when no elements are operated
5119   // upon. The vcpop instructions we've emitted in each case above will return
5120   // 0 for an inactive vector, and so we've already received the neutral value:
5121   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5122   // can simply include the start value.
5123   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5124 }
5125 
5126 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5127                                             SelectionDAG &DAG) const {
5128   SDLoc DL(Op);
5129   SDValue Vec = Op.getOperand(0);
5130   EVT VecEVT = Vec.getValueType();
5131 
5132   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5133 
5134   // Due to ordering in legalize types we may have a vector type that needs to
5135   // be split. Do that manually so we can get down to a legal type.
5136   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5137          TargetLowering::TypeSplitVector) {
5138     SDValue Lo, Hi;
5139     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5140     VecEVT = Lo.getValueType();
5141     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5142   }
5143 
5144   // TODO: The type may need to be widened rather than split. Or widened before
5145   // it can be split.
5146   if (!isTypeLegal(VecEVT))
5147     return SDValue();
5148 
5149   MVT VecVT = VecEVT.getSimpleVT();
5150   MVT VecEltVT = VecVT.getVectorElementType();
5151   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5152 
5153   MVT ContainerVT = VecVT;
5154   if (VecVT.isFixedLengthVector()) {
5155     ContainerVT = getContainerForFixedLengthVector(VecVT);
5156     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5157   }
5158 
5159   MVT M1VT = getLMUL1VT(ContainerVT);
5160   MVT XLenVT = Subtarget.getXLenVT();
5161 
5162   SDValue Mask, VL;
5163   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5164 
5165   SDValue NeutralElem =
5166       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5167   SDValue IdentitySplat =
5168       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5169                        M1VT, DL, DAG, Subtarget);
5170   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5171                                   IdentitySplat, Mask, VL);
5172   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5173                              DAG.getConstant(0, DL, XLenVT));
5174   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5175 }
5176 
5177 // Given a reduction op, this function returns the matching reduction opcode,
5178 // the vector SDValue and the scalar SDValue required to lower this to a
5179 // RISCVISD node.
5180 static std::tuple<unsigned, SDValue, SDValue>
5181 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5182   SDLoc DL(Op);
5183   auto Flags = Op->getFlags();
5184   unsigned Opcode = Op.getOpcode();
5185   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5186   switch (Opcode) {
5187   default:
5188     llvm_unreachable("Unhandled reduction");
5189   case ISD::VECREDUCE_FADD: {
5190     // Use positive zero if we can. It is cheaper to materialize.
5191     SDValue Zero =
5192         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5193     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5194   }
5195   case ISD::VECREDUCE_SEQ_FADD:
5196     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5197                            Op.getOperand(0));
5198   case ISD::VECREDUCE_FMIN:
5199     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5200                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5201   case ISD::VECREDUCE_FMAX:
5202     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5203                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5204   }
5205 }
5206 
5207 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5208                                               SelectionDAG &DAG) const {
5209   SDLoc DL(Op);
5210   MVT VecEltVT = Op.getSimpleValueType();
5211 
5212   unsigned RVVOpcode;
5213   SDValue VectorVal, ScalarVal;
5214   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5215       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5216   MVT VecVT = VectorVal.getSimpleValueType();
5217 
5218   MVT ContainerVT = VecVT;
5219   if (VecVT.isFixedLengthVector()) {
5220     ContainerVT = getContainerForFixedLengthVector(VecVT);
5221     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5222   }
5223 
5224   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5225   MVT XLenVT = Subtarget.getXLenVT();
5226 
5227   SDValue Mask, VL;
5228   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5229 
5230   SDValue ScalarSplat =
5231       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5232                        M1VT, DL, DAG, Subtarget);
5233   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5234                                   VectorVal, ScalarSplat, Mask, VL);
5235   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5236                      DAG.getConstant(0, DL, XLenVT));
5237 }
5238 
5239 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5240   switch (ISDOpcode) {
5241   default:
5242     llvm_unreachable("Unhandled reduction");
5243   case ISD::VP_REDUCE_ADD:
5244     return RISCVISD::VECREDUCE_ADD_VL;
5245   case ISD::VP_REDUCE_UMAX:
5246     return RISCVISD::VECREDUCE_UMAX_VL;
5247   case ISD::VP_REDUCE_SMAX:
5248     return RISCVISD::VECREDUCE_SMAX_VL;
5249   case ISD::VP_REDUCE_UMIN:
5250     return RISCVISD::VECREDUCE_UMIN_VL;
5251   case ISD::VP_REDUCE_SMIN:
5252     return RISCVISD::VECREDUCE_SMIN_VL;
5253   case ISD::VP_REDUCE_AND:
5254     return RISCVISD::VECREDUCE_AND_VL;
5255   case ISD::VP_REDUCE_OR:
5256     return RISCVISD::VECREDUCE_OR_VL;
5257   case ISD::VP_REDUCE_XOR:
5258     return RISCVISD::VECREDUCE_XOR_VL;
5259   case ISD::VP_REDUCE_FADD:
5260     return RISCVISD::VECREDUCE_FADD_VL;
5261   case ISD::VP_REDUCE_SEQ_FADD:
5262     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5263   case ISD::VP_REDUCE_FMAX:
5264     return RISCVISD::VECREDUCE_FMAX_VL;
5265   case ISD::VP_REDUCE_FMIN:
5266     return RISCVISD::VECREDUCE_FMIN_VL;
5267   }
5268 }
5269 
5270 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5271                                            SelectionDAG &DAG) const {
5272   SDLoc DL(Op);
5273   SDValue Vec = Op.getOperand(1);
5274   EVT VecEVT = Vec.getValueType();
5275 
5276   // TODO: The type may need to be widened rather than split. Or widened before
5277   // it can be split.
5278   if (!isTypeLegal(VecEVT))
5279     return SDValue();
5280 
5281   MVT VecVT = VecEVT.getSimpleVT();
5282   MVT VecEltVT = VecVT.getVectorElementType();
5283   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5284 
5285   MVT ContainerVT = VecVT;
5286   if (VecVT.isFixedLengthVector()) {
5287     ContainerVT = getContainerForFixedLengthVector(VecVT);
5288     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5289   }
5290 
5291   SDValue VL = Op.getOperand(3);
5292   SDValue Mask = Op.getOperand(2);
5293 
5294   MVT M1VT = getLMUL1VT(ContainerVT);
5295   MVT XLenVT = Subtarget.getXLenVT();
5296   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5297 
5298   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5299                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5300                                         DL, DAG, Subtarget);
5301   SDValue Reduction =
5302       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5303   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5304                              DAG.getConstant(0, DL, XLenVT));
5305   if (!VecVT.isInteger())
5306     return Elt0;
5307   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5308 }
5309 
5310 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5311                                                    SelectionDAG &DAG) const {
5312   SDValue Vec = Op.getOperand(0);
5313   SDValue SubVec = Op.getOperand(1);
5314   MVT VecVT = Vec.getSimpleValueType();
5315   MVT SubVecVT = SubVec.getSimpleValueType();
5316 
5317   SDLoc DL(Op);
5318   MVT XLenVT = Subtarget.getXLenVT();
5319   unsigned OrigIdx = Op.getConstantOperandVal(2);
5320   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5321 
5322   // We don't have the ability to slide mask vectors up indexed by their i1
5323   // elements; the smallest we can do is i8. Often we are able to bitcast to
5324   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5325   // into a scalable one, we might not necessarily have enough scalable
5326   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5327   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5328       (OrigIdx != 0 || !Vec.isUndef())) {
5329     if (VecVT.getVectorMinNumElements() >= 8 &&
5330         SubVecVT.getVectorMinNumElements() >= 8) {
5331       assert(OrigIdx % 8 == 0 && "Invalid index");
5332       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5333              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5334              "Unexpected mask vector lowering");
5335       OrigIdx /= 8;
5336       SubVecVT =
5337           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5338                            SubVecVT.isScalableVector());
5339       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5340                                VecVT.isScalableVector());
5341       Vec = DAG.getBitcast(VecVT, Vec);
5342       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5343     } else {
5344       // We can't slide this mask vector up indexed by its i1 elements.
5345       // This poses a problem when we wish to insert a scalable vector which
5346       // can't be re-expressed as a larger type. Just choose the slow path and
5347       // extend to a larger type, then truncate back down.
5348       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5349       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5350       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5351       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5352       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5353                         Op.getOperand(2));
5354       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5355       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5356     }
5357   }
5358 
5359   // If the subvector vector is a fixed-length type, we cannot use subregister
5360   // manipulation to simplify the codegen; we don't know which register of a
5361   // LMUL group contains the specific subvector as we only know the minimum
5362   // register size. Therefore we must slide the vector group up the full
5363   // amount.
5364   if (SubVecVT.isFixedLengthVector()) {
5365     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5366       return Op;
5367     MVT ContainerVT = VecVT;
5368     if (VecVT.isFixedLengthVector()) {
5369       ContainerVT = getContainerForFixedLengthVector(VecVT);
5370       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5371     }
5372     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5373                          DAG.getUNDEF(ContainerVT), SubVec,
5374                          DAG.getConstant(0, DL, XLenVT));
5375     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5376       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5377       return DAG.getBitcast(Op.getValueType(), SubVec);
5378     }
5379     SDValue Mask =
5380         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5381     // Set the vector length to only the number of elements we care about. Note
5382     // that for slideup this includes the offset.
5383     SDValue VL =
5384         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5385     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5386     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5387                                   SubVec, SlideupAmt, Mask, VL);
5388     if (VecVT.isFixedLengthVector())
5389       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5390     return DAG.getBitcast(Op.getValueType(), Slideup);
5391   }
5392 
5393   unsigned SubRegIdx, RemIdx;
5394   std::tie(SubRegIdx, RemIdx) =
5395       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5396           VecVT, SubVecVT, OrigIdx, TRI);
5397 
5398   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5399   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5400                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5401                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5402 
5403   // 1. If the Idx has been completely eliminated and this subvector's size is
5404   // a vector register or a multiple thereof, or the surrounding elements are
5405   // undef, then this is a subvector insert which naturally aligns to a vector
5406   // register. These can easily be handled using subregister manipulation.
5407   // 2. If the subvector is smaller than a vector register, then the insertion
5408   // must preserve the undisturbed elements of the register. We do this by
5409   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5410   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5411   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5412   // LMUL=1 type back into the larger vector (resolving to another subregister
5413   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5414   // to avoid allocating a large register group to hold our subvector.
5415   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5416     return Op;
5417 
5418   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5419   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5420   // (in our case undisturbed). This means we can set up a subvector insertion
5421   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5422   // size of the subvector.
5423   MVT InterSubVT = VecVT;
5424   SDValue AlignedExtract = Vec;
5425   unsigned AlignedIdx = OrigIdx - RemIdx;
5426   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5427     InterSubVT = getLMUL1VT(VecVT);
5428     // Extract a subvector equal to the nearest full vector register type. This
5429     // should resolve to a EXTRACT_SUBREG instruction.
5430     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5431                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5432   }
5433 
5434   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5435   // For scalable vectors this must be further multiplied by vscale.
5436   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5437 
5438   SDValue Mask, VL;
5439   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5440 
5441   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5442   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5443   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5444   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5445 
5446   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5447                        DAG.getUNDEF(InterSubVT), SubVec,
5448                        DAG.getConstant(0, DL, XLenVT));
5449 
5450   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5451                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5452 
5453   // If required, insert this subvector back into the correct vector register.
5454   // This should resolve to an INSERT_SUBREG instruction.
5455   if (VecVT.bitsGT(InterSubVT))
5456     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5457                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5458 
5459   // We might have bitcast from a mask type: cast back to the original type if
5460   // required.
5461   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5462 }
5463 
5464 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5465                                                     SelectionDAG &DAG) const {
5466   SDValue Vec = Op.getOperand(0);
5467   MVT SubVecVT = Op.getSimpleValueType();
5468   MVT VecVT = Vec.getSimpleValueType();
5469 
5470   SDLoc DL(Op);
5471   MVT XLenVT = Subtarget.getXLenVT();
5472   unsigned OrigIdx = Op.getConstantOperandVal(1);
5473   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5474 
5475   // We don't have the ability to slide mask vectors down indexed by their i1
5476   // elements; the smallest we can do is i8. Often we are able to bitcast to
5477   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5478   // from a scalable one, we might not necessarily have enough scalable
5479   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5480   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5481     if (VecVT.getVectorMinNumElements() >= 8 &&
5482         SubVecVT.getVectorMinNumElements() >= 8) {
5483       assert(OrigIdx % 8 == 0 && "Invalid index");
5484       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5485              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5486              "Unexpected mask vector lowering");
5487       OrigIdx /= 8;
5488       SubVecVT =
5489           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5490                            SubVecVT.isScalableVector());
5491       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5492                                VecVT.isScalableVector());
5493       Vec = DAG.getBitcast(VecVT, Vec);
5494     } else {
5495       // We can't slide this mask vector down, indexed by its i1 elements.
5496       // This poses a problem when we wish to extract a scalable vector which
5497       // can't be re-expressed as a larger type. Just choose the slow path and
5498       // extend to a larger type, then truncate back down.
5499       // TODO: We could probably improve this when extracting certain fixed
5500       // from fixed, where we can extract as i8 and shift the correct element
5501       // right to reach the desired subvector?
5502       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5503       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5504       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5505       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5506                         Op.getOperand(1));
5507       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5508       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5509     }
5510   }
5511 
5512   // If the subvector vector is a fixed-length type, we cannot use subregister
5513   // manipulation to simplify the codegen; we don't know which register of a
5514   // LMUL group contains the specific subvector as we only know the minimum
5515   // register size. Therefore we must slide the vector group down the full
5516   // amount.
5517   if (SubVecVT.isFixedLengthVector()) {
5518     // With an index of 0 this is a cast-like subvector, which can be performed
5519     // with subregister operations.
5520     if (OrigIdx == 0)
5521       return Op;
5522     MVT ContainerVT = VecVT;
5523     if (VecVT.isFixedLengthVector()) {
5524       ContainerVT = getContainerForFixedLengthVector(VecVT);
5525       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5526     }
5527     SDValue Mask =
5528         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5529     // Set the vector length to only the number of elements we care about. This
5530     // avoids sliding down elements we're going to discard straight away.
5531     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5532     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5533     SDValue Slidedown =
5534         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5535                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5536     // Now we can use a cast-like subvector extract to get the result.
5537     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5538                             DAG.getConstant(0, DL, XLenVT));
5539     return DAG.getBitcast(Op.getValueType(), Slidedown);
5540   }
5541 
5542   unsigned SubRegIdx, RemIdx;
5543   std::tie(SubRegIdx, RemIdx) =
5544       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5545           VecVT, SubVecVT, OrigIdx, TRI);
5546 
5547   // If the Idx has been completely eliminated then this is a subvector extract
5548   // which naturally aligns to a vector register. These can easily be handled
5549   // using subregister manipulation.
5550   if (RemIdx == 0)
5551     return Op;
5552 
5553   // Else we must shift our vector register directly to extract the subvector.
5554   // Do this using VSLIDEDOWN.
5555 
5556   // If the vector type is an LMUL-group type, extract a subvector equal to the
5557   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5558   // instruction.
5559   MVT InterSubVT = VecVT;
5560   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5561     InterSubVT = getLMUL1VT(VecVT);
5562     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5563                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5564   }
5565 
5566   // Slide this vector register down by the desired number of elements in order
5567   // to place the desired subvector starting at element 0.
5568   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5569   // For scalable vectors this must be further multiplied by vscale.
5570   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5571 
5572   SDValue Mask, VL;
5573   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5574   SDValue Slidedown =
5575       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5576                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5577 
5578   // Now the vector is in the right position, extract our final subvector. This
5579   // should resolve to a COPY.
5580   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5581                           DAG.getConstant(0, DL, XLenVT));
5582 
5583   // We might have bitcast from a mask type: cast back to the original type if
5584   // required.
5585   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5586 }
5587 
5588 // Lower step_vector to the vid instruction. Any non-identity step value must
5589 // be accounted for my manual expansion.
5590 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5591                                               SelectionDAG &DAG) const {
5592   SDLoc DL(Op);
5593   MVT VT = Op.getSimpleValueType();
5594   MVT XLenVT = Subtarget.getXLenVT();
5595   SDValue Mask, VL;
5596   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5597   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5598   uint64_t StepValImm = Op.getConstantOperandVal(0);
5599   if (StepValImm != 1) {
5600     if (isPowerOf2_64(StepValImm)) {
5601       SDValue StepVal =
5602           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5603                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5604       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5605     } else {
5606       SDValue StepVal = lowerScalarSplat(
5607           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5608           VL, VT, DL, DAG, Subtarget);
5609       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5610     }
5611   }
5612   return StepVec;
5613 }
5614 
5615 // Implement vector_reverse using vrgather.vv with indices determined by
5616 // subtracting the id of each element from (VLMAX-1). This will convert
5617 // the indices like so:
5618 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5619 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5620 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5621                                                  SelectionDAG &DAG) const {
5622   SDLoc DL(Op);
5623   MVT VecVT = Op.getSimpleValueType();
5624   unsigned EltSize = VecVT.getScalarSizeInBits();
5625   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5626 
5627   unsigned MaxVLMAX = 0;
5628   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5629   if (VectorBitsMax != 0)
5630     MaxVLMAX =
5631         RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5632 
5633   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5634   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5635 
5636   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5637   // to use vrgatherei16.vv.
5638   // TODO: It's also possible to use vrgatherei16.vv for other types to
5639   // decrease register width for the index calculation.
5640   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5641     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5642     // Reverse each half, then reassemble them in reverse order.
5643     // NOTE: It's also possible that after splitting that VLMAX no longer
5644     // requires vrgatherei16.vv.
5645     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5646       SDValue Lo, Hi;
5647       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5648       EVT LoVT, HiVT;
5649       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5650       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5651       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5652       // Reassemble the low and high pieces reversed.
5653       // FIXME: This is a CONCAT_VECTORS.
5654       SDValue Res =
5655           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5656                       DAG.getIntPtrConstant(0, DL));
5657       return DAG.getNode(
5658           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5659           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5660     }
5661 
5662     // Just promote the int type to i16 which will double the LMUL.
5663     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5664     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5665   }
5666 
5667   MVT XLenVT = Subtarget.getXLenVT();
5668   SDValue Mask, VL;
5669   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5670 
5671   // Calculate VLMAX-1 for the desired SEW.
5672   unsigned MinElts = VecVT.getVectorMinNumElements();
5673   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5674                               DAG.getConstant(MinElts, DL, XLenVT));
5675   SDValue VLMinus1 =
5676       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5677 
5678   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5679   bool IsRV32E64 =
5680       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5681   SDValue SplatVL;
5682   if (!IsRV32E64)
5683     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5684   else
5685     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5686                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5687 
5688   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5689   SDValue Indices =
5690       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5691 
5692   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask,
5693                      DAG.getUNDEF(VecVT), VL);
5694 }
5695 
5696 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5697                                                 SelectionDAG &DAG) const {
5698   SDLoc DL(Op);
5699   SDValue V1 = Op.getOperand(0);
5700   SDValue V2 = Op.getOperand(1);
5701   MVT XLenVT = Subtarget.getXLenVT();
5702   MVT VecVT = Op.getSimpleValueType();
5703 
5704   unsigned MinElts = VecVT.getVectorMinNumElements();
5705   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5706                               DAG.getConstant(MinElts, DL, XLenVT));
5707 
5708   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5709   SDValue DownOffset, UpOffset;
5710   if (ImmValue >= 0) {
5711     // The operand is a TargetConstant, we need to rebuild it as a regular
5712     // constant.
5713     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5714     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5715   } else {
5716     // The operand is a TargetConstant, we need to rebuild it as a regular
5717     // constant rather than negating the original operand.
5718     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5719     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5720   }
5721 
5722   SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG);
5723 
5724   SDValue SlideDown =
5725       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5726                   DownOffset, TrueMask, UpOffset);
5727   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5728                      TrueMask,
5729                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5730 }
5731 
5732 SDValue
5733 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5734                                                      SelectionDAG &DAG) const {
5735   SDLoc DL(Op);
5736   auto *Load = cast<LoadSDNode>(Op);
5737 
5738   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5739                                         Load->getMemoryVT(),
5740                                         *Load->getMemOperand()) &&
5741          "Expecting a correctly-aligned load");
5742 
5743   MVT VT = Op.getSimpleValueType();
5744   MVT XLenVT = Subtarget.getXLenVT();
5745   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5746 
5747   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5748 
5749   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5750   SDValue IntID = DAG.getTargetConstant(
5751       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5752   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5753   if (!IsMaskOp)
5754     Ops.push_back(DAG.getUNDEF(ContainerVT));
5755   Ops.push_back(Load->getBasePtr());
5756   Ops.push_back(VL);
5757   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5758   SDValue NewLoad =
5759       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5760                               Load->getMemoryVT(), Load->getMemOperand());
5761 
5762   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5763   return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL);
5764 }
5765 
5766 SDValue
5767 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5768                                                       SelectionDAG &DAG) const {
5769   SDLoc DL(Op);
5770   auto *Store = cast<StoreSDNode>(Op);
5771 
5772   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5773                                         Store->getMemoryVT(),
5774                                         *Store->getMemOperand()) &&
5775          "Expecting a correctly-aligned store");
5776 
5777   SDValue StoreVal = Store->getValue();
5778   MVT VT = StoreVal.getSimpleValueType();
5779   MVT XLenVT = Subtarget.getXLenVT();
5780 
5781   // If the size less than a byte, we need to pad with zeros to make a byte.
5782   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5783     VT = MVT::v8i1;
5784     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5785                            DAG.getConstant(0, DL, VT), StoreVal,
5786                            DAG.getIntPtrConstant(0, DL));
5787   }
5788 
5789   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5790 
5791   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5792 
5793   SDValue NewValue =
5794       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5795 
5796   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5797   SDValue IntID = DAG.getTargetConstant(
5798       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5799   return DAG.getMemIntrinsicNode(
5800       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5801       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5802       Store->getMemoryVT(), Store->getMemOperand());
5803 }
5804 
5805 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5806                                              SelectionDAG &DAG) const {
5807   SDLoc DL(Op);
5808   MVT VT = Op.getSimpleValueType();
5809 
5810   const auto *MemSD = cast<MemSDNode>(Op);
5811   EVT MemVT = MemSD->getMemoryVT();
5812   MachineMemOperand *MMO = MemSD->getMemOperand();
5813   SDValue Chain = MemSD->getChain();
5814   SDValue BasePtr = MemSD->getBasePtr();
5815 
5816   SDValue Mask, PassThru, VL;
5817   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5818     Mask = VPLoad->getMask();
5819     PassThru = DAG.getUNDEF(VT);
5820     VL = VPLoad->getVectorLength();
5821   } else {
5822     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5823     Mask = MLoad->getMask();
5824     PassThru = MLoad->getPassThru();
5825   }
5826 
5827   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5828 
5829   MVT XLenVT = Subtarget.getXLenVT();
5830 
5831   MVT ContainerVT = VT;
5832   if (VT.isFixedLengthVector()) {
5833     ContainerVT = getContainerForFixedLengthVector(VT);
5834     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5835     if (!IsUnmasked) {
5836       MVT MaskVT = getMaskTypeFor(ContainerVT);
5837       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5838     }
5839   }
5840 
5841   if (!VL)
5842     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5843 
5844   unsigned IntID =
5845       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5846   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5847   if (IsUnmasked)
5848     Ops.push_back(DAG.getUNDEF(ContainerVT));
5849   else
5850     Ops.push_back(PassThru);
5851   Ops.push_back(BasePtr);
5852   if (!IsUnmasked)
5853     Ops.push_back(Mask);
5854   Ops.push_back(VL);
5855   if (!IsUnmasked)
5856     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5857 
5858   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5859 
5860   SDValue Result =
5861       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5862   Chain = Result.getValue(1);
5863 
5864   if (VT.isFixedLengthVector())
5865     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5866 
5867   return DAG.getMergeValues({Result, Chain}, DL);
5868 }
5869 
5870 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5871                                               SelectionDAG &DAG) const {
5872   SDLoc DL(Op);
5873 
5874   const auto *MemSD = cast<MemSDNode>(Op);
5875   EVT MemVT = MemSD->getMemoryVT();
5876   MachineMemOperand *MMO = MemSD->getMemOperand();
5877   SDValue Chain = MemSD->getChain();
5878   SDValue BasePtr = MemSD->getBasePtr();
5879   SDValue Val, Mask, VL;
5880 
5881   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5882     Val = VPStore->getValue();
5883     Mask = VPStore->getMask();
5884     VL = VPStore->getVectorLength();
5885   } else {
5886     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5887     Val = MStore->getValue();
5888     Mask = MStore->getMask();
5889   }
5890 
5891   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5892 
5893   MVT VT = Val.getSimpleValueType();
5894   MVT XLenVT = Subtarget.getXLenVT();
5895 
5896   MVT ContainerVT = VT;
5897   if (VT.isFixedLengthVector()) {
5898     ContainerVT = getContainerForFixedLengthVector(VT);
5899 
5900     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5901     if (!IsUnmasked) {
5902       MVT MaskVT = getMaskTypeFor(ContainerVT);
5903       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5904     }
5905   }
5906 
5907   if (!VL)
5908     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5909 
5910   unsigned IntID =
5911       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5912   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5913   Ops.push_back(Val);
5914   Ops.push_back(BasePtr);
5915   if (!IsUnmasked)
5916     Ops.push_back(Mask);
5917   Ops.push_back(VL);
5918 
5919   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5920                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5921 }
5922 
5923 SDValue
5924 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5925                                                       SelectionDAG &DAG) const {
5926   MVT InVT = Op.getOperand(0).getSimpleValueType();
5927   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5928 
5929   MVT VT = Op.getSimpleValueType();
5930 
5931   SDValue Op1 =
5932       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5933   SDValue Op2 =
5934       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5935 
5936   SDLoc DL(Op);
5937   SDValue VL =
5938       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5939 
5940   MVT MaskVT = getMaskTypeFor(ContainerVT);
5941   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
5942 
5943   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5944                             Op.getOperand(2), Mask, VL);
5945 
5946   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5947 }
5948 
5949 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5950     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5951   MVT VT = Op.getSimpleValueType();
5952 
5953   if (VT.getVectorElementType() == MVT::i1)
5954     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5955 
5956   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5957 }
5958 
5959 SDValue
5960 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5961                                                       SelectionDAG &DAG) const {
5962   unsigned Opc;
5963   switch (Op.getOpcode()) {
5964   default: llvm_unreachable("Unexpected opcode!");
5965   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5966   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5967   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5968   }
5969 
5970   return lowerToScalableOp(Op, DAG, Opc);
5971 }
5972 
5973 // Lower vector ABS to smax(X, sub(0, X)).
5974 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5975   SDLoc DL(Op);
5976   MVT VT = Op.getSimpleValueType();
5977   SDValue X = Op.getOperand(0);
5978 
5979   assert(VT.isFixedLengthVector() && "Unexpected type");
5980 
5981   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5982   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5983 
5984   SDValue Mask, VL;
5985   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5986 
5987   SDValue SplatZero = DAG.getNode(
5988       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
5989       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5990   SDValue NegX =
5991       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5992   SDValue Max =
5993       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5994 
5995   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5996 }
5997 
5998 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5999     SDValue Op, SelectionDAG &DAG) const {
6000   SDLoc DL(Op);
6001   MVT VT = Op.getSimpleValueType();
6002   SDValue Mag = Op.getOperand(0);
6003   SDValue Sign = Op.getOperand(1);
6004   assert(Mag.getValueType() == Sign.getValueType() &&
6005          "Can only handle COPYSIGN with matching types.");
6006 
6007   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6008   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
6009   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
6010 
6011   SDValue Mask, VL;
6012   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6013 
6014   SDValue CopySign =
6015       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
6016 
6017   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
6018 }
6019 
6020 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
6021     SDValue Op, SelectionDAG &DAG) const {
6022   MVT VT = Op.getSimpleValueType();
6023   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6024 
6025   MVT I1ContainerVT =
6026       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6027 
6028   SDValue CC =
6029       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
6030   SDValue Op1 =
6031       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6032   SDValue Op2 =
6033       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
6034 
6035   SDLoc DL(Op);
6036   SDValue Mask, VL;
6037   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6038 
6039   SDValue Select =
6040       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
6041 
6042   return convertFromScalableVector(VT, Select, DAG, Subtarget);
6043 }
6044 
6045 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
6046                                                unsigned NewOpc,
6047                                                bool HasMask) const {
6048   MVT VT = Op.getSimpleValueType();
6049   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6050 
6051   // Create list of operands by converting existing ones to scalable types.
6052   SmallVector<SDValue, 6> Ops;
6053   for (const SDValue &V : Op->op_values()) {
6054     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6055 
6056     // Pass through non-vector operands.
6057     if (!V.getValueType().isVector()) {
6058       Ops.push_back(V);
6059       continue;
6060     }
6061 
6062     // "cast" fixed length vector to a scalable vector.
6063     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6064            "Only fixed length vectors are supported!");
6065     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6066   }
6067 
6068   SDLoc DL(Op);
6069   SDValue Mask, VL;
6070   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6071   if (HasMask)
6072     Ops.push_back(Mask);
6073   Ops.push_back(VL);
6074 
6075   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6076   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6077 }
6078 
6079 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6080 // * Operands of each node are assumed to be in the same order.
6081 // * The EVL operand is promoted from i32 to i64 on RV64.
6082 // * Fixed-length vectors are converted to their scalable-vector container
6083 //   types.
6084 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6085                                        unsigned RISCVISDOpc) const {
6086   SDLoc DL(Op);
6087   MVT VT = Op.getSimpleValueType();
6088   SmallVector<SDValue, 4> Ops;
6089 
6090   for (const auto &OpIdx : enumerate(Op->ops())) {
6091     SDValue V = OpIdx.value();
6092     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6093     // Pass through operands which aren't fixed-length vectors.
6094     if (!V.getValueType().isFixedLengthVector()) {
6095       Ops.push_back(V);
6096       continue;
6097     }
6098     // "cast" fixed length vector to a scalable vector.
6099     MVT OpVT = V.getSimpleValueType();
6100     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6101     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6102            "Only fixed length vectors are supported!");
6103     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6104   }
6105 
6106   if (!VT.isFixedLengthVector())
6107     return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags());
6108 
6109   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6110 
6111   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags());
6112 
6113   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6114 }
6115 
6116 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op,
6117                                               SelectionDAG &DAG) const {
6118   SDLoc DL(Op);
6119   MVT VT = Op.getSimpleValueType();
6120 
6121   SDValue Src = Op.getOperand(0);
6122   // NOTE: Mask is dropped.
6123   SDValue VL = Op.getOperand(2);
6124 
6125   MVT ContainerVT = VT;
6126   if (VT.isFixedLengthVector()) {
6127     ContainerVT = getContainerForFixedLengthVector(VT);
6128     MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6129     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6130   }
6131 
6132   MVT XLenVT = Subtarget.getXLenVT();
6133   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6134   SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6135                                   DAG.getUNDEF(ContainerVT), Zero, VL);
6136 
6137   SDValue SplatValue = DAG.getConstant(
6138       Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT);
6139   SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6140                               DAG.getUNDEF(ContainerVT), SplatValue, VL);
6141 
6142   SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src,
6143                                Splat, ZeroSplat, VL);
6144   if (!VT.isFixedLengthVector())
6145     return Result;
6146   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6147 }
6148 
6149 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op,
6150                                                 SelectionDAG &DAG) const {
6151   SDLoc DL(Op);
6152   MVT VT = Op.getSimpleValueType();
6153 
6154   SDValue Op1 = Op.getOperand(0);
6155   SDValue Op2 = Op.getOperand(1);
6156   ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6157   // NOTE: Mask is dropped.
6158   SDValue VL = Op.getOperand(4);
6159 
6160   MVT ContainerVT = VT;
6161   if (VT.isFixedLengthVector()) {
6162     ContainerVT = getContainerForFixedLengthVector(VT);
6163     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6164     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6165   }
6166 
6167   SDValue Result;
6168   SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
6169 
6170   switch (Condition) {
6171   default:
6172     break;
6173   // X != Y  --> (X^Y)
6174   case ISD::SETNE:
6175     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6176     break;
6177   // X == Y  --> ~(X^Y)
6178   case ISD::SETEQ: {
6179     SDValue Temp =
6180         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6181     Result =
6182         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL);
6183     break;
6184   }
6185   // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
6186   // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
6187   case ISD::SETGT:
6188   case ISD::SETULT: {
6189     SDValue Temp =
6190         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6191     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL);
6192     break;
6193   }
6194   // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
6195   // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
6196   case ISD::SETLT:
6197   case ISD::SETUGT: {
6198     SDValue Temp =
6199         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6200     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL);
6201     break;
6202   }
6203   // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
6204   // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
6205   case ISD::SETGE:
6206   case ISD::SETULE: {
6207     SDValue Temp =
6208         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6209     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL);
6210     break;
6211   }
6212   // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
6213   // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
6214   case ISD::SETLE:
6215   case ISD::SETUGE: {
6216     SDValue Temp =
6217         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6218     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL);
6219     break;
6220   }
6221   }
6222 
6223   if (!VT.isFixedLengthVector())
6224     return Result;
6225   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6226 }
6227 
6228 // Lower Floating-Point/Integer Type-Convert VP SDNodes
6229 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
6230                                                 unsigned RISCVISDOpc) const {
6231   SDLoc DL(Op);
6232 
6233   SDValue Src = Op.getOperand(0);
6234   SDValue Mask = Op.getOperand(1);
6235   SDValue VL = Op.getOperand(2);
6236 
6237   MVT DstVT = Op.getSimpleValueType();
6238   MVT SrcVT = Src.getSimpleValueType();
6239   if (DstVT.isFixedLengthVector()) {
6240     DstVT = getContainerForFixedLengthVector(DstVT);
6241     SrcVT = getContainerForFixedLengthVector(SrcVT);
6242     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6243     MVT MaskVT = getMaskTypeFor(DstVT);
6244     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6245   }
6246 
6247   unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL ||
6248                              RISCVISDOpc == RISCVISD::FP_TO_SINT_VL)
6249                                 ? RISCVISD::VSEXT_VL
6250                                 : RISCVISD::VZEXT_VL;
6251 
6252   unsigned DstEltSize = DstVT.getScalarSizeInBits();
6253   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
6254 
6255   SDValue Result;
6256   if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
6257     if (SrcVT.isInteger()) {
6258       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6259 
6260       // Do we need to do any pre-widening before converting?
6261       if (SrcEltSize == 1) {
6262         MVT IntVT = DstVT.changeVectorElementTypeToInteger();
6263         MVT XLenVT = Subtarget.getXLenVT();
6264         SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6265         SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6266                                         DAG.getUNDEF(IntVT), Zero, VL);
6267         SDValue One = DAG.getConstant(
6268             RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
6269         SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6270                                        DAG.getUNDEF(IntVT), One, VL);
6271         Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
6272                           ZeroSplat, VL);
6273       } else if (DstEltSize > (2 * SrcEltSize)) {
6274         // Widen before converting.
6275         MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
6276                                      DstVT.getVectorElementCount());
6277         Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL);
6278       }
6279 
6280       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6281     } else {
6282       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6283              "Wrong input/output vector types");
6284 
6285       // Convert f16 to f32 then convert f32 to i64.
6286       if (DstEltSize > (2 * SrcEltSize)) {
6287         assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6288         MVT InterimFVT =
6289             MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6290         Src =
6291             DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL);
6292       }
6293 
6294       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6295     }
6296   } else { // Narrowing + Conversion
6297     if (SrcVT.isInteger()) {
6298       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6299       // First do a narrowing convert to an FP type half the size, then round
6300       // the FP type to a small FP type if needed.
6301 
6302       MVT InterimFVT = DstVT;
6303       if (SrcEltSize > (2 * DstEltSize)) {
6304         assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
6305         assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6306         InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6307       }
6308 
6309       Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL);
6310 
6311       if (InterimFVT != DstVT) {
6312         Src = Result;
6313         Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL);
6314       }
6315     } else {
6316       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6317              "Wrong input/output vector types");
6318       // First do a narrowing conversion to an integer half the size, then
6319       // truncate if needed.
6320 
6321       if (DstEltSize == 1) {
6322         // First convert to the same size integer, then convert to mask using
6323         // setcc.
6324         assert(SrcEltSize >= 16 && "Unexpected FP type!");
6325         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize),
6326                                           DstVT.getVectorElementCount());
6327         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6328 
6329         // Compare the integer result to 0. The integer should be 0 or 1/-1,
6330         // otherwise the conversion was undefined.
6331         MVT XLenVT = Subtarget.getXLenVT();
6332         SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
6333         SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT,
6334                                 DAG.getUNDEF(InterimIVT), SplatZero);
6335         Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero,
6336                              DAG.getCondCode(ISD::SETNE), Mask, VL);
6337       } else {
6338         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6339                                           DstVT.getVectorElementCount());
6340 
6341         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6342 
6343         while (InterimIVT != DstVT) {
6344           SrcEltSize /= 2;
6345           Src = Result;
6346           InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6347                                         DstVT.getVectorElementCount());
6348           Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
6349                                Src, Mask, VL);
6350         }
6351       }
6352     }
6353   }
6354 
6355   MVT VT = Op.getSimpleValueType();
6356   if (!VT.isFixedLengthVector())
6357     return Result;
6358   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6359 }
6360 
6361 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6362                                             unsigned MaskOpc,
6363                                             unsigned VecOpc) const {
6364   MVT VT = Op.getSimpleValueType();
6365   if (VT.getVectorElementType() != MVT::i1)
6366     return lowerVPOp(Op, DAG, VecOpc);
6367 
6368   // It is safe to drop mask parameter as masked-off elements are undef.
6369   SDValue Op1 = Op->getOperand(0);
6370   SDValue Op2 = Op->getOperand(1);
6371   SDValue VL = Op->getOperand(3);
6372 
6373   MVT ContainerVT = VT;
6374   const bool IsFixed = VT.isFixedLengthVector();
6375   if (IsFixed) {
6376     ContainerVT = getContainerForFixedLengthVector(VT);
6377     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6378     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6379   }
6380 
6381   SDLoc DL(Op);
6382   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6383   if (!IsFixed)
6384     return Val;
6385   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6386 }
6387 
6388 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6389 // matched to a RVV indexed load. The RVV indexed load instructions only
6390 // support the "unsigned unscaled" addressing mode; indices are implicitly
6391 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6392 // signed or scaled indexing is extended to the XLEN value type and scaled
6393 // accordingly.
6394 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6395                                                SelectionDAG &DAG) const {
6396   SDLoc DL(Op);
6397   MVT VT = Op.getSimpleValueType();
6398 
6399   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6400   EVT MemVT = MemSD->getMemoryVT();
6401   MachineMemOperand *MMO = MemSD->getMemOperand();
6402   SDValue Chain = MemSD->getChain();
6403   SDValue BasePtr = MemSD->getBasePtr();
6404 
6405   ISD::LoadExtType LoadExtType;
6406   SDValue Index, Mask, PassThru, VL;
6407 
6408   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6409     Index = VPGN->getIndex();
6410     Mask = VPGN->getMask();
6411     PassThru = DAG.getUNDEF(VT);
6412     VL = VPGN->getVectorLength();
6413     // VP doesn't support extending loads.
6414     LoadExtType = ISD::NON_EXTLOAD;
6415   } else {
6416     // Else it must be a MGATHER.
6417     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6418     Index = MGN->getIndex();
6419     Mask = MGN->getMask();
6420     PassThru = MGN->getPassThru();
6421     LoadExtType = MGN->getExtensionType();
6422   }
6423 
6424   MVT IndexVT = Index.getSimpleValueType();
6425   MVT XLenVT = Subtarget.getXLenVT();
6426 
6427   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6428          "Unexpected VTs!");
6429   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6430   // Targets have to explicitly opt-in for extending vector loads.
6431   assert(LoadExtType == ISD::NON_EXTLOAD &&
6432          "Unexpected extending MGATHER/VP_GATHER");
6433   (void)LoadExtType;
6434 
6435   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6436   // the selection of the masked intrinsics doesn't do this for us.
6437   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6438 
6439   MVT ContainerVT = VT;
6440   if (VT.isFixedLengthVector()) {
6441     ContainerVT = getContainerForFixedLengthVector(VT);
6442     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6443                                ContainerVT.getVectorElementCount());
6444 
6445     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6446 
6447     if (!IsUnmasked) {
6448       MVT MaskVT = getMaskTypeFor(ContainerVT);
6449       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6450       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6451     }
6452   }
6453 
6454   if (!VL)
6455     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6456 
6457   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6458     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6459     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6460                                    VL);
6461     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6462                         TrueMask, VL);
6463   }
6464 
6465   unsigned IntID =
6466       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6467   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6468   if (IsUnmasked)
6469     Ops.push_back(DAG.getUNDEF(ContainerVT));
6470   else
6471     Ops.push_back(PassThru);
6472   Ops.push_back(BasePtr);
6473   Ops.push_back(Index);
6474   if (!IsUnmasked)
6475     Ops.push_back(Mask);
6476   Ops.push_back(VL);
6477   if (!IsUnmasked)
6478     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6479 
6480   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6481   SDValue Result =
6482       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6483   Chain = Result.getValue(1);
6484 
6485   if (VT.isFixedLengthVector())
6486     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6487 
6488   return DAG.getMergeValues({Result, Chain}, DL);
6489 }
6490 
6491 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6492 // matched to a RVV indexed store. The RVV indexed store instructions only
6493 // support the "unsigned unscaled" addressing mode; indices are implicitly
6494 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6495 // signed or scaled indexing is extended to the XLEN value type and scaled
6496 // accordingly.
6497 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6498                                                 SelectionDAG &DAG) const {
6499   SDLoc DL(Op);
6500   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6501   EVT MemVT = MemSD->getMemoryVT();
6502   MachineMemOperand *MMO = MemSD->getMemOperand();
6503   SDValue Chain = MemSD->getChain();
6504   SDValue BasePtr = MemSD->getBasePtr();
6505 
6506   bool IsTruncatingStore = false;
6507   SDValue Index, Mask, Val, VL;
6508 
6509   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6510     Index = VPSN->getIndex();
6511     Mask = VPSN->getMask();
6512     Val = VPSN->getValue();
6513     VL = VPSN->getVectorLength();
6514     // VP doesn't support truncating stores.
6515     IsTruncatingStore = false;
6516   } else {
6517     // Else it must be a MSCATTER.
6518     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6519     Index = MSN->getIndex();
6520     Mask = MSN->getMask();
6521     Val = MSN->getValue();
6522     IsTruncatingStore = MSN->isTruncatingStore();
6523   }
6524 
6525   MVT VT = Val.getSimpleValueType();
6526   MVT IndexVT = Index.getSimpleValueType();
6527   MVT XLenVT = Subtarget.getXLenVT();
6528 
6529   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6530          "Unexpected VTs!");
6531   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6532   // Targets have to explicitly opt-in for extending vector loads and
6533   // truncating vector stores.
6534   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6535   (void)IsTruncatingStore;
6536 
6537   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6538   // the selection of the masked intrinsics doesn't do this for us.
6539   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6540 
6541   MVT ContainerVT = VT;
6542   if (VT.isFixedLengthVector()) {
6543     ContainerVT = getContainerForFixedLengthVector(VT);
6544     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6545                                ContainerVT.getVectorElementCount());
6546 
6547     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6548     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6549 
6550     if (!IsUnmasked) {
6551       MVT MaskVT = getMaskTypeFor(ContainerVT);
6552       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6553     }
6554   }
6555 
6556   if (!VL)
6557     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6558 
6559   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6560     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6561     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6562                                    VL);
6563     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6564                         TrueMask, VL);
6565   }
6566 
6567   unsigned IntID =
6568       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6569   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6570   Ops.push_back(Val);
6571   Ops.push_back(BasePtr);
6572   Ops.push_back(Index);
6573   if (!IsUnmasked)
6574     Ops.push_back(Mask);
6575   Ops.push_back(VL);
6576 
6577   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6578                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6579 }
6580 
6581 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6582                                                SelectionDAG &DAG) const {
6583   const MVT XLenVT = Subtarget.getXLenVT();
6584   SDLoc DL(Op);
6585   SDValue Chain = Op->getOperand(0);
6586   SDValue SysRegNo = DAG.getTargetConstant(
6587       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6588   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6589   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6590 
6591   // Encoding used for rounding mode in RISCV differs from that used in
6592   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6593   // table, which consists of a sequence of 4-bit fields, each representing
6594   // corresponding FLT_ROUNDS mode.
6595   static const int Table =
6596       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6597       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6598       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6599       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6600       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6601 
6602   SDValue Shift =
6603       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6604   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6605                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6606   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6607                                DAG.getConstant(7, DL, XLenVT));
6608 
6609   return DAG.getMergeValues({Masked, Chain}, DL);
6610 }
6611 
6612 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6613                                                SelectionDAG &DAG) const {
6614   const MVT XLenVT = Subtarget.getXLenVT();
6615   SDLoc DL(Op);
6616   SDValue Chain = Op->getOperand(0);
6617   SDValue RMValue = Op->getOperand(1);
6618   SDValue SysRegNo = DAG.getTargetConstant(
6619       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6620 
6621   // Encoding used for rounding mode in RISCV differs from that used in
6622   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6623   // a table, which consists of a sequence of 4-bit fields, each representing
6624   // corresponding RISCV mode.
6625   static const unsigned Table =
6626       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6627       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6628       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6629       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6630       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6631 
6632   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6633                               DAG.getConstant(2, DL, XLenVT));
6634   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6635                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6636   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6637                         DAG.getConstant(0x7, DL, XLenVT));
6638   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6639                      RMValue);
6640 }
6641 
6642 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
6643                                                SelectionDAG &DAG) const {
6644   MachineFunction &MF = DAG.getMachineFunction();
6645 
6646   bool isRISCV64 = Subtarget.is64Bit();
6647   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6648 
6649   int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false);
6650   return DAG.getFrameIndex(FI, PtrVT);
6651 }
6652 
6653 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6654   switch (IntNo) {
6655   default:
6656     llvm_unreachable("Unexpected Intrinsic");
6657   case Intrinsic::riscv_bcompress:
6658     return RISCVISD::BCOMPRESSW;
6659   case Intrinsic::riscv_bdecompress:
6660     return RISCVISD::BDECOMPRESSW;
6661   case Intrinsic::riscv_bfp:
6662     return RISCVISD::BFPW;
6663   case Intrinsic::riscv_fsl:
6664     return RISCVISD::FSLW;
6665   case Intrinsic::riscv_fsr:
6666     return RISCVISD::FSRW;
6667   }
6668 }
6669 
6670 // Converts the given intrinsic to a i64 operation with any extension.
6671 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6672                                          unsigned IntNo) {
6673   SDLoc DL(N);
6674   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6675   // Deal with the Instruction Operands
6676   SmallVector<SDValue, 3> NewOps;
6677   for (SDValue Op : drop_begin(N->ops()))
6678     // Promote the operand to i64 type
6679     NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op));
6680   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps);
6681   // ReplaceNodeResults requires we maintain the same type for the return value.
6682   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6683 }
6684 
6685 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6686 // form of the given Opcode.
6687 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6688   switch (Opcode) {
6689   default:
6690     llvm_unreachable("Unexpected opcode");
6691   case ISD::SHL:
6692     return RISCVISD::SLLW;
6693   case ISD::SRA:
6694     return RISCVISD::SRAW;
6695   case ISD::SRL:
6696     return RISCVISD::SRLW;
6697   case ISD::SDIV:
6698     return RISCVISD::DIVW;
6699   case ISD::UDIV:
6700     return RISCVISD::DIVUW;
6701   case ISD::UREM:
6702     return RISCVISD::REMUW;
6703   case ISD::ROTL:
6704     return RISCVISD::ROLW;
6705   case ISD::ROTR:
6706     return RISCVISD::RORW;
6707   }
6708 }
6709 
6710 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6711 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6712 // otherwise be promoted to i64, making it difficult to select the
6713 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6714 // type i8/i16/i32 is lost.
6715 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6716                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6717   SDLoc DL(N);
6718   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6719   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6720   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6721   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6722   // ReplaceNodeResults requires we maintain the same type for the return value.
6723   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6724 }
6725 
6726 // Converts the given 32-bit operation to a i64 operation with signed extension
6727 // semantic to reduce the signed extension instructions.
6728 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6729   SDLoc DL(N);
6730   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6731   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6732   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6733   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6734                                DAG.getValueType(MVT::i32));
6735   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6736 }
6737 
6738 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6739                                              SmallVectorImpl<SDValue> &Results,
6740                                              SelectionDAG &DAG) const {
6741   SDLoc DL(N);
6742   switch (N->getOpcode()) {
6743   default:
6744     llvm_unreachable("Don't know how to custom type legalize this operation!");
6745   case ISD::STRICT_FP_TO_SINT:
6746   case ISD::STRICT_FP_TO_UINT:
6747   case ISD::FP_TO_SINT:
6748   case ISD::FP_TO_UINT: {
6749     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6750            "Unexpected custom legalisation");
6751     bool IsStrict = N->isStrictFPOpcode();
6752     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6753                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6754     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6755     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6756         TargetLowering::TypeSoftenFloat) {
6757       if (!isTypeLegal(Op0.getValueType()))
6758         return;
6759       if (IsStrict) {
6760         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6761                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6762         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6763         SDValue Res = DAG.getNode(
6764             Opc, DL, VTs, N->getOperand(0), Op0,
6765             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6766         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6767         Results.push_back(Res.getValue(1));
6768         return;
6769       }
6770       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6771       SDValue Res =
6772           DAG.getNode(Opc, DL, MVT::i64, Op0,
6773                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6774       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6775       return;
6776     }
6777     // If the FP type needs to be softened, emit a library call using the 'si'
6778     // version. If we left it to default legalization we'd end up with 'di'. If
6779     // the FP type doesn't need to be softened just let generic type
6780     // legalization promote the result type.
6781     RTLIB::Libcall LC;
6782     if (IsSigned)
6783       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6784     else
6785       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6786     MakeLibCallOptions CallOptions;
6787     EVT OpVT = Op0.getValueType();
6788     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6789     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6790     SDValue Result;
6791     std::tie(Result, Chain) =
6792         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6793     Results.push_back(Result);
6794     if (IsStrict)
6795       Results.push_back(Chain);
6796     break;
6797   }
6798   case ISD::READCYCLECOUNTER: {
6799     assert(!Subtarget.is64Bit() &&
6800            "READCYCLECOUNTER only has custom type legalization on riscv32");
6801 
6802     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6803     SDValue RCW =
6804         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6805 
6806     Results.push_back(
6807         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6808     Results.push_back(RCW.getValue(2));
6809     break;
6810   }
6811   case ISD::MUL: {
6812     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6813     unsigned XLen = Subtarget.getXLen();
6814     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6815     if (Size > XLen) {
6816       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6817       SDValue LHS = N->getOperand(0);
6818       SDValue RHS = N->getOperand(1);
6819       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6820 
6821       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6822       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6823       // We need exactly one side to be unsigned.
6824       if (LHSIsU == RHSIsU)
6825         return;
6826 
6827       auto MakeMULPair = [&](SDValue S, SDValue U) {
6828         MVT XLenVT = Subtarget.getXLenVT();
6829         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6830         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6831         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6832         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6833         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6834       };
6835 
6836       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6837       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6838 
6839       // The other operand should be signed, but still prefer MULH when
6840       // possible.
6841       if (RHSIsU && LHSIsS && !RHSIsS)
6842         Results.push_back(MakeMULPair(LHS, RHS));
6843       else if (LHSIsU && RHSIsS && !LHSIsS)
6844         Results.push_back(MakeMULPair(RHS, LHS));
6845 
6846       return;
6847     }
6848     LLVM_FALLTHROUGH;
6849   }
6850   case ISD::ADD:
6851   case ISD::SUB:
6852     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6853            "Unexpected custom legalisation");
6854     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6855     break;
6856   case ISD::SHL:
6857   case ISD::SRA:
6858   case ISD::SRL:
6859     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6860            "Unexpected custom legalisation");
6861     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6862       // If we can use a BSET instruction, allow default promotion to apply.
6863       if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() &&
6864           isOneConstant(N->getOperand(0)))
6865         break;
6866       Results.push_back(customLegalizeToWOp(N, DAG));
6867       break;
6868     }
6869 
6870     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6871     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6872     // shift amount.
6873     if (N->getOpcode() == ISD::SHL) {
6874       SDLoc DL(N);
6875       SDValue NewOp0 =
6876           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6877       SDValue NewOp1 =
6878           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6879       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6880       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6881                                    DAG.getValueType(MVT::i32));
6882       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6883     }
6884 
6885     break;
6886   case ISD::ROTL:
6887   case ISD::ROTR:
6888     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6889            "Unexpected custom legalisation");
6890     Results.push_back(customLegalizeToWOp(N, DAG));
6891     break;
6892   case ISD::CTTZ:
6893   case ISD::CTTZ_ZERO_UNDEF:
6894   case ISD::CTLZ:
6895   case ISD::CTLZ_ZERO_UNDEF: {
6896     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6897            "Unexpected custom legalisation");
6898 
6899     SDValue NewOp0 =
6900         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6901     bool IsCTZ =
6902         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6903     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6904     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6905     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6906     return;
6907   }
6908   case ISD::SDIV:
6909   case ISD::UDIV:
6910   case ISD::UREM: {
6911     MVT VT = N->getSimpleValueType(0);
6912     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6913            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6914            "Unexpected custom legalisation");
6915     // Don't promote division/remainder by constant since we should expand those
6916     // to multiply by magic constant.
6917     // FIXME: What if the expansion is disabled for minsize.
6918     if (N->getOperand(1).getOpcode() == ISD::Constant)
6919       return;
6920 
6921     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6922     // the upper 32 bits. For other types we need to sign or zero extend
6923     // based on the opcode.
6924     unsigned ExtOpc = ISD::ANY_EXTEND;
6925     if (VT != MVT::i32)
6926       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6927                                            : ISD::ZERO_EXTEND;
6928 
6929     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6930     break;
6931   }
6932   case ISD::UADDO:
6933   case ISD::USUBO: {
6934     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6935            "Unexpected custom legalisation");
6936     bool IsAdd = N->getOpcode() == ISD::UADDO;
6937     // Create an ADDW or SUBW.
6938     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6939     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6940     SDValue Res =
6941         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6942     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6943                       DAG.getValueType(MVT::i32));
6944 
6945     SDValue Overflow;
6946     if (IsAdd && isOneConstant(RHS)) {
6947       // Special case uaddo X, 1 overflowed if the addition result is 0.
6948       // The general case (X + C) < C is not necessarily beneficial. Although we
6949       // reduce the live range of X, we may introduce the materialization of
6950       // constant C, especially when the setcc result is used by branch. We have
6951       // no compare with constant and branch instructions.
6952       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res,
6953                               DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ);
6954     } else {
6955       // Sign extend the LHS and perform an unsigned compare with the ADDW
6956       // result. Since the inputs are sign extended from i32, this is equivalent
6957       // to comparing the lower 32 bits.
6958       LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6959       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6960                               IsAdd ? ISD::SETULT : ISD::SETUGT);
6961     }
6962 
6963     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6964     Results.push_back(Overflow);
6965     return;
6966   }
6967   case ISD::UADDSAT:
6968   case ISD::USUBSAT: {
6969     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6970            "Unexpected custom legalisation");
6971     if (Subtarget.hasStdExtZbb()) {
6972       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6973       // sign extend allows overflow of the lower 32 bits to be detected on
6974       // the promoted size.
6975       SDValue LHS =
6976           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6977       SDValue RHS =
6978           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6979       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6980       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6981       return;
6982     }
6983 
6984     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6985     // promotion for UADDO/USUBO.
6986     Results.push_back(expandAddSubSat(N, DAG));
6987     return;
6988   }
6989   case ISD::ABS: {
6990     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6991            "Unexpected custom legalisation");
6992           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6993 
6994     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
6995 
6996     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6997 
6998     // Freeze the source so we can increase it's use count.
6999     Src = DAG.getFreeze(Src);
7000 
7001     // Copy sign bit to all bits using the sraiw pattern.
7002     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
7003                                    DAG.getValueType(MVT::i32));
7004     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
7005                            DAG.getConstant(31, DL, MVT::i64));
7006 
7007     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
7008     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
7009 
7010     // NOTE: The result is only required to be anyextended, but sext is
7011     // consistent with type legalization of sub.
7012     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
7013                          DAG.getValueType(MVT::i32));
7014     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
7015     return;
7016   }
7017   case ISD::BITCAST: {
7018     EVT VT = N->getValueType(0);
7019     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
7020     SDValue Op0 = N->getOperand(0);
7021     EVT Op0VT = Op0.getValueType();
7022     MVT XLenVT = Subtarget.getXLenVT();
7023     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
7024       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
7025       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
7026     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
7027                Subtarget.hasStdExtF()) {
7028       SDValue FPConv =
7029           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
7030       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
7031     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
7032                isTypeLegal(Op0VT)) {
7033       // Custom-legalize bitcasts from fixed-length vector types to illegal
7034       // scalar types in order to improve codegen. Bitcast the vector to a
7035       // one-element vector type whose element type is the same as the result
7036       // type, and extract the first element.
7037       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
7038       if (isTypeLegal(BVT)) {
7039         SDValue BVec = DAG.getBitcast(BVT, Op0);
7040         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
7041                                       DAG.getConstant(0, DL, XLenVT)));
7042       }
7043     }
7044     break;
7045   }
7046   case RISCVISD::GREV:
7047   case RISCVISD::GORC:
7048   case RISCVISD::SHFL: {
7049     MVT VT = N->getSimpleValueType(0);
7050     MVT XLenVT = Subtarget.getXLenVT();
7051     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
7052            "Unexpected custom legalisation");
7053     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
7054     assert((Subtarget.hasStdExtZbp() ||
7055             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
7056              N->getConstantOperandVal(1) == 7)) &&
7057            "Unexpected extension");
7058     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7059     SDValue NewOp1 =
7060         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
7061     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
7062     // ReplaceNodeResults requires we maintain the same type for the return
7063     // value.
7064     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
7065     break;
7066   }
7067   case ISD::BSWAP:
7068   case ISD::BITREVERSE: {
7069     MVT VT = N->getSimpleValueType(0);
7070     MVT XLenVT = Subtarget.getXLenVT();
7071     assert((VT == MVT::i8 || VT == MVT::i16 ||
7072             (VT == MVT::i32 && Subtarget.is64Bit())) &&
7073            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
7074     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7075     unsigned Imm = VT.getSizeInBits() - 1;
7076     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
7077     if (N->getOpcode() == ISD::BSWAP)
7078       Imm &= ~0x7U;
7079     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
7080                                 DAG.getConstant(Imm, DL, XLenVT));
7081     // ReplaceNodeResults requires we maintain the same type for the return
7082     // value.
7083     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
7084     break;
7085   }
7086   case ISD::FSHL:
7087   case ISD::FSHR: {
7088     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7089            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
7090     SDValue NewOp0 =
7091         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7092     SDValue NewOp1 =
7093         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7094     SDValue NewShAmt =
7095         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7096     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
7097     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
7098     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
7099                            DAG.getConstant(0x1f, DL, MVT::i64));
7100     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
7101     // instruction use different orders. fshl will return its first operand for
7102     // shift of zero, fshr will return its second operand. fsl and fsr both
7103     // return rs1 so the ISD nodes need to have different operand orders.
7104     // Shift amount is in rs2.
7105     unsigned Opc = RISCVISD::FSLW;
7106     if (N->getOpcode() == ISD::FSHR) {
7107       std::swap(NewOp0, NewOp1);
7108       Opc = RISCVISD::FSRW;
7109     }
7110     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
7111     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
7112     break;
7113   }
7114   case ISD::EXTRACT_VECTOR_ELT: {
7115     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
7116     // type is illegal (currently only vXi64 RV32).
7117     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
7118     // transferred to the destination register. We issue two of these from the
7119     // upper- and lower- halves of the SEW-bit vector element, slid down to the
7120     // first element.
7121     SDValue Vec = N->getOperand(0);
7122     SDValue Idx = N->getOperand(1);
7123 
7124     // The vector type hasn't been legalized yet so we can't issue target
7125     // specific nodes if it needs legalization.
7126     // FIXME: We would manually legalize if it's important.
7127     if (!isTypeLegal(Vec.getValueType()))
7128       return;
7129 
7130     MVT VecVT = Vec.getSimpleValueType();
7131 
7132     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7133            VecVT.getVectorElementType() == MVT::i64 &&
7134            "Unexpected EXTRACT_VECTOR_ELT legalization");
7135 
7136     // If this is a fixed vector, we need to convert it to a scalable vector.
7137     MVT ContainerVT = VecVT;
7138     if (VecVT.isFixedLengthVector()) {
7139       ContainerVT = getContainerForFixedLengthVector(VecVT);
7140       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7141     }
7142 
7143     MVT XLenVT = Subtarget.getXLenVT();
7144 
7145     // Use a VL of 1 to avoid processing more elements than we need.
7146     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7147     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
7148 
7149     // Unless the index is known to be 0, we must slide the vector down to get
7150     // the desired element into index 0.
7151     if (!isNullConstant(Idx)) {
7152       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7153                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7154     }
7155 
7156     // Extract the lower XLEN bits of the correct vector element.
7157     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7158 
7159     // To extract the upper XLEN bits of the vector element, shift the first
7160     // element right by 32 bits and re-extract the lower XLEN bits.
7161     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7162                                      DAG.getUNDEF(ContainerVT),
7163                                      DAG.getConstant(32, DL, XLenVT), VL);
7164     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7165                                  ThirtyTwoV, Mask, VL);
7166 
7167     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7168 
7169     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7170     break;
7171   }
7172   case ISD::INTRINSIC_WO_CHAIN: {
7173     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7174     switch (IntNo) {
7175     default:
7176       llvm_unreachable(
7177           "Don't know how to custom type legalize this intrinsic!");
7178     case Intrinsic::riscv_grev:
7179     case Intrinsic::riscv_gorc: {
7180       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7181              "Unexpected custom legalisation");
7182       SDValue NewOp1 =
7183           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7184       SDValue NewOp2 =
7185           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7186       unsigned Opc =
7187           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7188       // If the control is a constant, promote the node by clearing any extra
7189       // bits bits in the control. isel will form greviw/gorciw if the result is
7190       // sign extended.
7191       if (isa<ConstantSDNode>(NewOp2)) {
7192         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7193                              DAG.getConstant(0x1f, DL, MVT::i64));
7194         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7195       }
7196       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7197       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7198       break;
7199     }
7200     case Intrinsic::riscv_bcompress:
7201     case Intrinsic::riscv_bdecompress:
7202     case Intrinsic::riscv_bfp:
7203     case Intrinsic::riscv_fsl:
7204     case Intrinsic::riscv_fsr: {
7205       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7206              "Unexpected custom legalisation");
7207       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7208       break;
7209     }
7210     case Intrinsic::riscv_orc_b: {
7211       // Lower to the GORCI encoding for orc.b with the operand extended.
7212       SDValue NewOp =
7213           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7214       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7215                                 DAG.getConstant(7, DL, MVT::i64));
7216       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7217       return;
7218     }
7219     case Intrinsic::riscv_shfl:
7220     case Intrinsic::riscv_unshfl: {
7221       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7222              "Unexpected custom legalisation");
7223       SDValue NewOp1 =
7224           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7225       SDValue NewOp2 =
7226           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7227       unsigned Opc =
7228           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7229       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7230       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7231       // will be shuffled the same way as the lower 32 bit half, but the two
7232       // halves won't cross.
7233       if (isa<ConstantSDNode>(NewOp2)) {
7234         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7235                              DAG.getConstant(0xf, DL, MVT::i64));
7236         Opc =
7237             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7238       }
7239       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7240       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7241       break;
7242     }
7243     case Intrinsic::riscv_vmv_x_s: {
7244       EVT VT = N->getValueType(0);
7245       MVT XLenVT = Subtarget.getXLenVT();
7246       if (VT.bitsLT(XLenVT)) {
7247         // Simple case just extract using vmv.x.s and truncate.
7248         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7249                                       Subtarget.getXLenVT(), N->getOperand(1));
7250         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7251         return;
7252       }
7253 
7254       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7255              "Unexpected custom legalization");
7256 
7257       // We need to do the move in two steps.
7258       SDValue Vec = N->getOperand(1);
7259       MVT VecVT = Vec.getSimpleValueType();
7260 
7261       // First extract the lower XLEN bits of the element.
7262       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7263 
7264       // To extract the upper XLEN bits of the vector element, shift the first
7265       // element right by 32 bits and re-extract the lower XLEN bits.
7266       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7267       SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG);
7268 
7269       SDValue ThirtyTwoV =
7270           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7271                       DAG.getConstant(32, DL, XLenVT), VL);
7272       SDValue LShr32 =
7273           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7274       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7275 
7276       Results.push_back(
7277           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7278       break;
7279     }
7280     }
7281     break;
7282   }
7283   case ISD::VECREDUCE_ADD:
7284   case ISD::VECREDUCE_AND:
7285   case ISD::VECREDUCE_OR:
7286   case ISD::VECREDUCE_XOR:
7287   case ISD::VECREDUCE_SMAX:
7288   case ISD::VECREDUCE_UMAX:
7289   case ISD::VECREDUCE_SMIN:
7290   case ISD::VECREDUCE_UMIN:
7291     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7292       Results.push_back(V);
7293     break;
7294   case ISD::VP_REDUCE_ADD:
7295   case ISD::VP_REDUCE_AND:
7296   case ISD::VP_REDUCE_OR:
7297   case ISD::VP_REDUCE_XOR:
7298   case ISD::VP_REDUCE_SMAX:
7299   case ISD::VP_REDUCE_UMAX:
7300   case ISD::VP_REDUCE_SMIN:
7301   case ISD::VP_REDUCE_UMIN:
7302     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7303       Results.push_back(V);
7304     break;
7305   case ISD::FLT_ROUNDS_: {
7306     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7307     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7308     Results.push_back(Res.getValue(0));
7309     Results.push_back(Res.getValue(1));
7310     break;
7311   }
7312   }
7313 }
7314 
7315 // A structure to hold one of the bit-manipulation patterns below. Together, a
7316 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7317 //   (or (and (shl x, 1), 0xAAAAAAAA),
7318 //       (and (srl x, 1), 0x55555555))
7319 struct RISCVBitmanipPat {
7320   SDValue Op;
7321   unsigned ShAmt;
7322   bool IsSHL;
7323 
7324   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7325     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7326   }
7327 };
7328 
7329 // Matches patterns of the form
7330 //   (and (shl x, C2), (C1 << C2))
7331 //   (and (srl x, C2), C1)
7332 //   (shl (and x, C1), C2)
7333 //   (srl (and x, (C1 << C2)), C2)
7334 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7335 // The expected masks for each shift amount are specified in BitmanipMasks where
7336 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7337 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7338 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7339 // XLen is 64.
7340 static Optional<RISCVBitmanipPat>
7341 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7342   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7343          "Unexpected number of masks");
7344   Optional<uint64_t> Mask;
7345   // Optionally consume a mask around the shift operation.
7346   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7347     Mask = Op.getConstantOperandVal(1);
7348     Op = Op.getOperand(0);
7349   }
7350   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7351     return None;
7352   bool IsSHL = Op.getOpcode() == ISD::SHL;
7353 
7354   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7355     return None;
7356   uint64_t ShAmt = Op.getConstantOperandVal(1);
7357 
7358   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7359   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7360     return None;
7361   // If we don't have enough masks for 64 bit, then we must be trying to
7362   // match SHFL so we're only allowed to shift 1/4 of the width.
7363   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7364     return None;
7365 
7366   SDValue Src = Op.getOperand(0);
7367 
7368   // The expected mask is shifted left when the AND is found around SHL
7369   // patterns.
7370   //   ((x >> 1) & 0x55555555)
7371   //   ((x << 1) & 0xAAAAAAAA)
7372   bool SHLExpMask = IsSHL;
7373 
7374   if (!Mask) {
7375     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7376     // the mask is all ones: consume that now.
7377     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7378       Mask = Src.getConstantOperandVal(1);
7379       Src = Src.getOperand(0);
7380       // The expected mask is now in fact shifted left for SRL, so reverse the
7381       // decision.
7382       //   ((x & 0xAAAAAAAA) >> 1)
7383       //   ((x & 0x55555555) << 1)
7384       SHLExpMask = !SHLExpMask;
7385     } else {
7386       // Use a default shifted mask of all-ones if there's no AND, truncated
7387       // down to the expected width. This simplifies the logic later on.
7388       Mask = maskTrailingOnes<uint64_t>(Width);
7389       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7390     }
7391   }
7392 
7393   unsigned MaskIdx = Log2_32(ShAmt);
7394   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7395 
7396   if (SHLExpMask)
7397     ExpMask <<= ShAmt;
7398 
7399   if (Mask != ExpMask)
7400     return None;
7401 
7402   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7403 }
7404 
7405 // Matches any of the following bit-manipulation patterns:
7406 //   (and (shl x, 1), (0x55555555 << 1))
7407 //   (and (srl x, 1), 0x55555555)
7408 //   (shl (and x, 0x55555555), 1)
7409 //   (srl (and x, (0x55555555 << 1)), 1)
7410 // where the shift amount and mask may vary thus:
7411 //   [1]  = 0x55555555 / 0xAAAAAAAA
7412 //   [2]  = 0x33333333 / 0xCCCCCCCC
7413 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7414 //   [8]  = 0x00FF00FF / 0xFF00FF00
7415 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7416 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7417 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7418   // These are the unshifted masks which we use to match bit-manipulation
7419   // patterns. They may be shifted left in certain circumstances.
7420   static const uint64_t BitmanipMasks[] = {
7421       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7422       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7423 
7424   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7425 }
7426 
7427 // Try to fold (<bop> x, (reduction.<bop> vec, start))
7428 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) {
7429   auto BinOpToRVVReduce = [](unsigned Opc) {
7430     switch (Opc) {
7431     default:
7432       llvm_unreachable("Unhandled binary to transfrom reduction");
7433     case ISD::ADD:
7434       return RISCVISD::VECREDUCE_ADD_VL;
7435     case ISD::UMAX:
7436       return RISCVISD::VECREDUCE_UMAX_VL;
7437     case ISD::SMAX:
7438       return RISCVISD::VECREDUCE_SMAX_VL;
7439     case ISD::UMIN:
7440       return RISCVISD::VECREDUCE_UMIN_VL;
7441     case ISD::SMIN:
7442       return RISCVISD::VECREDUCE_SMIN_VL;
7443     case ISD::AND:
7444       return RISCVISD::VECREDUCE_AND_VL;
7445     case ISD::OR:
7446       return RISCVISD::VECREDUCE_OR_VL;
7447     case ISD::XOR:
7448       return RISCVISD::VECREDUCE_XOR_VL;
7449     case ISD::FADD:
7450       return RISCVISD::VECREDUCE_FADD_VL;
7451     case ISD::FMAXNUM:
7452       return RISCVISD::VECREDUCE_FMAX_VL;
7453     case ISD::FMINNUM:
7454       return RISCVISD::VECREDUCE_FMIN_VL;
7455     }
7456   };
7457 
7458   auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) {
7459     return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7460            isNullConstant(V.getOperand(1)) &&
7461            V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc);
7462   };
7463 
7464   unsigned Opc = N->getOpcode();
7465   unsigned ReduceIdx;
7466   if (IsReduction(N->getOperand(0), Opc))
7467     ReduceIdx = 0;
7468   else if (IsReduction(N->getOperand(1), Opc))
7469     ReduceIdx = 1;
7470   else
7471     return SDValue();
7472 
7473   // Skip if FADD disallows reassociation but the combiner needs.
7474   if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation())
7475     return SDValue();
7476 
7477   SDValue Extract = N->getOperand(ReduceIdx);
7478   SDValue Reduce = Extract.getOperand(0);
7479   if (!Reduce.hasOneUse())
7480     return SDValue();
7481 
7482   SDValue ScalarV = Reduce.getOperand(2);
7483 
7484   // Make sure that ScalarV is a splat with VL=1.
7485   if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL &&
7486       ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL &&
7487       ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL)
7488     return SDValue();
7489 
7490   if (!isOneConstant(ScalarV.getOperand(2)))
7491     return SDValue();
7492 
7493   // TODO: Deal with value other than neutral element.
7494   auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) {
7495     if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() &&
7496         isNullFPConstant(V))
7497       return true;
7498     return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(),
7499                                  N->getFlags()) == V;
7500   };
7501 
7502   // Check the scalar of ScalarV is neutral element
7503   if (!IsRVVNeutralElement(N, ScalarV.getOperand(1)))
7504     return SDValue();
7505 
7506   if (!ScalarV.hasOneUse())
7507     return SDValue();
7508 
7509   EVT SplatVT = ScalarV.getValueType();
7510   SDValue NewStart = N->getOperand(1 - ReduceIdx);
7511   unsigned SplatOpc = RISCVISD::VFMV_S_F_VL;
7512   if (SplatVT.isInteger()) {
7513     auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode());
7514     if (!C || C->isZero() || !isInt<5>(C->getSExtValue()))
7515       SplatOpc = RISCVISD::VMV_S_X_VL;
7516     else
7517       SplatOpc = RISCVISD::VMV_V_X_VL;
7518   }
7519 
7520   SDValue NewScalarV =
7521       DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart,
7522                   ScalarV.getOperand(2));
7523   SDValue NewReduce =
7524       DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(),
7525                   Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV,
7526                   Reduce.getOperand(3), Reduce.getOperand(4));
7527   return DAG.getNode(Extract.getOpcode(), SDLoc(Extract),
7528                      Extract.getValueType(), NewReduce, Extract.getOperand(1));
7529 }
7530 
7531 // Match the following pattern as a GREVI(W) operation
7532 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7533 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7534                                const RISCVSubtarget &Subtarget) {
7535   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7536   EVT VT = Op.getValueType();
7537 
7538   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7539     auto LHS = matchGREVIPat(Op.getOperand(0));
7540     auto RHS = matchGREVIPat(Op.getOperand(1));
7541     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7542       SDLoc DL(Op);
7543       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7544                          DAG.getConstant(LHS->ShAmt, DL, VT));
7545     }
7546   }
7547   return SDValue();
7548 }
7549 
7550 // Matches any the following pattern as a GORCI(W) operation
7551 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7552 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7553 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7554 // Note that with the variant of 3.,
7555 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7556 // the inner pattern will first be matched as GREVI and then the outer
7557 // pattern will be matched to GORC via the first rule above.
7558 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7559 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7560                                const RISCVSubtarget &Subtarget) {
7561   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7562   EVT VT = Op.getValueType();
7563 
7564   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7565     SDLoc DL(Op);
7566     SDValue Op0 = Op.getOperand(0);
7567     SDValue Op1 = Op.getOperand(1);
7568 
7569     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7570       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7571           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7572           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7573         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7574       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7575       if ((Reverse.getOpcode() == ISD::ROTL ||
7576            Reverse.getOpcode() == ISD::ROTR) &&
7577           Reverse.getOperand(0) == X &&
7578           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7579         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7580         if (RotAmt == (VT.getSizeInBits() / 2))
7581           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7582                              DAG.getConstant(RotAmt, DL, VT));
7583       }
7584       return SDValue();
7585     };
7586 
7587     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7588     if (SDValue V = MatchOROfReverse(Op0, Op1))
7589       return V;
7590     if (SDValue V = MatchOROfReverse(Op1, Op0))
7591       return V;
7592 
7593     // OR is commutable so canonicalize its OR operand to the left
7594     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7595       std::swap(Op0, Op1);
7596     if (Op0.getOpcode() != ISD::OR)
7597       return SDValue();
7598     SDValue OrOp0 = Op0.getOperand(0);
7599     SDValue OrOp1 = Op0.getOperand(1);
7600     auto LHS = matchGREVIPat(OrOp0);
7601     // OR is commutable so swap the operands and try again: x might have been
7602     // on the left
7603     if (!LHS) {
7604       std::swap(OrOp0, OrOp1);
7605       LHS = matchGREVIPat(OrOp0);
7606     }
7607     auto RHS = matchGREVIPat(Op1);
7608     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7609       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7610                          DAG.getConstant(LHS->ShAmt, DL, VT));
7611     }
7612   }
7613   return SDValue();
7614 }
7615 
7616 // Matches any of the following bit-manipulation patterns:
7617 //   (and (shl x, 1), (0x22222222 << 1))
7618 //   (and (srl x, 1), 0x22222222)
7619 //   (shl (and x, 0x22222222), 1)
7620 //   (srl (and x, (0x22222222 << 1)), 1)
7621 // where the shift amount and mask may vary thus:
7622 //   [1]  = 0x22222222 / 0x44444444
7623 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7624 //   [4]  = 0x00F000F0 / 0x0F000F00
7625 //   [8]  = 0x0000FF00 / 0x00FF0000
7626 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7627 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7628   // These are the unshifted masks which we use to match bit-manipulation
7629   // patterns. They may be shifted left in certain circumstances.
7630   static const uint64_t BitmanipMasks[] = {
7631       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7632       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7633 
7634   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7635 }
7636 
7637 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7638 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7639                                const RISCVSubtarget &Subtarget) {
7640   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7641   EVT VT = Op.getValueType();
7642 
7643   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7644     return SDValue();
7645 
7646   SDValue Op0 = Op.getOperand(0);
7647   SDValue Op1 = Op.getOperand(1);
7648 
7649   // Or is commutable so canonicalize the second OR to the LHS.
7650   if (Op0.getOpcode() != ISD::OR)
7651     std::swap(Op0, Op1);
7652   if (Op0.getOpcode() != ISD::OR)
7653     return SDValue();
7654 
7655   // We found an inner OR, so our operands are the operands of the inner OR
7656   // and the other operand of the outer OR.
7657   SDValue A = Op0.getOperand(0);
7658   SDValue B = Op0.getOperand(1);
7659   SDValue C = Op1;
7660 
7661   auto Match1 = matchSHFLPat(A);
7662   auto Match2 = matchSHFLPat(B);
7663 
7664   // If neither matched, we failed.
7665   if (!Match1 && !Match2)
7666     return SDValue();
7667 
7668   // We had at least one match. if one failed, try the remaining C operand.
7669   if (!Match1) {
7670     std::swap(A, C);
7671     Match1 = matchSHFLPat(A);
7672     if (!Match1)
7673       return SDValue();
7674   } else if (!Match2) {
7675     std::swap(B, C);
7676     Match2 = matchSHFLPat(B);
7677     if (!Match2)
7678       return SDValue();
7679   }
7680   assert(Match1 && Match2);
7681 
7682   // Make sure our matches pair up.
7683   if (!Match1->formsPairWith(*Match2))
7684     return SDValue();
7685 
7686   // All the remains is to make sure C is an AND with the same input, that masks
7687   // out the bits that are being shuffled.
7688   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7689       C.getOperand(0) != Match1->Op)
7690     return SDValue();
7691 
7692   uint64_t Mask = C.getConstantOperandVal(1);
7693 
7694   static const uint64_t BitmanipMasks[] = {
7695       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7696       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7697   };
7698 
7699   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7700   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7701   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7702 
7703   if (Mask != ExpMask)
7704     return SDValue();
7705 
7706   SDLoc DL(Op);
7707   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7708                      DAG.getConstant(Match1->ShAmt, DL, VT));
7709 }
7710 
7711 // Optimize (add (shl x, c0), (shl y, c1)) ->
7712 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7713 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7714                                   const RISCVSubtarget &Subtarget) {
7715   // Perform this optimization only in the zba extension.
7716   if (!Subtarget.hasStdExtZba())
7717     return SDValue();
7718 
7719   // Skip for vector types and larger types.
7720   EVT VT = N->getValueType(0);
7721   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7722     return SDValue();
7723 
7724   // The two operand nodes must be SHL and have no other use.
7725   SDValue N0 = N->getOperand(0);
7726   SDValue N1 = N->getOperand(1);
7727   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7728       !N0->hasOneUse() || !N1->hasOneUse())
7729     return SDValue();
7730 
7731   // Check c0 and c1.
7732   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7733   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7734   if (!N0C || !N1C)
7735     return SDValue();
7736   int64_t C0 = N0C->getSExtValue();
7737   int64_t C1 = N1C->getSExtValue();
7738   if (C0 <= 0 || C1 <= 0)
7739     return SDValue();
7740 
7741   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7742   int64_t Bits = std::min(C0, C1);
7743   int64_t Diff = std::abs(C0 - C1);
7744   if (Diff != 1 && Diff != 2 && Diff != 3)
7745     return SDValue();
7746 
7747   // Build nodes.
7748   SDLoc DL(N);
7749   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7750   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7751   SDValue NA0 =
7752       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7753   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7754   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7755 }
7756 
7757 // Combine
7758 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7759 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7760 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7761 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7762 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7763 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7764 // The grev patterns represents BSWAP.
7765 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7766 // off the grev.
7767 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7768                                           const RISCVSubtarget &Subtarget) {
7769   bool IsWInstruction =
7770       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7771   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7772           IsWInstruction) &&
7773          "Unexpected opcode!");
7774   SDValue Src = N->getOperand(0);
7775   EVT VT = N->getValueType(0);
7776   SDLoc DL(N);
7777 
7778   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7779     return SDValue();
7780 
7781   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7782       !isa<ConstantSDNode>(Src.getOperand(1)))
7783     return SDValue();
7784 
7785   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7786   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7787 
7788   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7789   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7790   unsigned ShAmt1 = N->getConstantOperandVal(1);
7791   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7792   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7793     return SDValue();
7794 
7795   Src = Src.getOperand(0);
7796 
7797   // Toggle bit the MSB of the shift.
7798   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7799   if (CombinedShAmt == 0)
7800     return Src;
7801 
7802   SDValue Res = DAG.getNode(
7803       RISCVISD::GREV, DL, VT, Src,
7804       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7805   if (!IsWInstruction)
7806     return Res;
7807 
7808   // Sign extend the result to match the behavior of the rotate. This will be
7809   // selected to GREVIW in isel.
7810   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7811                      DAG.getValueType(MVT::i32));
7812 }
7813 
7814 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7815 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7816 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7817 // not undo itself, but they are redundant.
7818 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7819   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7820   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7821   SDValue Src = N->getOperand(0);
7822 
7823   if (Src.getOpcode() != N->getOpcode())
7824     return SDValue();
7825 
7826   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7827       !isa<ConstantSDNode>(Src.getOperand(1)))
7828     return SDValue();
7829 
7830   unsigned ShAmt1 = N->getConstantOperandVal(1);
7831   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7832   Src = Src.getOperand(0);
7833 
7834   unsigned CombinedShAmt;
7835   if (IsGORC)
7836     CombinedShAmt = ShAmt1 | ShAmt2;
7837   else
7838     CombinedShAmt = ShAmt1 ^ ShAmt2;
7839 
7840   if (CombinedShAmt == 0)
7841     return Src;
7842 
7843   SDLoc DL(N);
7844   return DAG.getNode(
7845       N->getOpcode(), DL, N->getValueType(0), Src,
7846       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7847 }
7848 
7849 // Combine a constant select operand into its use:
7850 //
7851 // (and (select cond, -1, c), x)
7852 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7853 // (or  (select cond, 0, c), x)
7854 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7855 // (xor (select cond, 0, c), x)
7856 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7857 // (add (select cond, 0, c), x)
7858 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7859 // (sub x, (select cond, 0, c))
7860 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7861 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7862                                    SelectionDAG &DAG, bool AllOnes) {
7863   EVT VT = N->getValueType(0);
7864 
7865   // Skip vectors.
7866   if (VT.isVector())
7867     return SDValue();
7868 
7869   if ((Slct.getOpcode() != ISD::SELECT &&
7870        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7871       !Slct.hasOneUse())
7872     return SDValue();
7873 
7874   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7875     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7876   };
7877 
7878   bool SwapSelectOps;
7879   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7880   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7881   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7882   SDValue NonConstantVal;
7883   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7884     SwapSelectOps = false;
7885     NonConstantVal = FalseVal;
7886   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7887     SwapSelectOps = true;
7888     NonConstantVal = TrueVal;
7889   } else
7890     return SDValue();
7891 
7892   // Slct is now know to be the desired identity constant when CC is true.
7893   TrueVal = OtherOp;
7894   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7895   // Unless SwapSelectOps says the condition should be false.
7896   if (SwapSelectOps)
7897     std::swap(TrueVal, FalseVal);
7898 
7899   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7900     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7901                        {Slct.getOperand(0), Slct.getOperand(1),
7902                         Slct.getOperand(2), TrueVal, FalseVal});
7903 
7904   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7905                      {Slct.getOperand(0), TrueVal, FalseVal});
7906 }
7907 
7908 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7909 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7910                                               bool AllOnes) {
7911   SDValue N0 = N->getOperand(0);
7912   SDValue N1 = N->getOperand(1);
7913   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7914     return Result;
7915   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7916     return Result;
7917   return SDValue();
7918 }
7919 
7920 // Transform (add (mul x, c0), c1) ->
7921 //           (add (mul (add x, c1/c0), c0), c1%c0).
7922 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7923 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7924 // to an infinite loop in DAGCombine if transformed.
7925 // Or transform (add (mul x, c0), c1) ->
7926 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7927 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7928 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7929 // lead to an infinite loop in DAGCombine if transformed.
7930 // Or transform (add (mul x, c0), c1) ->
7931 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7932 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7933 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7934 // lead to an infinite loop in DAGCombine if transformed.
7935 // Or transform (add (mul x, c0), c1) ->
7936 //              (mul (add x, c1/c0), c0).
7937 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7938 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7939                                      const RISCVSubtarget &Subtarget) {
7940   // Skip for vector types and larger types.
7941   EVT VT = N->getValueType(0);
7942   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7943     return SDValue();
7944   // The first operand node must be a MUL and has no other use.
7945   SDValue N0 = N->getOperand(0);
7946   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7947     return SDValue();
7948   // Check if c0 and c1 match above conditions.
7949   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7950   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7951   if (!N0C || !N1C)
7952     return SDValue();
7953   // If N0C has multiple uses it's possible one of the cases in
7954   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7955   // in an infinite loop.
7956   if (!N0C->hasOneUse())
7957     return SDValue();
7958   int64_t C0 = N0C->getSExtValue();
7959   int64_t C1 = N1C->getSExtValue();
7960   int64_t CA, CB;
7961   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7962     return SDValue();
7963   // Search for proper CA (non-zero) and CB that both are simm12.
7964   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7965       !isInt<12>(C0 * (C1 / C0))) {
7966     CA = C1 / C0;
7967     CB = C1 % C0;
7968   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7969              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7970     CA = C1 / C0 + 1;
7971     CB = C1 % C0 - C0;
7972   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7973              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7974     CA = C1 / C0 - 1;
7975     CB = C1 % C0 + C0;
7976   } else
7977     return SDValue();
7978   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7979   SDLoc DL(N);
7980   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7981                              DAG.getConstant(CA, DL, VT));
7982   SDValue New1 =
7983       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7984   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7985 }
7986 
7987 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7988                                  const RISCVSubtarget &Subtarget) {
7989   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7990     return V;
7991   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7992     return V;
7993   if (SDValue V = combineBinOpToReduce(N, DAG))
7994     return V;
7995   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7996   //      (select lhs, rhs, cc, x, (add x, y))
7997   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7998 }
7999 
8000 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
8001   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
8002   //      (select lhs, rhs, cc, x, (sub x, y))
8003   SDValue N0 = N->getOperand(0);
8004   SDValue N1 = N->getOperand(1);
8005   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
8006 }
8007 
8008 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
8009                                  const RISCVSubtarget &Subtarget) {
8010   SDValue N0 = N->getOperand(0);
8011   // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero
8012   // extending X. This is safe since we only need the LSB after the shift and
8013   // shift amounts larger than 31 would produce poison. If we wait until
8014   // type legalization, we'll create RISCVISD::SRLW and we can't recover it
8015   // to use a BEXT instruction.
8016   if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() &&
8017       N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) &&
8018       N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) &&
8019       N0.hasOneUse()) {
8020     SDLoc DL(N);
8021     SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0));
8022     SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1));
8023     SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1);
8024     SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl,
8025                               DAG.getConstant(1, DL, MVT::i64));
8026     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And);
8027   }
8028 
8029   if (SDValue V = combineBinOpToReduce(N, DAG))
8030     return V;
8031 
8032   // fold (and (select lhs, rhs, cc, -1, y), x) ->
8033   //      (select lhs, rhs, cc, x, (and x, y))
8034   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
8035 }
8036 
8037 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
8038                                 const RISCVSubtarget &Subtarget) {
8039   if (Subtarget.hasStdExtZbp()) {
8040     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
8041       return GREV;
8042     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
8043       return GORC;
8044     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
8045       return SHFL;
8046   }
8047 
8048   if (SDValue V = combineBinOpToReduce(N, DAG))
8049     return V;
8050   // fold (or (select cond, 0, y), x) ->
8051   //      (select cond, x, (or x, y))
8052   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8053 }
8054 
8055 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
8056   SDValue N0 = N->getOperand(0);
8057   SDValue N1 = N->getOperand(1);
8058 
8059   // fold (xor (sllw 1, x), -1) -> (rolw ~1, x)
8060   // NOTE: Assumes ROL being legal means ROLW is legal.
8061   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8062   if (N0.getOpcode() == RISCVISD::SLLW &&
8063       isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) &&
8064       TLI.isOperationLegal(ISD::ROTL, MVT::i64)) {
8065     SDLoc DL(N);
8066     return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64,
8067                        DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1));
8068   }
8069 
8070   if (SDValue V = combineBinOpToReduce(N, DAG))
8071     return V;
8072   // fold (xor (select cond, 0, y), x) ->
8073   //      (select cond, x, (xor x, y))
8074   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8075 }
8076 
8077 static SDValue
8078 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
8079                                 const RISCVSubtarget &Subtarget) {
8080   SDValue Src = N->getOperand(0);
8081   EVT VT = N->getValueType(0);
8082 
8083   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
8084   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8085       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
8086     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
8087                        Src.getOperand(0));
8088 
8089   // Fold (i64 (sext_inreg (abs X), i32)) ->
8090   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
8091   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
8092   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
8093   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
8094   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
8095   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
8096   // may get combined into an earlier operation so we need to use
8097   // ComputeNumSignBits.
8098   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
8099   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
8100   // we can't assume that X has 33 sign bits. We must check.
8101   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
8102       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
8103       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
8104       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
8105     SDLoc DL(N);
8106     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
8107     SDValue Neg =
8108         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
8109     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
8110                       DAG.getValueType(MVT::i32));
8111     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
8112   }
8113 
8114   return SDValue();
8115 }
8116 
8117 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
8118 // vwadd(u).vv/vx or vwsub(u).vv/vx.
8119 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
8120                                              bool Commute = false) {
8121   assert((N->getOpcode() == RISCVISD::ADD_VL ||
8122           N->getOpcode() == RISCVISD::SUB_VL) &&
8123          "Unexpected opcode");
8124   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
8125   SDValue Op0 = N->getOperand(0);
8126   SDValue Op1 = N->getOperand(1);
8127   if (Commute)
8128     std::swap(Op0, Op1);
8129 
8130   MVT VT = N->getSimpleValueType(0);
8131 
8132   // Determine the narrow size for a widening add/sub.
8133   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8134   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8135                                   VT.getVectorElementCount());
8136 
8137   SDValue Mask = N->getOperand(2);
8138   SDValue VL = N->getOperand(3);
8139 
8140   SDLoc DL(N);
8141 
8142   // If the RHS is a sext or zext, we can form a widening op.
8143   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
8144        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
8145       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
8146     unsigned ExtOpc = Op1.getOpcode();
8147     Op1 = Op1.getOperand(0);
8148     // Re-introduce narrower extends if needed.
8149     if (Op1.getValueType() != NarrowVT)
8150       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8151 
8152     unsigned WOpc;
8153     if (ExtOpc == RISCVISD::VSEXT_VL)
8154       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
8155     else
8156       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
8157 
8158     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
8159   }
8160 
8161   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
8162   // sext/zext?
8163 
8164   return SDValue();
8165 }
8166 
8167 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
8168 // vwsub(u).vv/vx.
8169 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
8170   SDValue Op0 = N->getOperand(0);
8171   SDValue Op1 = N->getOperand(1);
8172   SDValue Mask = N->getOperand(2);
8173   SDValue VL = N->getOperand(3);
8174 
8175   MVT VT = N->getSimpleValueType(0);
8176   MVT NarrowVT = Op1.getSimpleValueType();
8177   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
8178 
8179   unsigned VOpc;
8180   switch (N->getOpcode()) {
8181   default: llvm_unreachable("Unexpected opcode");
8182   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
8183   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
8184   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
8185   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
8186   }
8187 
8188   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8189                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
8190 
8191   SDLoc DL(N);
8192 
8193   // If the LHS is a sext or zext, we can narrow this op to the same size as
8194   // the RHS.
8195   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
8196        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
8197       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
8198     unsigned ExtOpc = Op0.getOpcode();
8199     Op0 = Op0.getOperand(0);
8200     // Re-introduce narrower extends if needed.
8201     if (Op0.getValueType() != NarrowVT)
8202       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8203     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
8204   }
8205 
8206   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8207                N->getOpcode() == RISCVISD::VWADDU_W_VL;
8208 
8209   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
8210   // to commute and use a vwadd(u).vx instead.
8211   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
8212       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
8213     Op0 = Op0.getOperand(1);
8214 
8215     // See if have enough sign bits or zero bits in the scalar to use a
8216     // widening add/sub by splatting to smaller element size.
8217     unsigned EltBits = VT.getScalarSizeInBits();
8218     unsigned ScalarBits = Op0.getValueSizeInBits();
8219     // Make sure we're getting all element bits from the scalar register.
8220     // FIXME: Support implicit sign extension of vmv.v.x?
8221     if (ScalarBits < EltBits)
8222       return SDValue();
8223 
8224     if (IsSigned) {
8225       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
8226         return SDValue();
8227     } else {
8228       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8229       if (!DAG.MaskedValueIsZero(Op0, Mask))
8230         return SDValue();
8231     }
8232 
8233     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8234                       DAG.getUNDEF(NarrowVT), Op0, VL);
8235     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
8236   }
8237 
8238   return SDValue();
8239 }
8240 
8241 // Try to form VWMUL, VWMULU or VWMULSU.
8242 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
8243 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
8244                                        bool Commute) {
8245   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
8246   SDValue Op0 = N->getOperand(0);
8247   SDValue Op1 = N->getOperand(1);
8248   if (Commute)
8249     std::swap(Op0, Op1);
8250 
8251   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
8252   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
8253   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
8254   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
8255     return SDValue();
8256 
8257   SDValue Mask = N->getOperand(2);
8258   SDValue VL = N->getOperand(3);
8259 
8260   // Make sure the mask and VL match.
8261   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8262     return SDValue();
8263 
8264   MVT VT = N->getSimpleValueType(0);
8265 
8266   // Determine the narrow size for a widening multiply.
8267   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8268   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8269                                   VT.getVectorElementCount());
8270 
8271   SDLoc DL(N);
8272 
8273   // See if the other operand is the same opcode.
8274   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8275     if (!Op1.hasOneUse())
8276       return SDValue();
8277 
8278     // Make sure the mask and VL match.
8279     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8280       return SDValue();
8281 
8282     Op1 = Op1.getOperand(0);
8283   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8284     // The operand is a splat of a scalar.
8285 
8286     // The pasthru must be undef for tail agnostic
8287     if (!Op1.getOperand(0).isUndef())
8288       return SDValue();
8289     // The VL must be the same.
8290     if (Op1.getOperand(2) != VL)
8291       return SDValue();
8292 
8293     // Get the scalar value.
8294     Op1 = Op1.getOperand(1);
8295 
8296     // See if have enough sign bits or zero bits in the scalar to use a
8297     // widening multiply by splatting to smaller element size.
8298     unsigned EltBits = VT.getScalarSizeInBits();
8299     unsigned ScalarBits = Op1.getValueSizeInBits();
8300     // Make sure we're getting all element bits from the scalar register.
8301     // FIXME: Support implicit sign extension of vmv.v.x?
8302     if (ScalarBits < EltBits)
8303       return SDValue();
8304 
8305     // If the LHS is a sign extend, try to use vwmul.
8306     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8307       // Can use vwmul.
8308     } else {
8309       // Otherwise try to use vwmulu or vwmulsu.
8310       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8311       if (DAG.MaskedValueIsZero(Op1, Mask))
8312         IsVWMULSU = IsSignExt;
8313       else
8314         return SDValue();
8315     }
8316 
8317     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8318                       DAG.getUNDEF(NarrowVT), Op1, VL);
8319   } else
8320     return SDValue();
8321 
8322   Op0 = Op0.getOperand(0);
8323 
8324   // Re-introduce narrower extends if needed.
8325   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8326   if (Op0.getValueType() != NarrowVT)
8327     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8328   // vwmulsu requires second operand to be zero extended.
8329   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8330   if (Op1.getValueType() != NarrowVT)
8331     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8332 
8333   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8334   if (!IsVWMULSU)
8335     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8336   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8337 }
8338 
8339 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8340   switch (Op.getOpcode()) {
8341   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8342   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8343   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8344   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8345   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8346   }
8347 
8348   return RISCVFPRndMode::Invalid;
8349 }
8350 
8351 // Fold
8352 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8353 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8354 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8355 //   (fp_to_int (fceil X))      -> fcvt X, rup
8356 //   (fp_to_int (fround X))     -> fcvt X, rmm
8357 static SDValue performFP_TO_INTCombine(SDNode *N,
8358                                        TargetLowering::DAGCombinerInfo &DCI,
8359                                        const RISCVSubtarget &Subtarget) {
8360   SelectionDAG &DAG = DCI.DAG;
8361   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8362   MVT XLenVT = Subtarget.getXLenVT();
8363 
8364   // Only handle XLen or i32 types. Other types narrower than XLen will
8365   // eventually be legalized to XLenVT.
8366   EVT VT = N->getValueType(0);
8367   if (VT != MVT::i32 && VT != XLenVT)
8368     return SDValue();
8369 
8370   SDValue Src = N->getOperand(0);
8371 
8372   // Ensure the FP type is also legal.
8373   if (!TLI.isTypeLegal(Src.getValueType()))
8374     return SDValue();
8375 
8376   // Don't do this for f16 with Zfhmin and not Zfh.
8377   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8378     return SDValue();
8379 
8380   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8381   if (FRM == RISCVFPRndMode::Invalid)
8382     return SDValue();
8383 
8384   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8385 
8386   unsigned Opc;
8387   if (VT == XLenVT)
8388     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8389   else
8390     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8391 
8392   SDLoc DL(N);
8393   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8394                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8395   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8396 }
8397 
8398 // Fold
8399 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8400 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8401 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8402 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8403 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8404 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8405                                        TargetLowering::DAGCombinerInfo &DCI,
8406                                        const RISCVSubtarget &Subtarget) {
8407   SelectionDAG &DAG = DCI.DAG;
8408   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8409   MVT XLenVT = Subtarget.getXLenVT();
8410 
8411   // Only handle XLen types. Other types narrower than XLen will eventually be
8412   // legalized to XLenVT.
8413   EVT DstVT = N->getValueType(0);
8414   if (DstVT != XLenVT)
8415     return SDValue();
8416 
8417   SDValue Src = N->getOperand(0);
8418 
8419   // Ensure the FP type is also legal.
8420   if (!TLI.isTypeLegal(Src.getValueType()))
8421     return SDValue();
8422 
8423   // Don't do this for f16 with Zfhmin and not Zfh.
8424   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8425     return SDValue();
8426 
8427   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8428 
8429   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8430   if (FRM == RISCVFPRndMode::Invalid)
8431     return SDValue();
8432 
8433   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8434 
8435   unsigned Opc;
8436   if (SatVT == DstVT)
8437     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8438   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8439     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8440   else
8441     return SDValue();
8442   // FIXME: Support other SatVTs by clamping before or after the conversion.
8443 
8444   Src = Src.getOperand(0);
8445 
8446   SDLoc DL(N);
8447   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8448                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8449 
8450   // RISCV FP-to-int conversions saturate to the destination register size, but
8451   // don't produce 0 for nan.
8452   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8453   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8454 }
8455 
8456 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8457 // smaller than XLenVT.
8458 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8459                                         const RISCVSubtarget &Subtarget) {
8460   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8461 
8462   SDValue Src = N->getOperand(0);
8463   if (Src.getOpcode() != ISD::BSWAP)
8464     return SDValue();
8465 
8466   EVT VT = N->getValueType(0);
8467   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8468       !isPowerOf2_32(VT.getSizeInBits()))
8469     return SDValue();
8470 
8471   SDLoc DL(N);
8472   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8473                      DAG.getConstant(7, DL, VT));
8474 }
8475 
8476 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8477                                                DAGCombinerInfo &DCI) const {
8478   SelectionDAG &DAG = DCI.DAG;
8479 
8480   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8481   // bits are demanded. N will be added to the Worklist if it was not deleted.
8482   // Caller should return SDValue(N, 0) if this returns true.
8483   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8484     SDValue Op = N->getOperand(OpNo);
8485     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8486     if (!SimplifyDemandedBits(Op, Mask, DCI))
8487       return false;
8488 
8489     if (N->getOpcode() != ISD::DELETED_NODE)
8490       DCI.AddToWorklist(N);
8491     return true;
8492   };
8493 
8494   switch (N->getOpcode()) {
8495   default:
8496     break;
8497   case RISCVISD::SplitF64: {
8498     SDValue Op0 = N->getOperand(0);
8499     // If the input to SplitF64 is just BuildPairF64 then the operation is
8500     // redundant. Instead, use BuildPairF64's operands directly.
8501     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8502       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8503 
8504     if (Op0->isUndef()) {
8505       SDValue Lo = DAG.getUNDEF(MVT::i32);
8506       SDValue Hi = DAG.getUNDEF(MVT::i32);
8507       return DCI.CombineTo(N, Lo, Hi);
8508     }
8509 
8510     SDLoc DL(N);
8511 
8512     // It's cheaper to materialise two 32-bit integers than to load a double
8513     // from the constant pool and transfer it to integer registers through the
8514     // stack.
8515     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8516       APInt V = C->getValueAPF().bitcastToAPInt();
8517       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8518       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8519       return DCI.CombineTo(N, Lo, Hi);
8520     }
8521 
8522     // This is a target-specific version of a DAGCombine performed in
8523     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8524     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8525     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8526     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8527         !Op0.getNode()->hasOneUse())
8528       break;
8529     SDValue NewSplitF64 =
8530         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8531                     Op0.getOperand(0));
8532     SDValue Lo = NewSplitF64.getValue(0);
8533     SDValue Hi = NewSplitF64.getValue(1);
8534     APInt SignBit = APInt::getSignMask(32);
8535     if (Op0.getOpcode() == ISD::FNEG) {
8536       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8537                                   DAG.getConstant(SignBit, DL, MVT::i32));
8538       return DCI.CombineTo(N, Lo, NewHi);
8539     }
8540     assert(Op0.getOpcode() == ISD::FABS);
8541     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8542                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8543     return DCI.CombineTo(N, Lo, NewHi);
8544   }
8545   case RISCVISD::SLLW:
8546   case RISCVISD::SRAW:
8547   case RISCVISD::SRLW: {
8548     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8549     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8550         SimplifyDemandedLowBitsHelper(1, 5))
8551       return SDValue(N, 0);
8552 
8553     break;
8554   }
8555   case ISD::ROTR:
8556   case ISD::ROTL:
8557   case RISCVISD::RORW:
8558   case RISCVISD::ROLW: {
8559     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8560       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8561       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8562           SimplifyDemandedLowBitsHelper(1, 5))
8563         return SDValue(N, 0);
8564     }
8565 
8566     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8567   }
8568   case RISCVISD::CLZW:
8569   case RISCVISD::CTZW: {
8570     // Only the lower 32 bits of the first operand are read
8571     if (SimplifyDemandedLowBitsHelper(0, 32))
8572       return SDValue(N, 0);
8573     break;
8574   }
8575   case RISCVISD::GREV:
8576   case RISCVISD::GORC: {
8577     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8578     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8579     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8580     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8581       return SDValue(N, 0);
8582 
8583     return combineGREVI_GORCI(N, DAG);
8584   }
8585   case RISCVISD::GREVW:
8586   case RISCVISD::GORCW: {
8587     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8588     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8589         SimplifyDemandedLowBitsHelper(1, 5))
8590       return SDValue(N, 0);
8591 
8592     break;
8593   }
8594   case RISCVISD::SHFL:
8595   case RISCVISD::UNSHFL: {
8596     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8597     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8598     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8599     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8600       return SDValue(N, 0);
8601 
8602     break;
8603   }
8604   case RISCVISD::SHFLW:
8605   case RISCVISD::UNSHFLW: {
8606     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8607     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8608         SimplifyDemandedLowBitsHelper(1, 4))
8609       return SDValue(N, 0);
8610 
8611     break;
8612   }
8613   case RISCVISD::BCOMPRESSW:
8614   case RISCVISD::BDECOMPRESSW: {
8615     // Only the lower 32 bits of LHS and RHS are read.
8616     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8617         SimplifyDemandedLowBitsHelper(1, 32))
8618       return SDValue(N, 0);
8619 
8620     break;
8621   }
8622   case RISCVISD::FSR:
8623   case RISCVISD::FSL:
8624   case RISCVISD::FSRW:
8625   case RISCVISD::FSLW: {
8626     bool IsWInstruction =
8627         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8628     unsigned BitWidth =
8629         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8630     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8631     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8632     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8633       return SDValue(N, 0);
8634 
8635     break;
8636   }
8637   case RISCVISD::FMV_X_ANYEXTH:
8638   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8639     SDLoc DL(N);
8640     SDValue Op0 = N->getOperand(0);
8641     MVT VT = N->getSimpleValueType(0);
8642     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8643     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8644     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8645     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8646          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8647         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8648          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8649       assert(Op0.getOperand(0).getValueType() == VT &&
8650              "Unexpected value type!");
8651       return Op0.getOperand(0);
8652     }
8653 
8654     // This is a target-specific version of a DAGCombine performed in
8655     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8656     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8657     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8658     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8659         !Op0.getNode()->hasOneUse())
8660       break;
8661     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8662     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8663     APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits());
8664     if (Op0.getOpcode() == ISD::FNEG)
8665       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8666                          DAG.getConstant(SignBit, DL, VT));
8667 
8668     assert(Op0.getOpcode() == ISD::FABS);
8669     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8670                        DAG.getConstant(~SignBit, DL, VT));
8671   }
8672   case ISD::ADD:
8673     return performADDCombine(N, DAG, Subtarget);
8674   case ISD::SUB:
8675     return performSUBCombine(N, DAG);
8676   case ISD::AND:
8677     return performANDCombine(N, DAG, Subtarget);
8678   case ISD::OR:
8679     return performORCombine(N, DAG, Subtarget);
8680   case ISD::XOR:
8681     return performXORCombine(N, DAG);
8682   case ISD::FADD:
8683   case ISD::UMAX:
8684   case ISD::UMIN:
8685   case ISD::SMAX:
8686   case ISD::SMIN:
8687   case ISD::FMAXNUM:
8688   case ISD::FMINNUM:
8689     return combineBinOpToReduce(N, DAG);
8690   case ISD::SIGN_EXTEND_INREG:
8691     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8692   case ISD::ZERO_EXTEND:
8693     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8694     // type legalization. This is safe because fp_to_uint produces poison if
8695     // it overflows.
8696     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8697       SDValue Src = N->getOperand(0);
8698       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8699           isTypeLegal(Src.getOperand(0).getValueType()))
8700         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8701                            Src.getOperand(0));
8702       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8703           isTypeLegal(Src.getOperand(1).getValueType())) {
8704         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8705         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8706                                   Src.getOperand(0), Src.getOperand(1));
8707         DCI.CombineTo(N, Res);
8708         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8709         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8710         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8711       }
8712     }
8713     return SDValue();
8714   case RISCVISD::SELECT_CC: {
8715     // Transform
8716     SDValue LHS = N->getOperand(0);
8717     SDValue RHS = N->getOperand(1);
8718     SDValue TrueV = N->getOperand(3);
8719     SDValue FalseV = N->getOperand(4);
8720 
8721     // If the True and False values are the same, we don't need a select_cc.
8722     if (TrueV == FalseV)
8723       return TrueV;
8724 
8725     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8726     if (!ISD::isIntEqualitySetCC(CCVal))
8727       break;
8728 
8729     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8730     //      (select_cc X, Y, lt, trueV, falseV)
8731     // Sometimes the setcc is introduced after select_cc has been formed.
8732     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8733         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8734       // If we're looking for eq 0 instead of ne 0, we need to invert the
8735       // condition.
8736       bool Invert = CCVal == ISD::SETEQ;
8737       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8738       if (Invert)
8739         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8740 
8741       SDLoc DL(N);
8742       RHS = LHS.getOperand(1);
8743       LHS = LHS.getOperand(0);
8744       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8745 
8746       SDValue TargetCC = DAG.getCondCode(CCVal);
8747       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8748                          {LHS, RHS, TargetCC, TrueV, FalseV});
8749     }
8750 
8751     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8752     //      (select_cc X, Y, eq/ne, trueV, falseV)
8753     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8754       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8755                          {LHS.getOperand(0), LHS.getOperand(1),
8756                           N->getOperand(2), TrueV, FalseV});
8757     // (select_cc X, 1, setne, trueV, falseV) ->
8758     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8759     // This can occur when legalizing some floating point comparisons.
8760     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8761     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8762       SDLoc DL(N);
8763       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8764       SDValue TargetCC = DAG.getCondCode(CCVal);
8765       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8766       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8767                          {LHS, RHS, TargetCC, TrueV, FalseV});
8768     }
8769 
8770     break;
8771   }
8772   case RISCVISD::BR_CC: {
8773     SDValue LHS = N->getOperand(1);
8774     SDValue RHS = N->getOperand(2);
8775     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8776     if (!ISD::isIntEqualitySetCC(CCVal))
8777       break;
8778 
8779     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8780     //      (br_cc X, Y, lt, dest)
8781     // Sometimes the setcc is introduced after br_cc has been formed.
8782     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8783         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8784       // If we're looking for eq 0 instead of ne 0, we need to invert the
8785       // condition.
8786       bool Invert = CCVal == ISD::SETEQ;
8787       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8788       if (Invert)
8789         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8790 
8791       SDLoc DL(N);
8792       RHS = LHS.getOperand(1);
8793       LHS = LHS.getOperand(0);
8794       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8795 
8796       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8797                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8798                          N->getOperand(4));
8799     }
8800 
8801     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8802     //      (br_cc X, Y, eq/ne, trueV, falseV)
8803     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8804       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8805                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8806                          N->getOperand(3), N->getOperand(4));
8807 
8808     // (br_cc X, 1, setne, br_cc) ->
8809     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8810     // This can occur when legalizing some floating point comparisons.
8811     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8812     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8813       SDLoc DL(N);
8814       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8815       SDValue TargetCC = DAG.getCondCode(CCVal);
8816       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8817       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8818                          N->getOperand(0), LHS, RHS, TargetCC,
8819                          N->getOperand(4));
8820     }
8821     break;
8822   }
8823   case ISD::BITREVERSE:
8824     return performBITREVERSECombine(N, DAG, Subtarget);
8825   case ISD::FP_TO_SINT:
8826   case ISD::FP_TO_UINT:
8827     return performFP_TO_INTCombine(N, DCI, Subtarget);
8828   case ISD::FP_TO_SINT_SAT:
8829   case ISD::FP_TO_UINT_SAT:
8830     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8831   case ISD::FCOPYSIGN: {
8832     EVT VT = N->getValueType(0);
8833     if (!VT.isVector())
8834       break;
8835     // There is a form of VFSGNJ which injects the negated sign of its second
8836     // operand. Try and bubble any FNEG up after the extend/round to produce
8837     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8838     // TRUNC=1.
8839     SDValue In2 = N->getOperand(1);
8840     // Avoid cases where the extend/round has multiple uses, as duplicating
8841     // those is typically more expensive than removing a fneg.
8842     if (!In2.hasOneUse())
8843       break;
8844     if (In2.getOpcode() != ISD::FP_EXTEND &&
8845         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8846       break;
8847     In2 = In2.getOperand(0);
8848     if (In2.getOpcode() != ISD::FNEG)
8849       break;
8850     SDLoc DL(N);
8851     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8852     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8853                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8854   }
8855   case ISD::MGATHER:
8856   case ISD::MSCATTER:
8857   case ISD::VP_GATHER:
8858   case ISD::VP_SCATTER: {
8859     if (!DCI.isBeforeLegalize())
8860       break;
8861     SDValue Index, ScaleOp;
8862     bool IsIndexScaled = false;
8863     bool IsIndexSigned = false;
8864     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8865       Index = VPGSN->getIndex();
8866       ScaleOp = VPGSN->getScale();
8867       IsIndexScaled = VPGSN->isIndexScaled();
8868       IsIndexSigned = VPGSN->isIndexSigned();
8869     } else {
8870       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8871       Index = MGSN->getIndex();
8872       ScaleOp = MGSN->getScale();
8873       IsIndexScaled = MGSN->isIndexScaled();
8874       IsIndexSigned = MGSN->isIndexSigned();
8875     }
8876     EVT IndexVT = Index.getValueType();
8877     MVT XLenVT = Subtarget.getXLenVT();
8878     // RISCV indexed loads only support the "unsigned unscaled" addressing
8879     // mode, so anything else must be manually legalized.
8880     bool NeedsIdxLegalization =
8881         IsIndexScaled ||
8882         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8883     if (!NeedsIdxLegalization)
8884       break;
8885 
8886     SDLoc DL(N);
8887 
8888     // Any index legalization should first promote to XLenVT, so we don't lose
8889     // bits when scaling. This may create an illegal index type so we let
8890     // LLVM's legalization take care of the splitting.
8891     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8892     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8893       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8894       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8895                           DL, IndexVT, Index);
8896     }
8897 
8898     if (IsIndexScaled) {
8899       // Manually scale the indices.
8900       // TODO: Sanitize the scale operand here?
8901       // TODO: For VP nodes, should we use VP_SHL here?
8902       unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8903       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8904       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8905       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8906       ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType());
8907     }
8908 
8909     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED;
8910     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8911       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8912                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8913                               ScaleOp, VPGN->getMask(),
8914                               VPGN->getVectorLength()},
8915                              VPGN->getMemOperand(), NewIndexTy);
8916     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8917       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8918                               {VPSN->getChain(), VPSN->getValue(),
8919                                VPSN->getBasePtr(), Index, ScaleOp,
8920                                VPSN->getMask(), VPSN->getVectorLength()},
8921                               VPSN->getMemOperand(), NewIndexTy);
8922     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8923       return DAG.getMaskedGather(
8924           N->getVTList(), MGN->getMemoryVT(), DL,
8925           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8926            MGN->getBasePtr(), Index, ScaleOp},
8927           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8928     const auto *MSN = cast<MaskedScatterSDNode>(N);
8929     return DAG.getMaskedScatter(
8930         N->getVTList(), MSN->getMemoryVT(), DL,
8931         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8932          Index, ScaleOp},
8933         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8934   }
8935   case RISCVISD::SRA_VL:
8936   case RISCVISD::SRL_VL:
8937   case RISCVISD::SHL_VL: {
8938     SDValue ShAmt = N->getOperand(1);
8939     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8940       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8941       SDLoc DL(N);
8942       SDValue VL = N->getOperand(3);
8943       EVT VT = N->getValueType(0);
8944       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8945                           ShAmt.getOperand(1), VL);
8946       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8947                          N->getOperand(2), N->getOperand(3));
8948     }
8949     break;
8950   }
8951   case ISD::SRA:
8952   case ISD::SRL:
8953   case ISD::SHL: {
8954     SDValue ShAmt = N->getOperand(1);
8955     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8956       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8957       SDLoc DL(N);
8958       EVT VT = N->getValueType(0);
8959       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8960                           ShAmt.getOperand(1),
8961                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8962       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8963     }
8964     break;
8965   }
8966   case RISCVISD::ADD_VL:
8967     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8968       return V;
8969     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8970   case RISCVISD::SUB_VL:
8971     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8972   case RISCVISD::VWADD_W_VL:
8973   case RISCVISD::VWADDU_W_VL:
8974   case RISCVISD::VWSUB_W_VL:
8975   case RISCVISD::VWSUBU_W_VL:
8976     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8977   case RISCVISD::MUL_VL:
8978     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8979       return V;
8980     // Mul is commutative.
8981     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8982   case ISD::STORE: {
8983     auto *Store = cast<StoreSDNode>(N);
8984     SDValue Val = Store->getValue();
8985     // Combine store of vmv.x.s to vse with VL of 1.
8986     // FIXME: Support FP.
8987     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8988       SDValue Src = Val.getOperand(0);
8989       EVT VecVT = Src.getValueType();
8990       EVT MemVT = Store->getMemoryVT();
8991       // The memory VT and the element type must match.
8992       if (VecVT.getVectorElementType() == MemVT) {
8993         SDLoc DL(N);
8994         MVT MaskVT = getMaskTypeFor(VecVT);
8995         return DAG.getStoreVP(
8996             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8997             DAG.getConstant(1, DL, MaskVT),
8998             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8999             Store->getMemOperand(), Store->getAddressingMode(),
9000             Store->isTruncatingStore(), /*IsCompress*/ false);
9001       }
9002     }
9003 
9004     break;
9005   }
9006   case ISD::SPLAT_VECTOR: {
9007     EVT VT = N->getValueType(0);
9008     // Only perform this combine on legal MVT types.
9009     if (!isTypeLegal(VT))
9010       break;
9011     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
9012                                          DAG, Subtarget))
9013       return Gather;
9014     break;
9015   }
9016   case RISCVISD::VMV_V_X_VL: {
9017     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
9018     // scalar input.
9019     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
9020     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
9021     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
9022       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
9023         return SDValue(N, 0);
9024 
9025     break;
9026   }
9027   case ISD::INTRINSIC_WO_CHAIN: {
9028     unsigned IntNo = N->getConstantOperandVal(0);
9029     switch (IntNo) {
9030       // By default we do not combine any intrinsic.
9031     default:
9032       return SDValue();
9033     case Intrinsic::riscv_vcpop:
9034     case Intrinsic::riscv_vcpop_mask:
9035     case Intrinsic::riscv_vfirst:
9036     case Intrinsic::riscv_vfirst_mask: {
9037       SDValue VL = N->getOperand(2);
9038       if (IntNo == Intrinsic::riscv_vcpop_mask ||
9039           IntNo == Intrinsic::riscv_vfirst_mask)
9040         VL = N->getOperand(3);
9041       if (!isNullConstant(VL))
9042         return SDValue();
9043       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
9044       SDLoc DL(N);
9045       EVT VT = N->getValueType(0);
9046       if (IntNo == Intrinsic::riscv_vfirst ||
9047           IntNo == Intrinsic::riscv_vfirst_mask)
9048         return DAG.getConstant(-1, DL, VT);
9049       return DAG.getConstant(0, DL, VT);
9050     }
9051     }
9052   }
9053   case ISD::BITCAST: {
9054     assert(Subtarget.useRVVForFixedLengthVectors());
9055     SDValue N0 = N->getOperand(0);
9056     EVT VT = N->getValueType(0);
9057     EVT SrcVT = N0.getValueType();
9058     // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer
9059     // type, widen both sides to avoid a trip through memory.
9060     if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) &&
9061         VT.isScalarInteger()) {
9062       unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
9063       SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
9064       Ops[0] = N0;
9065       SDLoc DL(N);
9066       N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops);
9067       N0 = DAG.getBitcast(MVT::i8, N0);
9068       return DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
9069     }
9070 
9071     return SDValue();
9072   }
9073   }
9074 
9075   return SDValue();
9076 }
9077 
9078 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
9079     const SDNode *N, CombineLevel Level) const {
9080   // The following folds are only desirable if `(OP _, c1 << c2)` can be
9081   // materialised in fewer instructions than `(OP _, c1)`:
9082   //
9083   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
9084   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
9085   SDValue N0 = N->getOperand(0);
9086   EVT Ty = N0.getValueType();
9087   if (Ty.isScalarInteger() &&
9088       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
9089     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9090     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
9091     if (C1 && C2) {
9092       const APInt &C1Int = C1->getAPIntValue();
9093       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
9094 
9095       // We can materialise `c1 << c2` into an add immediate, so it's "free",
9096       // and the combine should happen, to potentially allow further combines
9097       // later.
9098       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
9099           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
9100         return true;
9101 
9102       // We can materialise `c1` in an add immediate, so it's "free", and the
9103       // combine should be prevented.
9104       if (C1Int.getMinSignedBits() <= 64 &&
9105           isLegalAddImmediate(C1Int.getSExtValue()))
9106         return false;
9107 
9108       // Neither constant will fit into an immediate, so find materialisation
9109       // costs.
9110       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
9111                                               Subtarget.getFeatureBits(),
9112                                               /*CompressionCost*/true);
9113       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
9114           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
9115           /*CompressionCost*/true);
9116 
9117       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
9118       // combine should be prevented.
9119       if (C1Cost < ShiftedC1Cost)
9120         return false;
9121     }
9122   }
9123   return true;
9124 }
9125 
9126 bool RISCVTargetLowering::targetShrinkDemandedConstant(
9127     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
9128     TargetLoweringOpt &TLO) const {
9129   // Delay this optimization as late as possible.
9130   if (!TLO.LegalOps)
9131     return false;
9132 
9133   EVT VT = Op.getValueType();
9134   if (VT.isVector())
9135     return false;
9136 
9137   // Only handle AND for now.
9138   if (Op.getOpcode() != ISD::AND)
9139     return false;
9140 
9141   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9142   if (!C)
9143     return false;
9144 
9145   const APInt &Mask = C->getAPIntValue();
9146 
9147   // Clear all non-demanded bits initially.
9148   APInt ShrunkMask = Mask & DemandedBits;
9149 
9150   // Try to make a smaller immediate by setting undemanded bits.
9151 
9152   APInt ExpandedMask = Mask | ~DemandedBits;
9153 
9154   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
9155     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
9156   };
9157   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
9158     if (NewMask == Mask)
9159       return true;
9160     SDLoc DL(Op);
9161     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
9162     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
9163     return TLO.CombineTo(Op, NewOp);
9164   };
9165 
9166   // If the shrunk mask fits in sign extended 12 bits, let the target
9167   // independent code apply it.
9168   if (ShrunkMask.isSignedIntN(12))
9169     return false;
9170 
9171   // Preserve (and X, 0xffff) when zext.h is supported.
9172   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
9173     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
9174     if (IsLegalMask(NewMask))
9175       return UseMask(NewMask);
9176   }
9177 
9178   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
9179   if (VT == MVT::i64) {
9180     APInt NewMask = APInt(64, 0xffffffff);
9181     if (IsLegalMask(NewMask))
9182       return UseMask(NewMask);
9183   }
9184 
9185   // For the remaining optimizations, we need to be able to make a negative
9186   // number through a combination of mask and undemanded bits.
9187   if (!ExpandedMask.isNegative())
9188     return false;
9189 
9190   // What is the fewest number of bits we need to represent the negative number.
9191   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
9192 
9193   // Try to make a 12 bit negative immediate. If that fails try to make a 32
9194   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
9195   APInt NewMask = ShrunkMask;
9196   if (MinSignedBits <= 12)
9197     NewMask.setBitsFrom(11);
9198   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
9199     NewMask.setBitsFrom(31);
9200   else
9201     return false;
9202 
9203   // Check that our new mask is a subset of the demanded mask.
9204   assert(IsLegalMask(NewMask));
9205   return UseMask(NewMask);
9206 }
9207 
9208 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
9209   static const uint64_t GREVMasks[] = {
9210       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
9211       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
9212 
9213   for (unsigned Stage = 0; Stage != 6; ++Stage) {
9214     unsigned Shift = 1 << Stage;
9215     if (ShAmt & Shift) {
9216       uint64_t Mask = GREVMasks[Stage];
9217       uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
9218       if (IsGORC)
9219         Res |= x;
9220       x = Res;
9221     }
9222   }
9223 
9224   return x;
9225 }
9226 
9227 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9228                                                         KnownBits &Known,
9229                                                         const APInt &DemandedElts,
9230                                                         const SelectionDAG &DAG,
9231                                                         unsigned Depth) const {
9232   unsigned BitWidth = Known.getBitWidth();
9233   unsigned Opc = Op.getOpcode();
9234   assert((Opc >= ISD::BUILTIN_OP_END ||
9235           Opc == ISD::INTRINSIC_WO_CHAIN ||
9236           Opc == ISD::INTRINSIC_W_CHAIN ||
9237           Opc == ISD::INTRINSIC_VOID) &&
9238          "Should use MaskedValueIsZero if you don't know whether Op"
9239          " is a target node!");
9240 
9241   Known.resetAll();
9242   switch (Opc) {
9243   default: break;
9244   case RISCVISD::SELECT_CC: {
9245     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
9246     // If we don't know any bits, early out.
9247     if (Known.isUnknown())
9248       break;
9249     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
9250 
9251     // Only known if known in both the LHS and RHS.
9252     Known = KnownBits::commonBits(Known, Known2);
9253     break;
9254   }
9255   case RISCVISD::REMUW: {
9256     KnownBits Known2;
9257     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9258     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9259     // We only care about the lower 32 bits.
9260     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
9261     // Restore the original width by sign extending.
9262     Known = Known.sext(BitWidth);
9263     break;
9264   }
9265   case RISCVISD::DIVUW: {
9266     KnownBits Known2;
9267     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9268     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9269     // We only care about the lower 32 bits.
9270     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
9271     // Restore the original width by sign extending.
9272     Known = Known.sext(BitWidth);
9273     break;
9274   }
9275   case RISCVISD::CTZW: {
9276     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9277     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
9278     unsigned LowBits = Log2_32(PossibleTZ) + 1;
9279     Known.Zero.setBitsFrom(LowBits);
9280     break;
9281   }
9282   case RISCVISD::CLZW: {
9283     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9284     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
9285     unsigned LowBits = Log2_32(PossibleLZ) + 1;
9286     Known.Zero.setBitsFrom(LowBits);
9287     break;
9288   }
9289   case RISCVISD::GREV:
9290   case RISCVISD::GORC: {
9291     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9292       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9293       unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1);
9294       bool IsGORC = Op.getOpcode() == RISCVISD::GORC;
9295       // To compute zeros, we need to invert the value and invert it back after.
9296       Known.Zero =
9297           ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC);
9298       Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC);
9299     }
9300     break;
9301   }
9302   case RISCVISD::READ_VLENB: {
9303     // If we know the minimum VLen from Zvl extensions, we can use that to
9304     // determine the trailing zeros of VLENB.
9305     // FIXME: Limit to 128 bit vectors until we have more testing.
9306     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
9307     if (MinVLenB > 0)
9308       Known.Zero.setLowBits(Log2_32(MinVLenB));
9309     // We assume VLENB is no more than 65536 / 8 bytes.
9310     Known.Zero.setBitsFrom(14);
9311     break;
9312   }
9313   case ISD::INTRINSIC_W_CHAIN:
9314   case ISD::INTRINSIC_WO_CHAIN: {
9315     unsigned IntNo =
9316         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9317     switch (IntNo) {
9318     default:
9319       // We can't do anything for most intrinsics.
9320       break;
9321     case Intrinsic::riscv_vsetvli:
9322     case Intrinsic::riscv_vsetvlimax:
9323     case Intrinsic::riscv_vsetvli_opt:
9324     case Intrinsic::riscv_vsetvlimax_opt:
9325       // Assume that VL output is positive and would fit in an int32_t.
9326       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9327       if (BitWidth >= 32)
9328         Known.Zero.setBitsFrom(31);
9329       break;
9330     }
9331     break;
9332   }
9333   }
9334 }
9335 
9336 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9337     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9338     unsigned Depth) const {
9339   switch (Op.getOpcode()) {
9340   default:
9341     break;
9342   case RISCVISD::SELECT_CC: {
9343     unsigned Tmp =
9344         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9345     if (Tmp == 1) return 1;  // Early out.
9346     unsigned Tmp2 =
9347         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9348     return std::min(Tmp, Tmp2);
9349   }
9350   case RISCVISD::SLLW:
9351   case RISCVISD::SRAW:
9352   case RISCVISD::SRLW:
9353   case RISCVISD::DIVW:
9354   case RISCVISD::DIVUW:
9355   case RISCVISD::REMUW:
9356   case RISCVISD::ROLW:
9357   case RISCVISD::RORW:
9358   case RISCVISD::GREVW:
9359   case RISCVISD::GORCW:
9360   case RISCVISD::FSLW:
9361   case RISCVISD::FSRW:
9362   case RISCVISD::SHFLW:
9363   case RISCVISD::UNSHFLW:
9364   case RISCVISD::BCOMPRESSW:
9365   case RISCVISD::BDECOMPRESSW:
9366   case RISCVISD::BFPW:
9367   case RISCVISD::FCVT_W_RV64:
9368   case RISCVISD::FCVT_WU_RV64:
9369   case RISCVISD::STRICT_FCVT_W_RV64:
9370   case RISCVISD::STRICT_FCVT_WU_RV64:
9371     // TODO: As the result is sign-extended, this is conservatively correct. A
9372     // more precise answer could be calculated for SRAW depending on known
9373     // bits in the shift amount.
9374     return 33;
9375   case RISCVISD::SHFL:
9376   case RISCVISD::UNSHFL: {
9377     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9378     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9379     // will stay within the upper 32 bits. If there were more than 32 sign bits
9380     // before there will be at least 33 sign bits after.
9381     if (Op.getValueType() == MVT::i64 &&
9382         isa<ConstantSDNode>(Op.getOperand(1)) &&
9383         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9384       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9385       if (Tmp > 32)
9386         return 33;
9387     }
9388     break;
9389   }
9390   case RISCVISD::VMV_X_S: {
9391     // The number of sign bits of the scalar result is computed by obtaining the
9392     // element type of the input vector operand, subtracting its width from the
9393     // XLEN, and then adding one (sign bit within the element type). If the
9394     // element type is wider than XLen, the least-significant XLEN bits are
9395     // taken.
9396     unsigned XLen = Subtarget.getXLen();
9397     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9398     if (EltBits <= XLen)
9399       return XLen - EltBits + 1;
9400     break;
9401   }
9402   }
9403 
9404   return 1;
9405 }
9406 
9407 const Constant *
9408 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const {
9409   assert(Ld && "Unexpected null LoadSDNode");
9410   if (!ISD::isNormalLoad(Ld))
9411     return nullptr;
9412 
9413   SDValue Ptr = Ld->getBasePtr();
9414 
9415   // Only constant pools with no offset are supported.
9416   auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * {
9417     auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
9418     if (!CNode || CNode->isMachineConstantPoolEntry() ||
9419         CNode->getOffset() != 0)
9420       return nullptr;
9421 
9422     return CNode;
9423   };
9424 
9425   // Simple case, LLA.
9426   if (Ptr.getOpcode() == RISCVISD::LLA) {
9427     auto *CNode = GetSupportedConstantPool(Ptr);
9428     if (!CNode || CNode->getTargetFlags() != 0)
9429       return nullptr;
9430 
9431     return CNode->getConstVal();
9432   }
9433 
9434   // Look for a HI and ADD_LO pair.
9435   if (Ptr.getOpcode() != RISCVISD::ADD_LO ||
9436       Ptr.getOperand(0).getOpcode() != RISCVISD::HI)
9437     return nullptr;
9438 
9439   auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1));
9440   auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0));
9441 
9442   if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO ||
9443       !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI)
9444     return nullptr;
9445 
9446   if (CNodeLo->getConstVal() != CNodeHi->getConstVal())
9447     return nullptr;
9448 
9449   return CNodeLo->getConstVal();
9450 }
9451 
9452 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9453                                                   MachineBasicBlock *BB) {
9454   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9455 
9456   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9457   // Should the count have wrapped while it was being read, we need to try
9458   // again.
9459   // ...
9460   // read:
9461   // rdcycleh x3 # load high word of cycle
9462   // rdcycle  x2 # load low word of cycle
9463   // rdcycleh x4 # load high word of cycle
9464   // bne x3, x4, read # check if high word reads match, otherwise try again
9465   // ...
9466 
9467   MachineFunction &MF = *BB->getParent();
9468   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9469   MachineFunction::iterator It = ++BB->getIterator();
9470 
9471   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9472   MF.insert(It, LoopMBB);
9473 
9474   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9475   MF.insert(It, DoneMBB);
9476 
9477   // Transfer the remainder of BB and its successor edges to DoneMBB.
9478   DoneMBB->splice(DoneMBB->begin(), BB,
9479                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9480   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9481 
9482   BB->addSuccessor(LoopMBB);
9483 
9484   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9485   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9486   Register LoReg = MI.getOperand(0).getReg();
9487   Register HiReg = MI.getOperand(1).getReg();
9488   DebugLoc DL = MI.getDebugLoc();
9489 
9490   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9491   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9492       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9493       .addReg(RISCV::X0);
9494   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9495       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9496       .addReg(RISCV::X0);
9497   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9498       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9499       .addReg(RISCV::X0);
9500 
9501   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9502       .addReg(HiReg)
9503       .addReg(ReadAgainReg)
9504       .addMBB(LoopMBB);
9505 
9506   LoopMBB->addSuccessor(LoopMBB);
9507   LoopMBB->addSuccessor(DoneMBB);
9508 
9509   MI.eraseFromParent();
9510 
9511   return DoneMBB;
9512 }
9513 
9514 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9515                                              MachineBasicBlock *BB) {
9516   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9517 
9518   MachineFunction &MF = *BB->getParent();
9519   DebugLoc DL = MI.getDebugLoc();
9520   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9521   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9522   Register LoReg = MI.getOperand(0).getReg();
9523   Register HiReg = MI.getOperand(1).getReg();
9524   Register SrcReg = MI.getOperand(2).getReg();
9525   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9526   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9527 
9528   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9529                           RI);
9530   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9531   MachineMemOperand *MMOLo =
9532       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9533   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9534       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9535   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9536       .addFrameIndex(FI)
9537       .addImm(0)
9538       .addMemOperand(MMOLo);
9539   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9540       .addFrameIndex(FI)
9541       .addImm(4)
9542       .addMemOperand(MMOHi);
9543   MI.eraseFromParent(); // The pseudo instruction is gone now.
9544   return BB;
9545 }
9546 
9547 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9548                                                  MachineBasicBlock *BB) {
9549   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9550          "Unexpected instruction");
9551 
9552   MachineFunction &MF = *BB->getParent();
9553   DebugLoc DL = MI.getDebugLoc();
9554   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9555   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9556   Register DstReg = MI.getOperand(0).getReg();
9557   Register LoReg = MI.getOperand(1).getReg();
9558   Register HiReg = MI.getOperand(2).getReg();
9559   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9560   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9561 
9562   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9563   MachineMemOperand *MMOLo =
9564       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9565   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9566       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9567   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9568       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9569       .addFrameIndex(FI)
9570       .addImm(0)
9571       .addMemOperand(MMOLo);
9572   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9573       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9574       .addFrameIndex(FI)
9575       .addImm(4)
9576       .addMemOperand(MMOHi);
9577   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9578   MI.eraseFromParent(); // The pseudo instruction is gone now.
9579   return BB;
9580 }
9581 
9582 static bool isSelectPseudo(MachineInstr &MI) {
9583   switch (MI.getOpcode()) {
9584   default:
9585     return false;
9586   case RISCV::Select_GPR_Using_CC_GPR:
9587   case RISCV::Select_FPR16_Using_CC_GPR:
9588   case RISCV::Select_FPR32_Using_CC_GPR:
9589   case RISCV::Select_FPR64_Using_CC_GPR:
9590     return true;
9591   }
9592 }
9593 
9594 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9595                                         unsigned RelOpcode, unsigned EqOpcode,
9596                                         const RISCVSubtarget &Subtarget) {
9597   DebugLoc DL = MI.getDebugLoc();
9598   Register DstReg = MI.getOperand(0).getReg();
9599   Register Src1Reg = MI.getOperand(1).getReg();
9600   Register Src2Reg = MI.getOperand(2).getReg();
9601   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9602   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9603   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9604 
9605   // Save the current FFLAGS.
9606   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9607 
9608   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9609                  .addReg(Src1Reg)
9610                  .addReg(Src2Reg);
9611   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9612     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9613 
9614   // Restore the FFLAGS.
9615   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9616       .addReg(SavedFFlags, RegState::Kill);
9617 
9618   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9619   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9620                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9621                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9622   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9623     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9624 
9625   // Erase the pseudoinstruction.
9626   MI.eraseFromParent();
9627   return BB;
9628 }
9629 
9630 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9631                                            MachineBasicBlock *BB,
9632                                            const RISCVSubtarget &Subtarget) {
9633   // To "insert" Select_* instructions, we actually have to insert the triangle
9634   // control-flow pattern.  The incoming instructions know the destination vreg
9635   // to set, the condition code register to branch on, the true/false values to
9636   // select between, and the condcode to use to select the appropriate branch.
9637   //
9638   // We produce the following control flow:
9639   //     HeadMBB
9640   //     |  \
9641   //     |  IfFalseMBB
9642   //     | /
9643   //    TailMBB
9644   //
9645   // When we find a sequence of selects we attempt to optimize their emission
9646   // by sharing the control flow. Currently we only handle cases where we have
9647   // multiple selects with the exact same condition (same LHS, RHS and CC).
9648   // The selects may be interleaved with other instructions if the other
9649   // instructions meet some requirements we deem safe:
9650   // - They are debug instructions. Otherwise,
9651   // - They do not have side-effects, do not access memory and their inputs do
9652   //   not depend on the results of the select pseudo-instructions.
9653   // The TrueV/FalseV operands of the selects cannot depend on the result of
9654   // previous selects in the sequence.
9655   // These conditions could be further relaxed. See the X86 target for a
9656   // related approach and more information.
9657   Register LHS = MI.getOperand(1).getReg();
9658   Register RHS = MI.getOperand(2).getReg();
9659   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9660 
9661   SmallVector<MachineInstr *, 4> SelectDebugValues;
9662   SmallSet<Register, 4> SelectDests;
9663   SelectDests.insert(MI.getOperand(0).getReg());
9664 
9665   MachineInstr *LastSelectPseudo = &MI;
9666 
9667   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9668        SequenceMBBI != E; ++SequenceMBBI) {
9669     if (SequenceMBBI->isDebugInstr())
9670       continue;
9671     if (isSelectPseudo(*SequenceMBBI)) {
9672       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9673           SequenceMBBI->getOperand(2).getReg() != RHS ||
9674           SequenceMBBI->getOperand(3).getImm() != CC ||
9675           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9676           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9677         break;
9678       LastSelectPseudo = &*SequenceMBBI;
9679       SequenceMBBI->collectDebugValues(SelectDebugValues);
9680       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9681     } else {
9682       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9683           SequenceMBBI->mayLoadOrStore())
9684         break;
9685       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9686             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9687           }))
9688         break;
9689     }
9690   }
9691 
9692   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9693   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9694   DebugLoc DL = MI.getDebugLoc();
9695   MachineFunction::iterator I = ++BB->getIterator();
9696 
9697   MachineBasicBlock *HeadMBB = BB;
9698   MachineFunction *F = BB->getParent();
9699   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9700   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9701 
9702   F->insert(I, IfFalseMBB);
9703   F->insert(I, TailMBB);
9704 
9705   // Transfer debug instructions associated with the selects to TailMBB.
9706   for (MachineInstr *DebugInstr : SelectDebugValues) {
9707     TailMBB->push_back(DebugInstr->removeFromParent());
9708   }
9709 
9710   // Move all instructions after the sequence to TailMBB.
9711   TailMBB->splice(TailMBB->end(), HeadMBB,
9712                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9713   // Update machine-CFG edges by transferring all successors of the current
9714   // block to the new block which will contain the Phi nodes for the selects.
9715   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9716   // Set the successors for HeadMBB.
9717   HeadMBB->addSuccessor(IfFalseMBB);
9718   HeadMBB->addSuccessor(TailMBB);
9719 
9720   // Insert appropriate branch.
9721   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9722     .addReg(LHS)
9723     .addReg(RHS)
9724     .addMBB(TailMBB);
9725 
9726   // IfFalseMBB just falls through to TailMBB.
9727   IfFalseMBB->addSuccessor(TailMBB);
9728 
9729   // Create PHIs for all of the select pseudo-instructions.
9730   auto SelectMBBI = MI.getIterator();
9731   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9732   auto InsertionPoint = TailMBB->begin();
9733   while (SelectMBBI != SelectEnd) {
9734     auto Next = std::next(SelectMBBI);
9735     if (isSelectPseudo(*SelectMBBI)) {
9736       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9737       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9738               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9739           .addReg(SelectMBBI->getOperand(4).getReg())
9740           .addMBB(HeadMBB)
9741           .addReg(SelectMBBI->getOperand(5).getReg())
9742           .addMBB(IfFalseMBB);
9743       SelectMBBI->eraseFromParent();
9744     }
9745     SelectMBBI = Next;
9746   }
9747 
9748   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9749   return TailMBB;
9750 }
9751 
9752 MachineBasicBlock *
9753 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9754                                                  MachineBasicBlock *BB) const {
9755   switch (MI.getOpcode()) {
9756   default:
9757     llvm_unreachable("Unexpected instr type to insert");
9758   case RISCV::ReadCycleWide:
9759     assert(!Subtarget.is64Bit() &&
9760            "ReadCycleWrite is only to be used on riscv32");
9761     return emitReadCycleWidePseudo(MI, BB);
9762   case RISCV::Select_GPR_Using_CC_GPR:
9763   case RISCV::Select_FPR16_Using_CC_GPR:
9764   case RISCV::Select_FPR32_Using_CC_GPR:
9765   case RISCV::Select_FPR64_Using_CC_GPR:
9766     return emitSelectPseudo(MI, BB, Subtarget);
9767   case RISCV::BuildPairF64Pseudo:
9768     return emitBuildPairF64Pseudo(MI, BB);
9769   case RISCV::SplitF64Pseudo:
9770     return emitSplitF64Pseudo(MI, BB);
9771   case RISCV::PseudoQuietFLE_H:
9772     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9773   case RISCV::PseudoQuietFLT_H:
9774     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9775   case RISCV::PseudoQuietFLE_S:
9776     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9777   case RISCV::PseudoQuietFLT_S:
9778     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9779   case RISCV::PseudoQuietFLE_D:
9780     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9781   case RISCV::PseudoQuietFLT_D:
9782     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9783   }
9784 }
9785 
9786 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9787                                                         SDNode *Node) const {
9788   // Add FRM dependency to any instructions with dynamic rounding mode.
9789   unsigned Opc = MI.getOpcode();
9790   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9791   if (Idx < 0)
9792     return;
9793   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9794     return;
9795   // If the instruction already reads FRM, don't add another read.
9796   if (MI.readsRegister(RISCV::FRM))
9797     return;
9798   MI.addOperand(
9799       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9800 }
9801 
9802 // Calling Convention Implementation.
9803 // The expectations for frontend ABI lowering vary from target to target.
9804 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9805 // details, but this is a longer term goal. For now, we simply try to keep the
9806 // role of the frontend as simple and well-defined as possible. The rules can
9807 // be summarised as:
9808 // * Never split up large scalar arguments. We handle them here.
9809 // * If a hardfloat calling convention is being used, and the struct may be
9810 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9811 // available, then pass as two separate arguments. If either the GPRs or FPRs
9812 // are exhausted, then pass according to the rule below.
9813 // * If a struct could never be passed in registers or directly in a stack
9814 // slot (as it is larger than 2*XLEN and the floating point rules don't
9815 // apply), then pass it using a pointer with the byval attribute.
9816 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9817 // word-sized array or a 2*XLEN scalar (depending on alignment).
9818 // * The frontend can determine whether a struct is returned by reference or
9819 // not based on its size and fields. If it will be returned by reference, the
9820 // frontend must modify the prototype so a pointer with the sret annotation is
9821 // passed as the first argument. This is not necessary for large scalar
9822 // returns.
9823 // * Struct return values and varargs should be coerced to structs containing
9824 // register-size fields in the same situations they would be for fixed
9825 // arguments.
9826 
9827 static const MCPhysReg ArgGPRs[] = {
9828   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9829   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9830 };
9831 static const MCPhysReg ArgFPR16s[] = {
9832   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9833   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9834 };
9835 static const MCPhysReg ArgFPR32s[] = {
9836   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9837   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9838 };
9839 static const MCPhysReg ArgFPR64s[] = {
9840   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9841   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9842 };
9843 // This is an interim calling convention and it may be changed in the future.
9844 static const MCPhysReg ArgVRs[] = {
9845     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9846     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9847     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9848 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9849                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9850                                      RISCV::V20M2, RISCV::V22M2};
9851 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9852                                      RISCV::V20M4};
9853 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9854 
9855 // Pass a 2*XLEN argument that has been split into two XLEN values through
9856 // registers or the stack as necessary.
9857 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9858                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9859                                 MVT ValVT2, MVT LocVT2,
9860                                 ISD::ArgFlagsTy ArgFlags2) {
9861   unsigned XLenInBytes = XLen / 8;
9862   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9863     // At least one half can be passed via register.
9864     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9865                                      VA1.getLocVT(), CCValAssign::Full));
9866   } else {
9867     // Both halves must be passed on the stack, with proper alignment.
9868     Align StackAlign =
9869         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9870     State.addLoc(
9871         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9872                             State.AllocateStack(XLenInBytes, StackAlign),
9873                             VA1.getLocVT(), CCValAssign::Full));
9874     State.addLoc(CCValAssign::getMem(
9875         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9876         LocVT2, CCValAssign::Full));
9877     return false;
9878   }
9879 
9880   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9881     // The second half can also be passed via register.
9882     State.addLoc(
9883         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9884   } else {
9885     // The second half is passed via the stack, without additional alignment.
9886     State.addLoc(CCValAssign::getMem(
9887         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9888         LocVT2, CCValAssign::Full));
9889   }
9890 
9891   return false;
9892 }
9893 
9894 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9895                                Optional<unsigned> FirstMaskArgument,
9896                                CCState &State, const RISCVTargetLowering &TLI) {
9897   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9898   if (RC == &RISCV::VRRegClass) {
9899     // Assign the first mask argument to V0.
9900     // This is an interim calling convention and it may be changed in the
9901     // future.
9902     if (FirstMaskArgument && ValNo == *FirstMaskArgument)
9903       return State.AllocateReg(RISCV::V0);
9904     return State.AllocateReg(ArgVRs);
9905   }
9906   if (RC == &RISCV::VRM2RegClass)
9907     return State.AllocateReg(ArgVRM2s);
9908   if (RC == &RISCV::VRM4RegClass)
9909     return State.AllocateReg(ArgVRM4s);
9910   if (RC == &RISCV::VRM8RegClass)
9911     return State.AllocateReg(ArgVRM8s);
9912   llvm_unreachable("Unhandled register class for ValueType");
9913 }
9914 
9915 // Implements the RISC-V calling convention. Returns true upon failure.
9916 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9917                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9918                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9919                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9920                      Optional<unsigned> FirstMaskArgument) {
9921   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9922   assert(XLen == 32 || XLen == 64);
9923   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9924 
9925   // Any return value split in to more than two values can't be returned
9926   // directly. Vectors are returned via the available vector registers.
9927   if (!LocVT.isVector() && IsRet && ValNo > 1)
9928     return true;
9929 
9930   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9931   // variadic argument, or if no F16/F32 argument registers are available.
9932   bool UseGPRForF16_F32 = true;
9933   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9934   // variadic argument, or if no F64 argument registers are available.
9935   bool UseGPRForF64 = true;
9936 
9937   switch (ABI) {
9938   default:
9939     llvm_unreachable("Unexpected ABI");
9940   case RISCVABI::ABI_ILP32:
9941   case RISCVABI::ABI_LP64:
9942     break;
9943   case RISCVABI::ABI_ILP32F:
9944   case RISCVABI::ABI_LP64F:
9945     UseGPRForF16_F32 = !IsFixed;
9946     break;
9947   case RISCVABI::ABI_ILP32D:
9948   case RISCVABI::ABI_LP64D:
9949     UseGPRForF16_F32 = !IsFixed;
9950     UseGPRForF64 = !IsFixed;
9951     break;
9952   }
9953 
9954   // FPR16, FPR32, and FPR64 alias each other.
9955   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9956     UseGPRForF16_F32 = true;
9957     UseGPRForF64 = true;
9958   }
9959 
9960   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9961   // similar local variables rather than directly checking against the target
9962   // ABI.
9963 
9964   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9965     LocVT = XLenVT;
9966     LocInfo = CCValAssign::BCvt;
9967   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9968     LocVT = MVT::i64;
9969     LocInfo = CCValAssign::BCvt;
9970   }
9971 
9972   // If this is a variadic argument, the RISC-V calling convention requires
9973   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9974   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9975   // be used regardless of whether the original argument was split during
9976   // legalisation or not. The argument will not be passed by registers if the
9977   // original type is larger than 2*XLEN, so the register alignment rule does
9978   // not apply.
9979   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9980   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9981       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9982     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9983     // Skip 'odd' register if necessary.
9984     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9985       State.AllocateReg(ArgGPRs);
9986   }
9987 
9988   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9989   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9990       State.getPendingArgFlags();
9991 
9992   assert(PendingLocs.size() == PendingArgFlags.size() &&
9993          "PendingLocs and PendingArgFlags out of sync");
9994 
9995   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9996   // registers are exhausted.
9997   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9998     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9999            "Can't lower f64 if it is split");
10000     // Depending on available argument GPRS, f64 may be passed in a pair of
10001     // GPRs, split between a GPR and the stack, or passed completely on the
10002     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
10003     // cases.
10004     Register Reg = State.AllocateReg(ArgGPRs);
10005     LocVT = MVT::i32;
10006     if (!Reg) {
10007       unsigned StackOffset = State.AllocateStack(8, Align(8));
10008       State.addLoc(
10009           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10010       return false;
10011     }
10012     if (!State.AllocateReg(ArgGPRs))
10013       State.AllocateStack(4, Align(4));
10014     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10015     return false;
10016   }
10017 
10018   // Fixed-length vectors are located in the corresponding scalable-vector
10019   // container types.
10020   if (ValVT.isFixedLengthVector())
10021     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10022 
10023   // Split arguments might be passed indirectly, so keep track of the pending
10024   // values. Split vectors are passed via a mix of registers and indirectly, so
10025   // treat them as we would any other argument.
10026   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
10027     LocVT = XLenVT;
10028     LocInfo = CCValAssign::Indirect;
10029     PendingLocs.push_back(
10030         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
10031     PendingArgFlags.push_back(ArgFlags);
10032     if (!ArgFlags.isSplitEnd()) {
10033       return false;
10034     }
10035   }
10036 
10037   // If the split argument only had two elements, it should be passed directly
10038   // in registers or on the stack.
10039   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
10040       PendingLocs.size() <= 2) {
10041     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
10042     // Apply the normal calling convention rules to the first half of the
10043     // split argument.
10044     CCValAssign VA = PendingLocs[0];
10045     ISD::ArgFlagsTy AF = PendingArgFlags[0];
10046     PendingLocs.clear();
10047     PendingArgFlags.clear();
10048     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
10049                                ArgFlags);
10050   }
10051 
10052   // Allocate to a register if possible, or else a stack slot.
10053   Register Reg;
10054   unsigned StoreSizeBytes = XLen / 8;
10055   Align StackAlign = Align(XLen / 8);
10056 
10057   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
10058     Reg = State.AllocateReg(ArgFPR16s);
10059   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
10060     Reg = State.AllocateReg(ArgFPR32s);
10061   else if (ValVT == MVT::f64 && !UseGPRForF64)
10062     Reg = State.AllocateReg(ArgFPR64s);
10063   else if (ValVT.isVector()) {
10064     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
10065     if (!Reg) {
10066       // For return values, the vector must be passed fully via registers or
10067       // via the stack.
10068       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
10069       // but we're using all of them.
10070       if (IsRet)
10071         return true;
10072       // Try using a GPR to pass the address
10073       if ((Reg = State.AllocateReg(ArgGPRs))) {
10074         LocVT = XLenVT;
10075         LocInfo = CCValAssign::Indirect;
10076       } else if (ValVT.isScalableVector()) {
10077         LocVT = XLenVT;
10078         LocInfo = CCValAssign::Indirect;
10079       } else {
10080         // Pass fixed-length vectors on the stack.
10081         LocVT = ValVT;
10082         StoreSizeBytes = ValVT.getStoreSize();
10083         // Align vectors to their element sizes, being careful for vXi1
10084         // vectors.
10085         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10086       }
10087     }
10088   } else {
10089     Reg = State.AllocateReg(ArgGPRs);
10090   }
10091 
10092   unsigned StackOffset =
10093       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
10094 
10095   // If we reach this point and PendingLocs is non-empty, we must be at the
10096   // end of a split argument that must be passed indirectly.
10097   if (!PendingLocs.empty()) {
10098     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
10099     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
10100 
10101     for (auto &It : PendingLocs) {
10102       if (Reg)
10103         It.convertToReg(Reg);
10104       else
10105         It.convertToMem(StackOffset);
10106       State.addLoc(It);
10107     }
10108     PendingLocs.clear();
10109     PendingArgFlags.clear();
10110     return false;
10111   }
10112 
10113   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
10114           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
10115          "Expected an XLenVT or vector types at this stage");
10116 
10117   if (Reg) {
10118     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10119     return false;
10120   }
10121 
10122   // When a floating-point value is passed on the stack, no bit-conversion is
10123   // needed.
10124   if (ValVT.isFloatingPoint()) {
10125     LocVT = ValVT;
10126     LocInfo = CCValAssign::Full;
10127   }
10128   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10129   return false;
10130 }
10131 
10132 template <typename ArgTy>
10133 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
10134   for (const auto &ArgIdx : enumerate(Args)) {
10135     MVT ArgVT = ArgIdx.value().VT;
10136     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
10137       return ArgIdx.index();
10138   }
10139   return None;
10140 }
10141 
10142 void RISCVTargetLowering::analyzeInputArgs(
10143     MachineFunction &MF, CCState &CCInfo,
10144     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
10145     RISCVCCAssignFn Fn) const {
10146   unsigned NumArgs = Ins.size();
10147   FunctionType *FType = MF.getFunction().getFunctionType();
10148 
10149   Optional<unsigned> FirstMaskArgument;
10150   if (Subtarget.hasVInstructions())
10151     FirstMaskArgument = preAssignMask(Ins);
10152 
10153   for (unsigned i = 0; i != NumArgs; ++i) {
10154     MVT ArgVT = Ins[i].VT;
10155     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
10156 
10157     Type *ArgTy = nullptr;
10158     if (IsRet)
10159       ArgTy = FType->getReturnType();
10160     else if (Ins[i].isOrigArg())
10161       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
10162 
10163     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10164     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10165            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
10166            FirstMaskArgument)) {
10167       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
10168                         << EVT(ArgVT).getEVTString() << '\n');
10169       llvm_unreachable(nullptr);
10170     }
10171   }
10172 }
10173 
10174 void RISCVTargetLowering::analyzeOutputArgs(
10175     MachineFunction &MF, CCState &CCInfo,
10176     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
10177     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
10178   unsigned NumArgs = Outs.size();
10179 
10180   Optional<unsigned> FirstMaskArgument;
10181   if (Subtarget.hasVInstructions())
10182     FirstMaskArgument = preAssignMask(Outs);
10183 
10184   for (unsigned i = 0; i != NumArgs; i++) {
10185     MVT ArgVT = Outs[i].VT;
10186     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10187     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
10188 
10189     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10190     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10191            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
10192            FirstMaskArgument)) {
10193       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
10194                         << EVT(ArgVT).getEVTString() << "\n");
10195       llvm_unreachable(nullptr);
10196     }
10197   }
10198 }
10199 
10200 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
10201 // values.
10202 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
10203                                    const CCValAssign &VA, const SDLoc &DL,
10204                                    const RISCVSubtarget &Subtarget) {
10205   switch (VA.getLocInfo()) {
10206   default:
10207     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10208   case CCValAssign::Full:
10209     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
10210       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
10211     break;
10212   case CCValAssign::BCvt:
10213     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10214       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
10215     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10216       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
10217     else
10218       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
10219     break;
10220   }
10221   return Val;
10222 }
10223 
10224 // The caller is responsible for loading the full value if the argument is
10225 // passed with CCValAssign::Indirect.
10226 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
10227                                 const CCValAssign &VA, const SDLoc &DL,
10228                                 const RISCVTargetLowering &TLI) {
10229   MachineFunction &MF = DAG.getMachineFunction();
10230   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10231   EVT LocVT = VA.getLocVT();
10232   SDValue Val;
10233   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
10234   Register VReg = RegInfo.createVirtualRegister(RC);
10235   RegInfo.addLiveIn(VA.getLocReg(), VReg);
10236   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
10237 
10238   if (VA.getLocInfo() == CCValAssign::Indirect)
10239     return Val;
10240 
10241   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
10242 }
10243 
10244 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
10245                                    const CCValAssign &VA, const SDLoc &DL,
10246                                    const RISCVSubtarget &Subtarget) {
10247   EVT LocVT = VA.getLocVT();
10248 
10249   switch (VA.getLocInfo()) {
10250   default:
10251     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10252   case CCValAssign::Full:
10253     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
10254       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
10255     break;
10256   case CCValAssign::BCvt:
10257     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10258       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
10259     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10260       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
10261     else
10262       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
10263     break;
10264   }
10265   return Val;
10266 }
10267 
10268 // The caller is responsible for loading the full value if the argument is
10269 // passed with CCValAssign::Indirect.
10270 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
10271                                 const CCValAssign &VA, const SDLoc &DL) {
10272   MachineFunction &MF = DAG.getMachineFunction();
10273   MachineFrameInfo &MFI = MF.getFrameInfo();
10274   EVT LocVT = VA.getLocVT();
10275   EVT ValVT = VA.getValVT();
10276   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
10277   if (ValVT.isScalableVector()) {
10278     // When the value is a scalable vector, we save the pointer which points to
10279     // the scalable vector value in the stack. The ValVT will be the pointer
10280     // type, instead of the scalable vector type.
10281     ValVT = LocVT;
10282   }
10283   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
10284                                  /*IsImmutable=*/true);
10285   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
10286   SDValue Val;
10287 
10288   ISD::LoadExtType ExtType;
10289   switch (VA.getLocInfo()) {
10290   default:
10291     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10292   case CCValAssign::Full:
10293   case CCValAssign::Indirect:
10294   case CCValAssign::BCvt:
10295     ExtType = ISD::NON_EXTLOAD;
10296     break;
10297   }
10298   Val = DAG.getExtLoad(
10299       ExtType, DL, LocVT, Chain, FIN,
10300       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
10301   return Val;
10302 }
10303 
10304 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
10305                                        const CCValAssign &VA, const SDLoc &DL) {
10306   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
10307          "Unexpected VA");
10308   MachineFunction &MF = DAG.getMachineFunction();
10309   MachineFrameInfo &MFI = MF.getFrameInfo();
10310   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10311 
10312   if (VA.isMemLoc()) {
10313     // f64 is passed on the stack.
10314     int FI =
10315         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
10316     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10317     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
10318                        MachinePointerInfo::getFixedStack(MF, FI));
10319   }
10320 
10321   assert(VA.isRegLoc() && "Expected register VA assignment");
10322 
10323   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10324   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
10325   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
10326   SDValue Hi;
10327   if (VA.getLocReg() == RISCV::X17) {
10328     // Second half of f64 is passed on the stack.
10329     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
10330     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10331     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10332                      MachinePointerInfo::getFixedStack(MF, FI));
10333   } else {
10334     // Second half of f64 is passed in another GPR.
10335     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10336     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10337     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10338   }
10339   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10340 }
10341 
10342 // FastCC has less than 1% performance improvement for some particular
10343 // benchmark. But theoretically, it may has benenfit for some cases.
10344 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10345                             unsigned ValNo, MVT ValVT, MVT LocVT,
10346                             CCValAssign::LocInfo LocInfo,
10347                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10348                             bool IsFixed, bool IsRet, Type *OrigTy,
10349                             const RISCVTargetLowering &TLI,
10350                             Optional<unsigned> FirstMaskArgument) {
10351 
10352   // X5 and X6 might be used for save-restore libcall.
10353   static const MCPhysReg GPRList[] = {
10354       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10355       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10356       RISCV::X29, RISCV::X30, RISCV::X31};
10357 
10358   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10359     if (unsigned Reg = State.AllocateReg(GPRList)) {
10360       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10361       return false;
10362     }
10363   }
10364 
10365   if (LocVT == MVT::f16) {
10366     static const MCPhysReg FPR16List[] = {
10367         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10368         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10369         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10370         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10371     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10372       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10373       return false;
10374     }
10375   }
10376 
10377   if (LocVT == MVT::f32) {
10378     static const MCPhysReg FPR32List[] = {
10379         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10380         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10381         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10382         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10383     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10384       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10385       return false;
10386     }
10387   }
10388 
10389   if (LocVT == MVT::f64) {
10390     static const MCPhysReg FPR64List[] = {
10391         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10392         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10393         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10394         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10395     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10396       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10397       return false;
10398     }
10399   }
10400 
10401   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10402     unsigned Offset4 = State.AllocateStack(4, Align(4));
10403     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10404     return false;
10405   }
10406 
10407   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10408     unsigned Offset5 = State.AllocateStack(8, Align(8));
10409     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10410     return false;
10411   }
10412 
10413   if (LocVT.isVector()) {
10414     if (unsigned Reg =
10415             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10416       // Fixed-length vectors are located in the corresponding scalable-vector
10417       // container types.
10418       if (ValVT.isFixedLengthVector())
10419         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10420       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10421     } else {
10422       // Try and pass the address via a "fast" GPR.
10423       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10424         LocInfo = CCValAssign::Indirect;
10425         LocVT = TLI.getSubtarget().getXLenVT();
10426         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10427       } else if (ValVT.isFixedLengthVector()) {
10428         auto StackAlign =
10429             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10430         unsigned StackOffset =
10431             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10432         State.addLoc(
10433             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10434       } else {
10435         // Can't pass scalable vectors on the stack.
10436         return true;
10437       }
10438     }
10439 
10440     return false;
10441   }
10442 
10443   return true; // CC didn't match.
10444 }
10445 
10446 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10447                          CCValAssign::LocInfo LocInfo,
10448                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10449 
10450   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10451     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10452     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10453     static const MCPhysReg GPRList[] = {
10454         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10455         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10456     if (unsigned Reg = State.AllocateReg(GPRList)) {
10457       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10458       return false;
10459     }
10460   }
10461 
10462   if (LocVT == MVT::f32) {
10463     // Pass in STG registers: F1, ..., F6
10464     //                        fs0 ... fs5
10465     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10466                                           RISCV::F18_F, RISCV::F19_F,
10467                                           RISCV::F20_F, RISCV::F21_F};
10468     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10469       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10470       return false;
10471     }
10472   }
10473 
10474   if (LocVT == MVT::f64) {
10475     // Pass in STG registers: D1, ..., D6
10476     //                        fs6 ... fs11
10477     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10478                                           RISCV::F24_D, RISCV::F25_D,
10479                                           RISCV::F26_D, RISCV::F27_D};
10480     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10481       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10482       return false;
10483     }
10484   }
10485 
10486   report_fatal_error("No registers left in GHC calling convention");
10487   return true;
10488 }
10489 
10490 // Transform physical registers into virtual registers.
10491 SDValue RISCVTargetLowering::LowerFormalArguments(
10492     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10493     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10494     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10495 
10496   MachineFunction &MF = DAG.getMachineFunction();
10497 
10498   switch (CallConv) {
10499   default:
10500     report_fatal_error("Unsupported calling convention");
10501   case CallingConv::C:
10502   case CallingConv::Fast:
10503     break;
10504   case CallingConv::GHC:
10505     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10506         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10507       report_fatal_error(
10508         "GHC calling convention requires the F and D instruction set extensions");
10509   }
10510 
10511   const Function &Func = MF.getFunction();
10512   if (Func.hasFnAttribute("interrupt")) {
10513     if (!Func.arg_empty())
10514       report_fatal_error(
10515         "Functions with the interrupt attribute cannot have arguments!");
10516 
10517     StringRef Kind =
10518       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10519 
10520     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10521       report_fatal_error(
10522         "Function interrupt attribute argument not supported!");
10523   }
10524 
10525   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10526   MVT XLenVT = Subtarget.getXLenVT();
10527   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10528   // Used with vargs to acumulate store chains.
10529   std::vector<SDValue> OutChains;
10530 
10531   // Assign locations to all of the incoming arguments.
10532   SmallVector<CCValAssign, 16> ArgLocs;
10533   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10534 
10535   if (CallConv == CallingConv::GHC)
10536     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10537   else
10538     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10539                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10540                                                    : CC_RISCV);
10541 
10542   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10543     CCValAssign &VA = ArgLocs[i];
10544     SDValue ArgValue;
10545     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10546     // case.
10547     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10548       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10549     else if (VA.isRegLoc())
10550       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10551     else
10552       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10553 
10554     if (VA.getLocInfo() == CCValAssign::Indirect) {
10555       // If the original argument was split and passed by reference (e.g. i128
10556       // on RV32), we need to load all parts of it here (using the same
10557       // address). Vectors may be partly split to registers and partly to the
10558       // stack, in which case the base address is partly offset and subsequent
10559       // stores are relative to that.
10560       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10561                                    MachinePointerInfo()));
10562       unsigned ArgIndex = Ins[i].OrigArgIndex;
10563       unsigned ArgPartOffset = Ins[i].PartOffset;
10564       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10565       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10566         CCValAssign &PartVA = ArgLocs[i + 1];
10567         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10568         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10569         if (PartVA.getValVT().isScalableVector())
10570           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10571         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10572         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10573                                      MachinePointerInfo()));
10574         ++i;
10575       }
10576       continue;
10577     }
10578     InVals.push_back(ArgValue);
10579   }
10580 
10581   if (IsVarArg) {
10582     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10583     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10584     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10585     MachineFrameInfo &MFI = MF.getFrameInfo();
10586     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10587     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10588 
10589     // Offset of the first variable argument from stack pointer, and size of
10590     // the vararg save area. For now, the varargs save area is either zero or
10591     // large enough to hold a0-a7.
10592     int VaArgOffset, VarArgsSaveSize;
10593 
10594     // If all registers are allocated, then all varargs must be passed on the
10595     // stack and we don't need to save any argregs.
10596     if (ArgRegs.size() == Idx) {
10597       VaArgOffset = CCInfo.getNextStackOffset();
10598       VarArgsSaveSize = 0;
10599     } else {
10600       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10601       VaArgOffset = -VarArgsSaveSize;
10602     }
10603 
10604     // Record the frame index of the first variable argument
10605     // which is a value necessary to VASTART.
10606     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10607     RVFI->setVarArgsFrameIndex(FI);
10608 
10609     // If saving an odd number of registers then create an extra stack slot to
10610     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10611     // offsets to even-numbered registered remain 2*XLEN-aligned.
10612     if (Idx % 2) {
10613       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10614       VarArgsSaveSize += XLenInBytes;
10615     }
10616 
10617     // Copy the integer registers that may have been used for passing varargs
10618     // to the vararg save area.
10619     for (unsigned I = Idx; I < ArgRegs.size();
10620          ++I, VaArgOffset += XLenInBytes) {
10621       const Register Reg = RegInfo.createVirtualRegister(RC);
10622       RegInfo.addLiveIn(ArgRegs[I], Reg);
10623       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10624       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10625       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10626       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10627                                    MachinePointerInfo::getFixedStack(MF, FI));
10628       cast<StoreSDNode>(Store.getNode())
10629           ->getMemOperand()
10630           ->setValue((Value *)nullptr);
10631       OutChains.push_back(Store);
10632     }
10633     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10634   }
10635 
10636   // All stores are grouped in one node to allow the matching between
10637   // the size of Ins and InVals. This only happens for vararg functions.
10638   if (!OutChains.empty()) {
10639     OutChains.push_back(Chain);
10640     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10641   }
10642 
10643   return Chain;
10644 }
10645 
10646 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10647 /// for tail call optimization.
10648 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10649 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10650     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10651     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10652 
10653   auto &Callee = CLI.Callee;
10654   auto CalleeCC = CLI.CallConv;
10655   auto &Outs = CLI.Outs;
10656   auto &Caller = MF.getFunction();
10657   auto CallerCC = Caller.getCallingConv();
10658 
10659   // Exception-handling functions need a special set of instructions to
10660   // indicate a return to the hardware. Tail-calling another function would
10661   // probably break this.
10662   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10663   // should be expanded as new function attributes are introduced.
10664   if (Caller.hasFnAttribute("interrupt"))
10665     return false;
10666 
10667   // Do not tail call opt if the stack is used to pass parameters.
10668   if (CCInfo.getNextStackOffset() != 0)
10669     return false;
10670 
10671   // Do not tail call opt if any parameters need to be passed indirectly.
10672   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10673   // passed indirectly. So the address of the value will be passed in a
10674   // register, or if not available, then the address is put on the stack. In
10675   // order to pass indirectly, space on the stack often needs to be allocated
10676   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10677   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10678   // are passed CCValAssign::Indirect.
10679   for (auto &VA : ArgLocs)
10680     if (VA.getLocInfo() == CCValAssign::Indirect)
10681       return false;
10682 
10683   // Do not tail call opt if either caller or callee uses struct return
10684   // semantics.
10685   auto IsCallerStructRet = Caller.hasStructRetAttr();
10686   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10687   if (IsCallerStructRet || IsCalleeStructRet)
10688     return false;
10689 
10690   // Externally-defined functions with weak linkage should not be
10691   // tail-called. The behaviour of branch instructions in this situation (as
10692   // used for tail calls) is implementation-defined, so we cannot rely on the
10693   // linker replacing the tail call with a return.
10694   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10695     const GlobalValue *GV = G->getGlobal();
10696     if (GV->hasExternalWeakLinkage())
10697       return false;
10698   }
10699 
10700   // The callee has to preserve all registers the caller needs to preserve.
10701   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10702   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10703   if (CalleeCC != CallerCC) {
10704     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10705     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10706       return false;
10707   }
10708 
10709   // Byval parameters hand the function a pointer directly into the stack area
10710   // we want to reuse during a tail call. Working around this *is* possible
10711   // but less efficient and uglier in LowerCall.
10712   for (auto &Arg : Outs)
10713     if (Arg.Flags.isByVal())
10714       return false;
10715 
10716   return true;
10717 }
10718 
10719 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10720   return DAG.getDataLayout().getPrefTypeAlign(
10721       VT.getTypeForEVT(*DAG.getContext()));
10722 }
10723 
10724 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10725 // and output parameter nodes.
10726 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10727                                        SmallVectorImpl<SDValue> &InVals) const {
10728   SelectionDAG &DAG = CLI.DAG;
10729   SDLoc &DL = CLI.DL;
10730   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10731   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10732   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10733   SDValue Chain = CLI.Chain;
10734   SDValue Callee = CLI.Callee;
10735   bool &IsTailCall = CLI.IsTailCall;
10736   CallingConv::ID CallConv = CLI.CallConv;
10737   bool IsVarArg = CLI.IsVarArg;
10738   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10739   MVT XLenVT = Subtarget.getXLenVT();
10740 
10741   MachineFunction &MF = DAG.getMachineFunction();
10742 
10743   // Analyze the operands of the call, assigning locations to each operand.
10744   SmallVector<CCValAssign, 16> ArgLocs;
10745   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10746 
10747   if (CallConv == CallingConv::GHC)
10748     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10749   else
10750     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10751                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10752                                                     : CC_RISCV);
10753 
10754   // Check if it's really possible to do a tail call.
10755   if (IsTailCall)
10756     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10757 
10758   if (IsTailCall)
10759     ++NumTailCalls;
10760   else if (CLI.CB && CLI.CB->isMustTailCall())
10761     report_fatal_error("failed to perform tail call elimination on a call "
10762                        "site marked musttail");
10763 
10764   // Get a count of how many bytes are to be pushed on the stack.
10765   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10766 
10767   // Create local copies for byval args
10768   SmallVector<SDValue, 8> ByValArgs;
10769   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10770     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10771     if (!Flags.isByVal())
10772       continue;
10773 
10774     SDValue Arg = OutVals[i];
10775     unsigned Size = Flags.getByValSize();
10776     Align Alignment = Flags.getNonZeroByValAlign();
10777 
10778     int FI =
10779         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10780     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10781     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10782 
10783     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10784                           /*IsVolatile=*/false,
10785                           /*AlwaysInline=*/false, IsTailCall,
10786                           MachinePointerInfo(), MachinePointerInfo());
10787     ByValArgs.push_back(FIPtr);
10788   }
10789 
10790   if (!IsTailCall)
10791     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10792 
10793   // Copy argument values to their designated locations.
10794   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10795   SmallVector<SDValue, 8> MemOpChains;
10796   SDValue StackPtr;
10797   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10798     CCValAssign &VA = ArgLocs[i];
10799     SDValue ArgValue = OutVals[i];
10800     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10801 
10802     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10803     bool IsF64OnRV32DSoftABI =
10804         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10805     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10806       SDValue SplitF64 = DAG.getNode(
10807           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10808       SDValue Lo = SplitF64.getValue(0);
10809       SDValue Hi = SplitF64.getValue(1);
10810 
10811       Register RegLo = VA.getLocReg();
10812       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10813 
10814       if (RegLo == RISCV::X17) {
10815         // Second half of f64 is passed on the stack.
10816         // Work out the address of the stack slot.
10817         if (!StackPtr.getNode())
10818           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10819         // Emit the store.
10820         MemOpChains.push_back(
10821             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10822       } else {
10823         // Second half of f64 is passed in another GPR.
10824         assert(RegLo < RISCV::X31 && "Invalid register pair");
10825         Register RegHigh = RegLo + 1;
10826         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10827       }
10828       continue;
10829     }
10830 
10831     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10832     // as any other MemLoc.
10833 
10834     // Promote the value if needed.
10835     // For now, only handle fully promoted and indirect arguments.
10836     if (VA.getLocInfo() == CCValAssign::Indirect) {
10837       // Store the argument in a stack slot and pass its address.
10838       Align StackAlign =
10839           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10840                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10841       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10842       // If the original argument was split (e.g. i128), we need
10843       // to store the required parts of it here (and pass just one address).
10844       // Vectors may be partly split to registers and partly to the stack, in
10845       // which case the base address is partly offset and subsequent stores are
10846       // relative to that.
10847       unsigned ArgIndex = Outs[i].OrigArgIndex;
10848       unsigned ArgPartOffset = Outs[i].PartOffset;
10849       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10850       // Calculate the total size to store. We don't have access to what we're
10851       // actually storing other than performing the loop and collecting the
10852       // info.
10853       SmallVector<std::pair<SDValue, SDValue>> Parts;
10854       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10855         SDValue PartValue = OutVals[i + 1];
10856         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10857         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10858         EVT PartVT = PartValue.getValueType();
10859         if (PartVT.isScalableVector())
10860           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10861         StoredSize += PartVT.getStoreSize();
10862         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10863         Parts.push_back(std::make_pair(PartValue, Offset));
10864         ++i;
10865       }
10866       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10867       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10868       MemOpChains.push_back(
10869           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10870                        MachinePointerInfo::getFixedStack(MF, FI)));
10871       for (const auto &Part : Parts) {
10872         SDValue PartValue = Part.first;
10873         SDValue PartOffset = Part.second;
10874         SDValue Address =
10875             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10876         MemOpChains.push_back(
10877             DAG.getStore(Chain, DL, PartValue, Address,
10878                          MachinePointerInfo::getFixedStack(MF, FI)));
10879       }
10880       ArgValue = SpillSlot;
10881     } else {
10882       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10883     }
10884 
10885     // Use local copy if it is a byval arg.
10886     if (Flags.isByVal())
10887       ArgValue = ByValArgs[j++];
10888 
10889     if (VA.isRegLoc()) {
10890       // Queue up the argument copies and emit them at the end.
10891       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10892     } else {
10893       assert(VA.isMemLoc() && "Argument not register or memory");
10894       assert(!IsTailCall && "Tail call not allowed if stack is used "
10895                             "for passing parameters");
10896 
10897       // Work out the address of the stack slot.
10898       if (!StackPtr.getNode())
10899         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10900       SDValue Address =
10901           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10902                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10903 
10904       // Emit the store.
10905       MemOpChains.push_back(
10906           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10907     }
10908   }
10909 
10910   // Join the stores, which are independent of one another.
10911   if (!MemOpChains.empty())
10912     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10913 
10914   SDValue Glue;
10915 
10916   // Build a sequence of copy-to-reg nodes, chained and glued together.
10917   for (auto &Reg : RegsToPass) {
10918     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10919     Glue = Chain.getValue(1);
10920   }
10921 
10922   // Validate that none of the argument registers have been marked as
10923   // reserved, if so report an error. Do the same for the return address if this
10924   // is not a tailcall.
10925   validateCCReservedRegs(RegsToPass, MF);
10926   if (!IsTailCall &&
10927       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10928     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10929         MF.getFunction(),
10930         "Return address register required, but has been reserved."});
10931 
10932   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10933   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10934   // split it and then direct call can be matched by PseudoCALL.
10935   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10936     const GlobalValue *GV = S->getGlobal();
10937 
10938     unsigned OpFlags = RISCVII::MO_CALL;
10939     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10940       OpFlags = RISCVII::MO_PLT;
10941 
10942     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10943   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10944     unsigned OpFlags = RISCVII::MO_CALL;
10945 
10946     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10947                                                  nullptr))
10948       OpFlags = RISCVII::MO_PLT;
10949 
10950     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10951   }
10952 
10953   // The first call operand is the chain and the second is the target address.
10954   SmallVector<SDValue, 8> Ops;
10955   Ops.push_back(Chain);
10956   Ops.push_back(Callee);
10957 
10958   // Add argument registers to the end of the list so that they are
10959   // known live into the call.
10960   for (auto &Reg : RegsToPass)
10961     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10962 
10963   if (!IsTailCall) {
10964     // Add a register mask operand representing the call-preserved registers.
10965     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10966     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10967     assert(Mask && "Missing call preserved mask for calling convention");
10968     Ops.push_back(DAG.getRegisterMask(Mask));
10969   }
10970 
10971   // Glue the call to the argument copies, if any.
10972   if (Glue.getNode())
10973     Ops.push_back(Glue);
10974 
10975   // Emit the call.
10976   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10977 
10978   if (IsTailCall) {
10979     MF.getFrameInfo().setHasTailCall();
10980     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10981   }
10982 
10983   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10984   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10985   Glue = Chain.getValue(1);
10986 
10987   // Mark the end of the call, which is glued to the call itself.
10988   Chain = DAG.getCALLSEQ_END(Chain,
10989                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10990                              DAG.getConstant(0, DL, PtrVT, true),
10991                              Glue, DL);
10992   Glue = Chain.getValue(1);
10993 
10994   // Assign locations to each value returned by this call.
10995   SmallVector<CCValAssign, 16> RVLocs;
10996   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10997   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10998 
10999   // Copy all of the result registers out of their specified physreg.
11000   for (auto &VA : RVLocs) {
11001     // Copy the value out
11002     SDValue RetValue =
11003         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
11004     // Glue the RetValue to the end of the call sequence
11005     Chain = RetValue.getValue(1);
11006     Glue = RetValue.getValue(2);
11007 
11008     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11009       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
11010       SDValue RetValue2 =
11011           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
11012       Chain = RetValue2.getValue(1);
11013       Glue = RetValue2.getValue(2);
11014       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
11015                              RetValue2);
11016     }
11017 
11018     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
11019 
11020     InVals.push_back(RetValue);
11021   }
11022 
11023   return Chain;
11024 }
11025 
11026 bool RISCVTargetLowering::CanLowerReturn(
11027     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
11028     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
11029   SmallVector<CCValAssign, 16> RVLocs;
11030   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
11031 
11032   Optional<unsigned> FirstMaskArgument;
11033   if (Subtarget.hasVInstructions())
11034     FirstMaskArgument = preAssignMask(Outs);
11035 
11036   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
11037     MVT VT = Outs[i].VT;
11038     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
11039     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
11040     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
11041                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
11042                  *this, FirstMaskArgument))
11043       return false;
11044   }
11045   return true;
11046 }
11047 
11048 SDValue
11049 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
11050                                  bool IsVarArg,
11051                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
11052                                  const SmallVectorImpl<SDValue> &OutVals,
11053                                  const SDLoc &DL, SelectionDAG &DAG) const {
11054   const MachineFunction &MF = DAG.getMachineFunction();
11055   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11056 
11057   // Stores the assignment of the return value to a location.
11058   SmallVector<CCValAssign, 16> RVLocs;
11059 
11060   // Info about the registers and stack slot.
11061   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
11062                  *DAG.getContext());
11063 
11064   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
11065                     nullptr, CC_RISCV);
11066 
11067   if (CallConv == CallingConv::GHC && !RVLocs.empty())
11068     report_fatal_error("GHC functions return void only");
11069 
11070   SDValue Glue;
11071   SmallVector<SDValue, 4> RetOps(1, Chain);
11072 
11073   // Copy the result values into the output registers.
11074   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
11075     SDValue Val = OutVals[i];
11076     CCValAssign &VA = RVLocs[i];
11077     assert(VA.isRegLoc() && "Can only return in registers!");
11078 
11079     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11080       // Handle returning f64 on RV32D with a soft float ABI.
11081       assert(VA.isRegLoc() && "Expected return via registers");
11082       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
11083                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
11084       SDValue Lo = SplitF64.getValue(0);
11085       SDValue Hi = SplitF64.getValue(1);
11086       Register RegLo = VA.getLocReg();
11087       assert(RegLo < RISCV::X31 && "Invalid register pair");
11088       Register RegHi = RegLo + 1;
11089 
11090       if (STI.isRegisterReservedByUser(RegLo) ||
11091           STI.isRegisterReservedByUser(RegHi))
11092         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11093             MF.getFunction(),
11094             "Return value register required, but has been reserved."});
11095 
11096       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
11097       Glue = Chain.getValue(1);
11098       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
11099       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
11100       Glue = Chain.getValue(1);
11101       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
11102     } else {
11103       // Handle a 'normal' return.
11104       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
11105       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
11106 
11107       if (STI.isRegisterReservedByUser(VA.getLocReg()))
11108         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11109             MF.getFunction(),
11110             "Return value register required, but has been reserved."});
11111 
11112       // Guarantee that all emitted copies are stuck together.
11113       Glue = Chain.getValue(1);
11114       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
11115     }
11116   }
11117 
11118   RetOps[0] = Chain; // Update chain.
11119 
11120   // Add the glue node if we have it.
11121   if (Glue.getNode()) {
11122     RetOps.push_back(Glue);
11123   }
11124 
11125   unsigned RetOpc = RISCVISD::RET_FLAG;
11126   // Interrupt service routines use different return instructions.
11127   const Function &Func = DAG.getMachineFunction().getFunction();
11128   if (Func.hasFnAttribute("interrupt")) {
11129     if (!Func.getReturnType()->isVoidTy())
11130       report_fatal_error(
11131           "Functions with the interrupt attribute must have void return type!");
11132 
11133     MachineFunction &MF = DAG.getMachineFunction();
11134     StringRef Kind =
11135       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
11136 
11137     if (Kind == "user")
11138       RetOpc = RISCVISD::URET_FLAG;
11139     else if (Kind == "supervisor")
11140       RetOpc = RISCVISD::SRET_FLAG;
11141     else
11142       RetOpc = RISCVISD::MRET_FLAG;
11143   }
11144 
11145   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
11146 }
11147 
11148 void RISCVTargetLowering::validateCCReservedRegs(
11149     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
11150     MachineFunction &MF) const {
11151   const Function &F = MF.getFunction();
11152   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11153 
11154   if (llvm::any_of(Regs, [&STI](auto Reg) {
11155         return STI.isRegisterReservedByUser(Reg.first);
11156       }))
11157     F.getContext().diagnose(DiagnosticInfoUnsupported{
11158         F, "Argument register required, but has been reserved."});
11159 }
11160 
11161 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11162   return CI->isTailCall();
11163 }
11164 
11165 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
11166 #define NODE_NAME_CASE(NODE)                                                   \
11167   case RISCVISD::NODE:                                                         \
11168     return "RISCVISD::" #NODE;
11169   // clang-format off
11170   switch ((RISCVISD::NodeType)Opcode) {
11171   case RISCVISD::FIRST_NUMBER:
11172     break;
11173   NODE_NAME_CASE(RET_FLAG)
11174   NODE_NAME_CASE(URET_FLAG)
11175   NODE_NAME_CASE(SRET_FLAG)
11176   NODE_NAME_CASE(MRET_FLAG)
11177   NODE_NAME_CASE(CALL)
11178   NODE_NAME_CASE(SELECT_CC)
11179   NODE_NAME_CASE(BR_CC)
11180   NODE_NAME_CASE(BuildPairF64)
11181   NODE_NAME_CASE(SplitF64)
11182   NODE_NAME_CASE(TAIL)
11183   NODE_NAME_CASE(ADD_LO)
11184   NODE_NAME_CASE(HI)
11185   NODE_NAME_CASE(LLA)
11186   NODE_NAME_CASE(ADD_TPREL)
11187   NODE_NAME_CASE(MULHSU)
11188   NODE_NAME_CASE(SLLW)
11189   NODE_NAME_CASE(SRAW)
11190   NODE_NAME_CASE(SRLW)
11191   NODE_NAME_CASE(DIVW)
11192   NODE_NAME_CASE(DIVUW)
11193   NODE_NAME_CASE(REMUW)
11194   NODE_NAME_CASE(ROLW)
11195   NODE_NAME_CASE(RORW)
11196   NODE_NAME_CASE(CLZW)
11197   NODE_NAME_CASE(CTZW)
11198   NODE_NAME_CASE(FSLW)
11199   NODE_NAME_CASE(FSRW)
11200   NODE_NAME_CASE(FSL)
11201   NODE_NAME_CASE(FSR)
11202   NODE_NAME_CASE(FMV_H_X)
11203   NODE_NAME_CASE(FMV_X_ANYEXTH)
11204   NODE_NAME_CASE(FMV_X_SIGNEXTH)
11205   NODE_NAME_CASE(FMV_W_X_RV64)
11206   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
11207   NODE_NAME_CASE(FCVT_X)
11208   NODE_NAME_CASE(FCVT_XU)
11209   NODE_NAME_CASE(FCVT_W_RV64)
11210   NODE_NAME_CASE(FCVT_WU_RV64)
11211   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
11212   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
11213   NODE_NAME_CASE(READ_CYCLE_WIDE)
11214   NODE_NAME_CASE(GREV)
11215   NODE_NAME_CASE(GREVW)
11216   NODE_NAME_CASE(GORC)
11217   NODE_NAME_CASE(GORCW)
11218   NODE_NAME_CASE(SHFL)
11219   NODE_NAME_CASE(SHFLW)
11220   NODE_NAME_CASE(UNSHFL)
11221   NODE_NAME_CASE(UNSHFLW)
11222   NODE_NAME_CASE(BFP)
11223   NODE_NAME_CASE(BFPW)
11224   NODE_NAME_CASE(BCOMPRESS)
11225   NODE_NAME_CASE(BCOMPRESSW)
11226   NODE_NAME_CASE(BDECOMPRESS)
11227   NODE_NAME_CASE(BDECOMPRESSW)
11228   NODE_NAME_CASE(VMV_V_X_VL)
11229   NODE_NAME_CASE(VFMV_V_F_VL)
11230   NODE_NAME_CASE(VMV_X_S)
11231   NODE_NAME_CASE(VMV_S_X_VL)
11232   NODE_NAME_CASE(VFMV_S_F_VL)
11233   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
11234   NODE_NAME_CASE(READ_VLENB)
11235   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
11236   NODE_NAME_CASE(VSLIDEUP_VL)
11237   NODE_NAME_CASE(VSLIDE1UP_VL)
11238   NODE_NAME_CASE(VSLIDEDOWN_VL)
11239   NODE_NAME_CASE(VSLIDE1DOWN_VL)
11240   NODE_NAME_CASE(VID_VL)
11241   NODE_NAME_CASE(VFNCVT_ROD_VL)
11242   NODE_NAME_CASE(VECREDUCE_ADD_VL)
11243   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
11244   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
11245   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
11246   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
11247   NODE_NAME_CASE(VECREDUCE_AND_VL)
11248   NODE_NAME_CASE(VECREDUCE_OR_VL)
11249   NODE_NAME_CASE(VECREDUCE_XOR_VL)
11250   NODE_NAME_CASE(VECREDUCE_FADD_VL)
11251   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
11252   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
11253   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
11254   NODE_NAME_CASE(ADD_VL)
11255   NODE_NAME_CASE(AND_VL)
11256   NODE_NAME_CASE(MUL_VL)
11257   NODE_NAME_CASE(OR_VL)
11258   NODE_NAME_CASE(SDIV_VL)
11259   NODE_NAME_CASE(SHL_VL)
11260   NODE_NAME_CASE(SREM_VL)
11261   NODE_NAME_CASE(SRA_VL)
11262   NODE_NAME_CASE(SRL_VL)
11263   NODE_NAME_CASE(SUB_VL)
11264   NODE_NAME_CASE(UDIV_VL)
11265   NODE_NAME_CASE(UREM_VL)
11266   NODE_NAME_CASE(XOR_VL)
11267   NODE_NAME_CASE(SADDSAT_VL)
11268   NODE_NAME_CASE(UADDSAT_VL)
11269   NODE_NAME_CASE(SSUBSAT_VL)
11270   NODE_NAME_CASE(USUBSAT_VL)
11271   NODE_NAME_CASE(FADD_VL)
11272   NODE_NAME_CASE(FSUB_VL)
11273   NODE_NAME_CASE(FMUL_VL)
11274   NODE_NAME_CASE(FDIV_VL)
11275   NODE_NAME_CASE(FNEG_VL)
11276   NODE_NAME_CASE(FABS_VL)
11277   NODE_NAME_CASE(FSQRT_VL)
11278   NODE_NAME_CASE(FMA_VL)
11279   NODE_NAME_CASE(FCOPYSIGN_VL)
11280   NODE_NAME_CASE(SMIN_VL)
11281   NODE_NAME_CASE(SMAX_VL)
11282   NODE_NAME_CASE(UMIN_VL)
11283   NODE_NAME_CASE(UMAX_VL)
11284   NODE_NAME_CASE(FMINNUM_VL)
11285   NODE_NAME_CASE(FMAXNUM_VL)
11286   NODE_NAME_CASE(MULHS_VL)
11287   NODE_NAME_CASE(MULHU_VL)
11288   NODE_NAME_CASE(FP_TO_SINT_VL)
11289   NODE_NAME_CASE(FP_TO_UINT_VL)
11290   NODE_NAME_CASE(SINT_TO_FP_VL)
11291   NODE_NAME_CASE(UINT_TO_FP_VL)
11292   NODE_NAME_CASE(FP_EXTEND_VL)
11293   NODE_NAME_CASE(FP_ROUND_VL)
11294   NODE_NAME_CASE(VWMUL_VL)
11295   NODE_NAME_CASE(VWMULU_VL)
11296   NODE_NAME_CASE(VWMULSU_VL)
11297   NODE_NAME_CASE(VWADD_VL)
11298   NODE_NAME_CASE(VWADDU_VL)
11299   NODE_NAME_CASE(VWSUB_VL)
11300   NODE_NAME_CASE(VWSUBU_VL)
11301   NODE_NAME_CASE(VWADD_W_VL)
11302   NODE_NAME_CASE(VWADDU_W_VL)
11303   NODE_NAME_CASE(VWSUB_W_VL)
11304   NODE_NAME_CASE(VWSUBU_W_VL)
11305   NODE_NAME_CASE(SETCC_VL)
11306   NODE_NAME_CASE(VSELECT_VL)
11307   NODE_NAME_CASE(VP_MERGE_VL)
11308   NODE_NAME_CASE(VMAND_VL)
11309   NODE_NAME_CASE(VMOR_VL)
11310   NODE_NAME_CASE(VMXOR_VL)
11311   NODE_NAME_CASE(VMCLR_VL)
11312   NODE_NAME_CASE(VMSET_VL)
11313   NODE_NAME_CASE(VRGATHER_VX_VL)
11314   NODE_NAME_CASE(VRGATHER_VV_VL)
11315   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
11316   NODE_NAME_CASE(VSEXT_VL)
11317   NODE_NAME_CASE(VZEXT_VL)
11318   NODE_NAME_CASE(VCPOP_VL)
11319   NODE_NAME_CASE(READ_CSR)
11320   NODE_NAME_CASE(WRITE_CSR)
11321   NODE_NAME_CASE(SWAP_CSR)
11322   }
11323   // clang-format on
11324   return nullptr;
11325 #undef NODE_NAME_CASE
11326 }
11327 
11328 /// getConstraintType - Given a constraint letter, return the type of
11329 /// constraint it is for this target.
11330 RISCVTargetLowering::ConstraintType
11331 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
11332   if (Constraint.size() == 1) {
11333     switch (Constraint[0]) {
11334     default:
11335       break;
11336     case 'f':
11337       return C_RegisterClass;
11338     case 'I':
11339     case 'J':
11340     case 'K':
11341       return C_Immediate;
11342     case 'A':
11343       return C_Memory;
11344     case 'S': // A symbolic address
11345       return C_Other;
11346     }
11347   } else {
11348     if (Constraint == "vr" || Constraint == "vm")
11349       return C_RegisterClass;
11350   }
11351   return TargetLowering::getConstraintType(Constraint);
11352 }
11353 
11354 std::pair<unsigned, const TargetRegisterClass *>
11355 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11356                                                   StringRef Constraint,
11357                                                   MVT VT) const {
11358   // First, see if this is a constraint that directly corresponds to a
11359   // RISCV register class.
11360   if (Constraint.size() == 1) {
11361     switch (Constraint[0]) {
11362     case 'r':
11363       // TODO: Support fixed vectors up to XLen for P extension?
11364       if (VT.isVector())
11365         break;
11366       return std::make_pair(0U, &RISCV::GPRRegClass);
11367     case 'f':
11368       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11369         return std::make_pair(0U, &RISCV::FPR16RegClass);
11370       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11371         return std::make_pair(0U, &RISCV::FPR32RegClass);
11372       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11373         return std::make_pair(0U, &RISCV::FPR64RegClass);
11374       break;
11375     default:
11376       break;
11377     }
11378   } else if (Constraint == "vr") {
11379     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11380                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11381       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11382         return std::make_pair(0U, RC);
11383     }
11384   } else if (Constraint == "vm") {
11385     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11386       return std::make_pair(0U, &RISCV::VMV0RegClass);
11387   }
11388 
11389   // Clang will correctly decode the usage of register name aliases into their
11390   // official names. However, other frontends like `rustc` do not. This allows
11391   // users of these frontends to use the ABI names for registers in LLVM-style
11392   // register constraints.
11393   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11394                                .Case("{zero}", RISCV::X0)
11395                                .Case("{ra}", RISCV::X1)
11396                                .Case("{sp}", RISCV::X2)
11397                                .Case("{gp}", RISCV::X3)
11398                                .Case("{tp}", RISCV::X4)
11399                                .Case("{t0}", RISCV::X5)
11400                                .Case("{t1}", RISCV::X6)
11401                                .Case("{t2}", RISCV::X7)
11402                                .Cases("{s0}", "{fp}", RISCV::X8)
11403                                .Case("{s1}", RISCV::X9)
11404                                .Case("{a0}", RISCV::X10)
11405                                .Case("{a1}", RISCV::X11)
11406                                .Case("{a2}", RISCV::X12)
11407                                .Case("{a3}", RISCV::X13)
11408                                .Case("{a4}", RISCV::X14)
11409                                .Case("{a5}", RISCV::X15)
11410                                .Case("{a6}", RISCV::X16)
11411                                .Case("{a7}", RISCV::X17)
11412                                .Case("{s2}", RISCV::X18)
11413                                .Case("{s3}", RISCV::X19)
11414                                .Case("{s4}", RISCV::X20)
11415                                .Case("{s5}", RISCV::X21)
11416                                .Case("{s6}", RISCV::X22)
11417                                .Case("{s7}", RISCV::X23)
11418                                .Case("{s8}", RISCV::X24)
11419                                .Case("{s9}", RISCV::X25)
11420                                .Case("{s10}", RISCV::X26)
11421                                .Case("{s11}", RISCV::X27)
11422                                .Case("{t3}", RISCV::X28)
11423                                .Case("{t4}", RISCV::X29)
11424                                .Case("{t5}", RISCV::X30)
11425                                .Case("{t6}", RISCV::X31)
11426                                .Default(RISCV::NoRegister);
11427   if (XRegFromAlias != RISCV::NoRegister)
11428     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11429 
11430   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11431   // TableGen record rather than the AsmName to choose registers for InlineAsm
11432   // constraints, plus we want to match those names to the widest floating point
11433   // register type available, manually select floating point registers here.
11434   //
11435   // The second case is the ABI name of the register, so that frontends can also
11436   // use the ABI names in register constraint lists.
11437   if (Subtarget.hasStdExtF()) {
11438     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11439                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11440                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11441                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11442                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11443                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11444                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11445                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11446                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11447                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11448                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11449                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11450                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11451                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11452                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11453                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11454                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11455                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11456                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11457                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11458                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11459                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11460                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11461                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11462                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11463                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11464                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11465                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11466                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11467                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11468                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11469                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11470                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11471                         .Default(RISCV::NoRegister);
11472     if (FReg != RISCV::NoRegister) {
11473       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11474       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11475         unsigned RegNo = FReg - RISCV::F0_F;
11476         unsigned DReg = RISCV::F0_D + RegNo;
11477         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11478       }
11479       if (VT == MVT::f32 || VT == MVT::Other)
11480         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11481       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11482         unsigned RegNo = FReg - RISCV::F0_F;
11483         unsigned HReg = RISCV::F0_H + RegNo;
11484         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11485       }
11486     }
11487   }
11488 
11489   if (Subtarget.hasVInstructions()) {
11490     Register VReg = StringSwitch<Register>(Constraint.lower())
11491                         .Case("{v0}", RISCV::V0)
11492                         .Case("{v1}", RISCV::V1)
11493                         .Case("{v2}", RISCV::V2)
11494                         .Case("{v3}", RISCV::V3)
11495                         .Case("{v4}", RISCV::V4)
11496                         .Case("{v5}", RISCV::V5)
11497                         .Case("{v6}", RISCV::V6)
11498                         .Case("{v7}", RISCV::V7)
11499                         .Case("{v8}", RISCV::V8)
11500                         .Case("{v9}", RISCV::V9)
11501                         .Case("{v10}", RISCV::V10)
11502                         .Case("{v11}", RISCV::V11)
11503                         .Case("{v12}", RISCV::V12)
11504                         .Case("{v13}", RISCV::V13)
11505                         .Case("{v14}", RISCV::V14)
11506                         .Case("{v15}", RISCV::V15)
11507                         .Case("{v16}", RISCV::V16)
11508                         .Case("{v17}", RISCV::V17)
11509                         .Case("{v18}", RISCV::V18)
11510                         .Case("{v19}", RISCV::V19)
11511                         .Case("{v20}", RISCV::V20)
11512                         .Case("{v21}", RISCV::V21)
11513                         .Case("{v22}", RISCV::V22)
11514                         .Case("{v23}", RISCV::V23)
11515                         .Case("{v24}", RISCV::V24)
11516                         .Case("{v25}", RISCV::V25)
11517                         .Case("{v26}", RISCV::V26)
11518                         .Case("{v27}", RISCV::V27)
11519                         .Case("{v28}", RISCV::V28)
11520                         .Case("{v29}", RISCV::V29)
11521                         .Case("{v30}", RISCV::V30)
11522                         .Case("{v31}", RISCV::V31)
11523                         .Default(RISCV::NoRegister);
11524     if (VReg != RISCV::NoRegister) {
11525       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11526         return std::make_pair(VReg, &RISCV::VMRegClass);
11527       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11528         return std::make_pair(VReg, &RISCV::VRRegClass);
11529       for (const auto *RC :
11530            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11531         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11532           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11533           return std::make_pair(VReg, RC);
11534         }
11535       }
11536     }
11537   }
11538 
11539   std::pair<Register, const TargetRegisterClass *> Res =
11540       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11541 
11542   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11543   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11544   // Subtarget into account.
11545   if (Res.second == &RISCV::GPRF16RegClass ||
11546       Res.second == &RISCV::GPRF32RegClass ||
11547       Res.second == &RISCV::GPRF64RegClass)
11548     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11549 
11550   return Res;
11551 }
11552 
11553 unsigned
11554 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11555   // Currently only support length 1 constraints.
11556   if (ConstraintCode.size() == 1) {
11557     switch (ConstraintCode[0]) {
11558     case 'A':
11559       return InlineAsm::Constraint_A;
11560     default:
11561       break;
11562     }
11563   }
11564 
11565   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11566 }
11567 
11568 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11569     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11570     SelectionDAG &DAG) const {
11571   // Currently only support length 1 constraints.
11572   if (Constraint.length() == 1) {
11573     switch (Constraint[0]) {
11574     case 'I':
11575       // Validate & create a 12-bit signed immediate operand.
11576       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11577         uint64_t CVal = C->getSExtValue();
11578         if (isInt<12>(CVal))
11579           Ops.push_back(
11580               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11581       }
11582       return;
11583     case 'J':
11584       // Validate & create an integer zero operand.
11585       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11586         if (C->getZExtValue() == 0)
11587           Ops.push_back(
11588               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11589       return;
11590     case 'K':
11591       // Validate & create a 5-bit unsigned immediate operand.
11592       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11593         uint64_t CVal = C->getZExtValue();
11594         if (isUInt<5>(CVal))
11595           Ops.push_back(
11596               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11597       }
11598       return;
11599     case 'S':
11600       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11601         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11602                                                  GA->getValueType(0)));
11603       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11604         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11605                                                 BA->getValueType(0)));
11606       }
11607       return;
11608     default:
11609       break;
11610     }
11611   }
11612   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11613 }
11614 
11615 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11616                                                    Instruction *Inst,
11617                                                    AtomicOrdering Ord) const {
11618   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11619     return Builder.CreateFence(Ord);
11620   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11621     return Builder.CreateFence(AtomicOrdering::Release);
11622   return nullptr;
11623 }
11624 
11625 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11626                                                     Instruction *Inst,
11627                                                     AtomicOrdering Ord) const {
11628   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11629     return Builder.CreateFence(AtomicOrdering::Acquire);
11630   return nullptr;
11631 }
11632 
11633 TargetLowering::AtomicExpansionKind
11634 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11635   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11636   // point operations can't be used in an lr/sc sequence without breaking the
11637   // forward-progress guarantee.
11638   if (AI->isFloatingPointOperation())
11639     return AtomicExpansionKind::CmpXChg;
11640 
11641   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11642   if (Size == 8 || Size == 16)
11643     return AtomicExpansionKind::MaskedIntrinsic;
11644   return AtomicExpansionKind::None;
11645 }
11646 
11647 static Intrinsic::ID
11648 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11649   if (XLen == 32) {
11650     switch (BinOp) {
11651     default:
11652       llvm_unreachable("Unexpected AtomicRMW BinOp");
11653     case AtomicRMWInst::Xchg:
11654       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11655     case AtomicRMWInst::Add:
11656       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11657     case AtomicRMWInst::Sub:
11658       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11659     case AtomicRMWInst::Nand:
11660       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11661     case AtomicRMWInst::Max:
11662       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11663     case AtomicRMWInst::Min:
11664       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11665     case AtomicRMWInst::UMax:
11666       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11667     case AtomicRMWInst::UMin:
11668       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11669     }
11670   }
11671 
11672   if (XLen == 64) {
11673     switch (BinOp) {
11674     default:
11675       llvm_unreachable("Unexpected AtomicRMW BinOp");
11676     case AtomicRMWInst::Xchg:
11677       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11678     case AtomicRMWInst::Add:
11679       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11680     case AtomicRMWInst::Sub:
11681       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11682     case AtomicRMWInst::Nand:
11683       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11684     case AtomicRMWInst::Max:
11685       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11686     case AtomicRMWInst::Min:
11687       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11688     case AtomicRMWInst::UMax:
11689       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11690     case AtomicRMWInst::UMin:
11691       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11692     }
11693   }
11694 
11695   llvm_unreachable("Unexpected XLen\n");
11696 }
11697 
11698 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11699     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11700     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11701   unsigned XLen = Subtarget.getXLen();
11702   Value *Ordering =
11703       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11704   Type *Tys[] = {AlignedAddr->getType()};
11705   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11706       AI->getModule(),
11707       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11708 
11709   if (XLen == 64) {
11710     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11711     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11712     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11713   }
11714 
11715   Value *Result;
11716 
11717   // Must pass the shift amount needed to sign extend the loaded value prior
11718   // to performing a signed comparison for min/max. ShiftAmt is the number of
11719   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11720   // is the number of bits to left+right shift the value in order to
11721   // sign-extend.
11722   if (AI->getOperation() == AtomicRMWInst::Min ||
11723       AI->getOperation() == AtomicRMWInst::Max) {
11724     const DataLayout &DL = AI->getModule()->getDataLayout();
11725     unsigned ValWidth =
11726         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11727     Value *SextShamt =
11728         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11729     Result = Builder.CreateCall(LrwOpScwLoop,
11730                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11731   } else {
11732     Result =
11733         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11734   }
11735 
11736   if (XLen == 64)
11737     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11738   return Result;
11739 }
11740 
11741 TargetLowering::AtomicExpansionKind
11742 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11743     AtomicCmpXchgInst *CI) const {
11744   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11745   if (Size == 8 || Size == 16)
11746     return AtomicExpansionKind::MaskedIntrinsic;
11747   return AtomicExpansionKind::None;
11748 }
11749 
11750 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11751     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11752     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11753   unsigned XLen = Subtarget.getXLen();
11754   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11755   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11756   if (XLen == 64) {
11757     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11758     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11759     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11760     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11761   }
11762   Type *Tys[] = {AlignedAddr->getType()};
11763   Function *MaskedCmpXchg =
11764       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11765   Value *Result = Builder.CreateCall(
11766       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11767   if (XLen == 64)
11768     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11769   return Result;
11770 }
11771 
11772 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT,
11773                                                         EVT DataVT) const {
11774   return false;
11775 }
11776 
11777 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11778                                                EVT VT) const {
11779   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11780     return false;
11781 
11782   switch (FPVT.getSimpleVT().SimpleTy) {
11783   case MVT::f16:
11784     return Subtarget.hasStdExtZfh();
11785   case MVT::f32:
11786     return Subtarget.hasStdExtF();
11787   case MVT::f64:
11788     return Subtarget.hasStdExtD();
11789   default:
11790     return false;
11791   }
11792 }
11793 
11794 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11795   // If we are using the small code model, we can reduce size of jump table
11796   // entry to 4 bytes.
11797   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11798       getTargetMachine().getCodeModel() == CodeModel::Small) {
11799     return MachineJumpTableInfo::EK_Custom32;
11800   }
11801   return TargetLowering::getJumpTableEncoding();
11802 }
11803 
11804 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11805     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11806     unsigned uid, MCContext &Ctx) const {
11807   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11808          getTargetMachine().getCodeModel() == CodeModel::Small);
11809   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11810 }
11811 
11812 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11813                                                      EVT VT) const {
11814   VT = VT.getScalarType();
11815 
11816   if (!VT.isSimple())
11817     return false;
11818 
11819   switch (VT.getSimpleVT().SimpleTy) {
11820   case MVT::f16:
11821     return Subtarget.hasStdExtZfh();
11822   case MVT::f32:
11823     return Subtarget.hasStdExtF();
11824   case MVT::f64:
11825     return Subtarget.hasStdExtD();
11826   default:
11827     break;
11828   }
11829 
11830   return false;
11831 }
11832 
11833 Register RISCVTargetLowering::getExceptionPointerRegister(
11834     const Constant *PersonalityFn) const {
11835   return RISCV::X10;
11836 }
11837 
11838 Register RISCVTargetLowering::getExceptionSelectorRegister(
11839     const Constant *PersonalityFn) const {
11840   return RISCV::X11;
11841 }
11842 
11843 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11844   // Return false to suppress the unnecessary extensions if the LibCall
11845   // arguments or return value is f32 type for LP64 ABI.
11846   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11847   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11848     return false;
11849 
11850   return true;
11851 }
11852 
11853 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11854   if (Subtarget.is64Bit() && Type == MVT::i32)
11855     return true;
11856 
11857   return IsSigned;
11858 }
11859 
11860 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11861                                                  SDValue C) const {
11862   // Check integral scalar types.
11863   if (VT.isScalarInteger()) {
11864     // Omit the optimization if the sub target has the M extension and the data
11865     // size exceeds XLen.
11866     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11867       return false;
11868     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11869       // Break the MUL to a SLLI and an ADD/SUB.
11870       const APInt &Imm = ConstNode->getAPIntValue();
11871       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11872           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11873         return true;
11874       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11875       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11876           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11877            (Imm - 8).isPowerOf2()))
11878         return true;
11879       // Omit the following optimization if the sub target has the M extension
11880       // and the data size >= XLen.
11881       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11882         return false;
11883       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11884       // a pair of LUI/ADDI.
11885       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11886         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11887         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11888             (1 - ImmS).isPowerOf2())
11889         return true;
11890       }
11891     }
11892   }
11893 
11894   return false;
11895 }
11896 
11897 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
11898                                                       SDValue ConstNode) const {
11899   // Let the DAGCombiner decide for vectors.
11900   EVT VT = AddNode.getValueType();
11901   if (VT.isVector())
11902     return true;
11903 
11904   // Let the DAGCombiner decide for larger types.
11905   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11906     return true;
11907 
11908   // It is worse if c1 is simm12 while c1*c2 is not.
11909   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11910   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11911   const APInt &C1 = C1Node->getAPIntValue();
11912   const APInt &C2 = C2Node->getAPIntValue();
11913   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11914     return false;
11915 
11916   // Default to true and let the DAGCombiner decide.
11917   return true;
11918 }
11919 
11920 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11921     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11922     bool *Fast) const {
11923   if (!VT.isVector()) {
11924     if (Fast)
11925       *Fast = false;
11926     return Subtarget.enableUnalignedScalarMem();
11927   }
11928 
11929   // All vector implementations must support element alignment
11930   EVT ElemVT = VT.getVectorElementType();
11931   if (Alignment >= ElemVT.getStoreSize()) {
11932     if (Fast)
11933       *Fast = true;
11934     return true;
11935   }
11936 
11937   return false;
11938 }
11939 
11940 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11941     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11942     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11943   bool IsABIRegCopy = CC.has_value();
11944   EVT ValueVT = Val.getValueType();
11945   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11946     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11947     // and cast to f32.
11948     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11949     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11950     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11951                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11952     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11953     Parts[0] = Val;
11954     return true;
11955   }
11956 
11957   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11958     LLVMContext &Context = *DAG.getContext();
11959     EVT ValueEltVT = ValueVT.getVectorElementType();
11960     EVT PartEltVT = PartVT.getVectorElementType();
11961     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11962     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11963     if (PartVTBitSize % ValueVTBitSize == 0) {
11964       assert(PartVTBitSize >= ValueVTBitSize);
11965       // If the element types are different, bitcast to the same element type of
11966       // PartVT first.
11967       // Give an example here, we want copy a <vscale x 1 x i8> value to
11968       // <vscale x 4 x i16>.
11969       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11970       // subvector, then we can bitcast to <vscale x 4 x i16>.
11971       if (ValueEltVT != PartEltVT) {
11972         if (PartVTBitSize > ValueVTBitSize) {
11973           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11974           assert(Count != 0 && "The number of element should not be zero.");
11975           EVT SameEltTypeVT =
11976               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11977           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11978                             DAG.getUNDEF(SameEltTypeVT), Val,
11979                             DAG.getVectorIdxConstant(0, DL));
11980         }
11981         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11982       } else {
11983         Val =
11984             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11985                         Val, DAG.getVectorIdxConstant(0, DL));
11986       }
11987       Parts[0] = Val;
11988       return true;
11989     }
11990   }
11991   return false;
11992 }
11993 
11994 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11995     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11996     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11997   bool IsABIRegCopy = CC.has_value();
11998   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11999     SDValue Val = Parts[0];
12000 
12001     // Cast the f32 to i32, truncate to i16, and cast back to f16.
12002     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
12003     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
12004     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
12005     return Val;
12006   }
12007 
12008   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
12009     LLVMContext &Context = *DAG.getContext();
12010     SDValue Val = Parts[0];
12011     EVT ValueEltVT = ValueVT.getVectorElementType();
12012     EVT PartEltVT = PartVT.getVectorElementType();
12013     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
12014     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
12015     if (PartVTBitSize % ValueVTBitSize == 0) {
12016       assert(PartVTBitSize >= ValueVTBitSize);
12017       EVT SameEltTypeVT = ValueVT;
12018       // If the element types are different, convert it to the same element type
12019       // of PartVT.
12020       // Give an example here, we want copy a <vscale x 1 x i8> value from
12021       // <vscale x 4 x i16>.
12022       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
12023       // then we can extract <vscale x 1 x i8>.
12024       if (ValueEltVT != PartEltVT) {
12025         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
12026         assert(Count != 0 && "The number of element should not be zero.");
12027         SameEltTypeVT =
12028             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
12029         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
12030       }
12031       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
12032                         DAG.getVectorIdxConstant(0, DL));
12033       return Val;
12034     }
12035   }
12036   return SDValue();
12037 }
12038 
12039 SDValue
12040 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12041                                    SelectionDAG &DAG,
12042                                    SmallVectorImpl<SDNode *> &Created) const {
12043   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
12044   if (isIntDivCheap(N->getValueType(0), Attr))
12045     return SDValue(N, 0); // Lower SDIV as SDIV
12046 
12047   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
12048          "Unexpected divisor!");
12049 
12050   // Conditional move is needed, so do the transformation iff Zbt is enabled.
12051   if (!Subtarget.hasStdExtZbt())
12052     return SDValue();
12053 
12054   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
12055   // Besides, more critical path instructions will be generated when dividing
12056   // by 2. So we keep using the original DAGs for these cases.
12057   unsigned Lg2 = Divisor.countTrailingZeros();
12058   if (Lg2 == 1 || Lg2 >= 12)
12059     return SDValue();
12060 
12061   // fold (sdiv X, pow2)
12062   EVT VT = N->getValueType(0);
12063   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
12064     return SDValue();
12065 
12066   SDLoc DL(N);
12067   SDValue N0 = N->getOperand(0);
12068   SDValue Zero = DAG.getConstant(0, DL, VT);
12069   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
12070 
12071   // Add (N0 < 0) ? Pow2 - 1 : 0;
12072   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
12073   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
12074   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
12075 
12076   Created.push_back(Cmp.getNode());
12077   Created.push_back(Add.getNode());
12078   Created.push_back(Sel.getNode());
12079 
12080   // Divide by pow2.
12081   SDValue SRA =
12082       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
12083 
12084   // If we're dividing by a positive value, we're done.  Otherwise, we must
12085   // negate the result.
12086   if (Divisor.isNonNegative())
12087     return SRA;
12088 
12089   Created.push_back(SRA.getNode());
12090   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
12091 }
12092 
12093 #define GET_REGISTER_MATCHER
12094 #include "RISCVGenAsmMatcher.inc"
12095 
12096 Register
12097 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
12098                                        const MachineFunction &MF) const {
12099   Register Reg = MatchRegisterAltName(RegName);
12100   if (Reg == RISCV::NoRegister)
12101     Reg = MatchRegisterName(RegName);
12102   if (Reg == RISCV::NoRegister)
12103     report_fatal_error(
12104         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
12105   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
12106   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
12107     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
12108                              StringRef(RegName) + "\"."));
12109   return Reg;
12110 }
12111 
12112 namespace llvm {
12113 namespace RISCVVIntrinsicsTable {
12114 
12115 #define GET_RISCVVIntrinsicsTable_IMPL
12116 #include "RISCVGenSearchableTables.inc"
12117 
12118 } // namespace RISCVVIntrinsicsTable
12119 
12120 } // namespace llvm
12121