xref: /freebsd/contrib/llvm-project/llvm/lib/Target/RISCV/RISCVISelLowering.cpp (revision 972a253a57b6f144b0e4a3e2080a2a0076ec55a0)
1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/DiagnosticPrinter.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/IntrinsicsRISCV.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/KnownBits.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "riscv-lower"
45 
46 STATISTIC(NumTailCalls, "Number of tail calls");
47 
48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
49                                          const RISCVSubtarget &STI)
50     : TargetLowering(TM), Subtarget(STI) {
51 
52   if (Subtarget.isRV32E())
53     report_fatal_error("Codegen not yet implemented for RV32E");
54 
55   RISCVABI::ABI ABI = Subtarget.getTargetABI();
56   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
57 
58   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
59       !Subtarget.hasStdExtF()) {
60     errs() << "Hard-float 'f' ABI can't be used for a target that "
61                 "doesn't support the F instruction set extension (ignoring "
62                           "target-abi)\n";
63     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
64   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
65              !Subtarget.hasStdExtD()) {
66     errs() << "Hard-float 'd' ABI can't be used for a target that "
67               "doesn't support the D instruction set extension (ignoring "
68               "target-abi)\n";
69     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
70   }
71 
72   switch (ABI) {
73   default:
74     report_fatal_error("Don't know how to lower this ABI");
75   case RISCVABI::ABI_ILP32:
76   case RISCVABI::ABI_ILP32F:
77   case RISCVABI::ABI_ILP32D:
78   case RISCVABI::ABI_LP64:
79   case RISCVABI::ABI_LP64F:
80   case RISCVABI::ABI_LP64D:
81     break;
82   }
83 
84   MVT XLenVT = Subtarget.getXLenVT();
85 
86   // Set up the register classes.
87   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
88 
89   if (Subtarget.hasStdExtZfh())
90     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
91   if (Subtarget.hasStdExtF())
92     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
93   if (Subtarget.hasStdExtD())
94     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
95 
96   static const MVT::SimpleValueType BoolVecVTs[] = {
97       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
98       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
99   static const MVT::SimpleValueType IntVecVTs[] = {
100       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
101       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
102       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
103       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
104       MVT::nxv4i64, MVT::nxv8i64};
105   static const MVT::SimpleValueType F16VecVTs[] = {
106       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
107       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
108   static const MVT::SimpleValueType F32VecVTs[] = {
109       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
110   static const MVT::SimpleValueType F64VecVTs[] = {
111       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
112 
113   if (Subtarget.hasVInstructions()) {
114     auto addRegClassForRVV = [this](MVT VT) {
115       // Disable the smallest fractional LMUL types if ELEN is less than
116       // RVVBitsPerBlock.
117       unsigned MinElts = RISCV::RVVBitsPerBlock / Subtarget.getELEN();
118       if (VT.getVectorMinNumElements() < MinElts)
119         return;
120 
121       unsigned Size = VT.getSizeInBits().getKnownMinValue();
122       const TargetRegisterClass *RC;
123       if (Size <= RISCV::RVVBitsPerBlock)
124         RC = &RISCV::VRRegClass;
125       else if (Size == 2 * RISCV::RVVBitsPerBlock)
126         RC = &RISCV::VRM2RegClass;
127       else if (Size == 4 * RISCV::RVVBitsPerBlock)
128         RC = &RISCV::VRM4RegClass;
129       else if (Size == 8 * RISCV::RVVBitsPerBlock)
130         RC = &RISCV::VRM8RegClass;
131       else
132         llvm_unreachable("Unexpected size");
133 
134       addRegisterClass(VT, RC);
135     };
136 
137     for (MVT VT : BoolVecVTs)
138       addRegClassForRVV(VT);
139     for (MVT VT : IntVecVTs) {
140       if (VT.getVectorElementType() == MVT::i64 &&
141           !Subtarget.hasVInstructionsI64())
142         continue;
143       addRegClassForRVV(VT);
144     }
145 
146     if (Subtarget.hasVInstructionsF16())
147       for (MVT VT : F16VecVTs)
148         addRegClassForRVV(VT);
149 
150     if (Subtarget.hasVInstructionsF32())
151       for (MVT VT : F32VecVTs)
152         addRegClassForRVV(VT);
153 
154     if (Subtarget.hasVInstructionsF64())
155       for (MVT VT : F64VecVTs)
156         addRegClassForRVV(VT);
157 
158     if (Subtarget.useRVVForFixedLengthVectors()) {
159       auto addRegClassForFixedVectors = [this](MVT VT) {
160         MVT ContainerVT = getContainerForFixedLengthVector(VT);
161         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
162         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
163         addRegisterClass(VT, TRI.getRegClass(RCID));
164       };
165       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
166         if (useRVVForFixedLengthVectorVT(VT))
167           addRegClassForFixedVectors(VT);
168 
169       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
170         if (useRVVForFixedLengthVectorVT(VT))
171           addRegClassForFixedVectors(VT);
172     }
173   }
174 
175   // Compute derived properties from the register classes.
176   computeRegisterProperties(STI.getRegisterInfo());
177 
178   setStackPointerRegisterToSaveRestore(RISCV::X2);
179 
180   setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, XLenVT,
181                    MVT::i1, Promote);
182 
183   // TODO: add all necessary setOperationAction calls.
184   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
185 
186   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
187   setOperationAction(ISD::BR_CC, XLenVT, Expand);
188   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
189   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
190 
191   setOperationAction({ISD::STACKSAVE, ISD::STACKRESTORE}, MVT::Other, Expand);
192 
193   setOperationAction(ISD::VASTART, MVT::Other, Custom);
194   setOperationAction({ISD::VAARG, ISD::VACOPY, ISD::VAEND}, MVT::Other, Expand);
195 
196   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
197 
198   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
199 
200   if (!Subtarget.hasStdExtZbb())
201     setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand);
202 
203   if (Subtarget.is64Bit()) {
204     setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
205 
206     setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL},
207                        MVT::i32, Custom);
208 
209     setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT},
210                        MVT::i32, Custom);
211   } else {
212     setLibcallName(
213         {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128},
214         nullptr);
215     setLibcallName(RTLIB::MULO_I64, nullptr);
216   }
217 
218   if (!Subtarget.hasStdExtM() && !Subtarget.hasStdExtZmmul()) {
219     setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU}, XLenVT, Expand);
220   } else {
221     if (Subtarget.is64Bit()) {
222       setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom);
223     } else {
224       setOperationAction(ISD::MUL, MVT::i64, Custom);
225     }
226   }
227 
228   if (!Subtarget.hasStdExtM()) {
229     setOperationAction({ISD::SDIV, ISD::UDIV, ISD::SREM, ISD::UREM},
230                        XLenVT, Expand);
231   } else {
232     if (Subtarget.is64Bit()) {
233       setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM},
234                           {MVT::i8, MVT::i16, MVT::i32}, Custom);
235     }
236   }
237 
238   setOperationAction(
239       {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT,
240       Expand);
241 
242   setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT,
243                      Custom);
244 
245   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
246       Subtarget.hasStdExtZbkb()) {
247     if (Subtarget.is64Bit())
248       setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom);
249   } else {
250     setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand);
251   }
252 
253   if (Subtarget.hasStdExtZbp()) {
254     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
255     // more combining.
256     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom);
257 
258     // BSWAP i8 doesn't exist.
259     setOperationAction(ISD::BITREVERSE, MVT::i8, Custom);
260 
261     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom);
262 
263     if (Subtarget.is64Bit())
264       setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom);
265   } else {
266     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
267     // pattern match it directly in isel.
268     setOperationAction(ISD::BSWAP, XLenVT,
269                        (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
270                            ? Legal
271                            : Expand);
272     // Zbkb can use rev8+brev8 to implement bitreverse.
273     setOperationAction(ISD::BITREVERSE, XLenVT,
274                        Subtarget.hasStdExtZbkb() ? Custom : Expand);
275   }
276 
277   if (Subtarget.hasStdExtZbb()) {
278     setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT,
279                        Legal);
280 
281     if (Subtarget.is64Bit())
282       setOperationAction(
283           {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF},
284           MVT::i32, Custom);
285   } else {
286     setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand);
287 
288     if (Subtarget.is64Bit())
289       setOperationAction(ISD::ABS, MVT::i32, Custom);
290   }
291 
292   if (Subtarget.hasStdExtZbt()) {
293     setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom);
294     setOperationAction(ISD::SELECT, XLenVT, Legal);
295 
296     if (Subtarget.is64Bit())
297       setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom);
298   } else {
299     setOperationAction(ISD::SELECT, XLenVT, Custom);
300   }
301 
302   static const unsigned FPLegalNodeTypes[] = {
303       ISD::FMINNUM,        ISD::FMAXNUM,       ISD::LRINT,
304       ISD::LLRINT,         ISD::LROUND,        ISD::LLROUND,
305       ISD::STRICT_LRINT,   ISD::STRICT_LLRINT, ISD::STRICT_LROUND,
306       ISD::STRICT_LLROUND, ISD::STRICT_FMA,    ISD::STRICT_FADD,
307       ISD::STRICT_FSUB,    ISD::STRICT_FMUL,   ISD::STRICT_FDIV,
308       ISD::STRICT_FSQRT,   ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS};
309 
310   static const ISD::CondCode FPCCToExpand[] = {
311       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
312       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
313       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
314 
315   static const unsigned FPOpToExpand[] = {
316       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
317       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
318 
319   if (Subtarget.hasStdExtZfh())
320     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
321 
322   if (Subtarget.hasStdExtZfh()) {
323     setOperationAction(FPLegalNodeTypes, MVT::f16, Legal);
324     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
325     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
326     setCondCodeAction(FPCCToExpand, MVT::f16, Expand);
327     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
328     setOperationAction(ISD::SELECT, MVT::f16, Custom);
329     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
330 
331     setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT,
332                         ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC,
333                         ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN,
334                         ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG,
335                         ISD::FLOG2, ISD::FLOG10},
336                        MVT::f16, Promote);
337 
338     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
339     // complete support for all operations in LegalizeDAG.
340 
341     // We need to custom promote this.
342     if (Subtarget.is64Bit())
343       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
344   }
345 
346   if (Subtarget.hasStdExtF()) {
347     setOperationAction(FPLegalNodeTypes, MVT::f32, Legal);
348     setCondCodeAction(FPCCToExpand, MVT::f32, Expand);
349     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
350     setOperationAction(ISD::SELECT, MVT::f32, Custom);
351     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
352     setOperationAction(FPOpToExpand, MVT::f32, Expand);
353     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
354     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
355   }
356 
357   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
358     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
359 
360   if (Subtarget.hasStdExtD()) {
361     setOperationAction(FPLegalNodeTypes, MVT::f64, Legal);
362     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
363     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
364     setCondCodeAction(FPCCToExpand, MVT::f64, Expand);
365     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
366     setOperationAction(ISD::SELECT, MVT::f64, Custom);
367     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
368     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
369     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
370     setOperationAction(FPOpToExpand, MVT::f64, Expand);
371     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
372     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
373   }
374 
375   if (Subtarget.is64Bit())
376     setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT,
377                         ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT},
378                        MVT::i32, Custom);
379 
380   if (Subtarget.hasStdExtF()) {
381     setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT,
382                        Custom);
383 
384     setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT,
385                         ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP},
386                        XLenVT, Legal);
387 
388     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
389     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
390   }
391 
392   setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool,
393                       ISD::JumpTable},
394                      XLenVT, Custom);
395 
396   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
397 
398   if (Subtarget.is64Bit())
399     setOperationAction(ISD::Constant, MVT::i64, Custom);
400 
401   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
402   // Unfortunately this can't be determined just from the ISA naming string.
403   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
404                      Subtarget.is64Bit() ? Legal : Custom);
405 
406   setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal);
407   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
408   if (Subtarget.is64Bit())
409     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
410 
411   if (Subtarget.hasStdExtA()) {
412     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
413     setMinCmpXchgSizeInBits(32);
414   } else {
415     setMaxAtomicSizeInBitsSupported(0);
416   }
417 
418   setBooleanContents(ZeroOrOneBooleanContent);
419 
420   if (Subtarget.hasVInstructions()) {
421     setBooleanVectorContents(ZeroOrOneBooleanContent);
422 
423     setOperationAction(ISD::VSCALE, XLenVT, Custom);
424 
425     // RVV intrinsics may have illegal operands.
426     // We also need to custom legalize vmv.x.s.
427     setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
428                        {MVT::i8, MVT::i16}, Custom);
429     if (Subtarget.is64Bit())
430       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
431     else
432       setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
433                          MVT::i64, Custom);
434 
435     setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID},
436                        MVT::Other, Custom);
437 
438     static const unsigned IntegerVPOps[] = {
439         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
440         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
441         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
442         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
443         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
444         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
445         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
446         ISD::VP_MERGE,       ISD::VP_SELECT,      ISD::VP_FPTOSI,
447         ISD::VP_FPTOUI,      ISD::VP_SETCC,       ISD::VP_SIGN_EXTEND,
448         ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE};
449 
450     static const unsigned FloatingPointVPOps[] = {
451         ISD::VP_FADD,        ISD::VP_FSUB,
452         ISD::VP_FMUL,        ISD::VP_FDIV,
453         ISD::VP_FNEG,        ISD::VP_FMA,
454         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
455         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX,
456         ISD::VP_MERGE,       ISD::VP_SELECT,
457         ISD::VP_SITOFP,      ISD::VP_UITOFP,
458         ISD::VP_SETCC,       ISD::VP_FP_ROUND,
459         ISD::VP_FP_EXTEND};
460 
461     static const unsigned IntegerVecReduceOps[] = {
462         ISD::VECREDUCE_ADD,  ISD::VECREDUCE_AND,  ISD::VECREDUCE_OR,
463         ISD::VECREDUCE_XOR,  ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
464         ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN};
465 
466     static const unsigned FloatingPointVecReduceOps[] = {
467         ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, ISD::VECREDUCE_FMIN,
468         ISD::VECREDUCE_FMAX};
469 
470     if (!Subtarget.is64Bit()) {
471       // We must custom-lower certain vXi64 operations on RV32 due to the vector
472       // element type being illegal.
473       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
474                          MVT::i64, Custom);
475 
476       setOperationAction(IntegerVecReduceOps, MVT::i64, Custom);
477 
478       setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND,
479                           ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR,
480                           ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN,
481                           ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN},
482                          MVT::i64, Custom);
483     }
484 
485     for (MVT VT : BoolVecVTs) {
486       if (!isTypeLegal(VT))
487         continue;
488 
489       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
490 
491       // Mask VTs are custom-expanded into a series of standard nodes
492       setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS,
493                           ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
494                          VT, Custom);
495 
496       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
497                          Custom);
498 
499       setOperationAction(ISD::SELECT, VT, Custom);
500       setOperationAction(
501           {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT,
502           Expand);
503 
504       setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom);
505 
506       setOperationAction(
507           {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
508           Custom);
509 
510       setOperationAction(
511           {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
512           Custom);
513 
514       // RVV has native int->float & float->int conversions where the
515       // element type sizes are within one power-of-two of each other. Any
516       // wider distances between type sizes have to be lowered as sequences
517       // which progressively narrow the gap in stages.
518       setOperationAction(
519           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
520           VT, Custom);
521 
522       // Expand all extending loads to types larger than this, and truncating
523       // stores from types larger than this.
524       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
525         setTruncStoreAction(OtherVT, VT, Expand);
526         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
527                          VT, Expand);
528       }
529 
530       setOperationAction(
531           {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT,
532           Custom);
533       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
534 
535       setOperationPromotedToType(
536           ISD::VECTOR_SPLICE, VT,
537           MVT::getVectorVT(MVT::i8, VT.getVectorElementCount()));
538     }
539 
540     for (MVT VT : IntVecVTs) {
541       if (!isTypeLegal(VT))
542         continue;
543 
544       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
545       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
546 
547       // Vectors implement MULHS/MULHU.
548       setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand);
549 
550       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
551       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV())
552         setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand);
553 
554       setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT,
555                          Legal);
556 
557       setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand);
558 
559       setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT,
560                          Expand);
561 
562       setOperationAction(ISD::BSWAP, VT, Expand);
563 
564       // Custom-lower extensions and truncations from/to mask types.
565       setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND},
566                          VT, Custom);
567 
568       // RVV has native int->float & float->int conversions where the
569       // element type sizes are within one power-of-two of each other. Any
570       // wider distances between type sizes have to be lowered as sequences
571       // which progressively narrow the gap in stages.
572       setOperationAction(
573           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
574           VT, Custom);
575 
576       setOperationAction(
577           {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal);
578 
579       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
580       // nodes which truncate by one power of two at a time.
581       setOperationAction(ISD::TRUNCATE, VT, Custom);
582 
583       // Custom-lower insert/extract operations to simplify patterns.
584       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
585                          Custom);
586 
587       // Custom-lower reduction operations to set up the corresponding custom
588       // nodes' operands.
589       setOperationAction(IntegerVecReduceOps, VT, Custom);
590 
591       setOperationAction(IntegerVPOps, VT, Custom);
592 
593       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
594 
595       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
596                          VT, Custom);
597 
598       setOperationAction(
599           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
600           Custom);
601 
602       setOperationAction(
603           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
604           VT, Custom);
605 
606       setOperationAction(ISD::SELECT, VT, Custom);
607       setOperationAction(ISD::SELECT_CC, VT, Expand);
608 
609       setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom);
610 
611       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
612         setTruncStoreAction(VT, OtherVT, Expand);
613         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
614                          VT, Expand);
615       }
616 
617       // Splice
618       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
619 
620       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
621       // type that can represent the value exactly.
622       if (VT.getVectorElementType() != MVT::i64) {
623         MVT FloatEltVT =
624             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
625         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
626         if (isTypeLegal(FloatVT)) {
627           setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
628                              Custom);
629         }
630       }
631     }
632 
633     // Expand various CCs to best match the RVV ISA, which natively supports UNE
634     // but no other unordered comparisons, and supports all ordered comparisons
635     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
636     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
637     // and we pattern-match those back to the "original", swapping operands once
638     // more. This way we catch both operations and both "vf" and "fv" forms with
639     // fewer patterns.
640     static const ISD::CondCode VFPCCToExpand[] = {
641         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
642         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
643         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
644     };
645 
646     // Sets common operation actions on RVV floating-point vector types.
647     const auto SetCommonVFPActions = [&](MVT VT) {
648       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
649       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
650       // sizes are within one power-of-two of each other. Therefore conversions
651       // between vXf16 and vXf64 must be lowered as sequences which convert via
652       // vXf32.
653       setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
654       // Custom-lower insert/extract operations to simplify patterns.
655       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
656                          Custom);
657       // Expand various condition codes (explained above).
658       setCondCodeAction(VFPCCToExpand, VT, Expand);
659 
660       setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal);
661 
662       setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
663                          VT, Custom);
664 
665       setOperationAction(FloatingPointVecReduceOps, VT, Custom);
666 
667       // Expand FP operations that need libcalls.
668       setOperationAction(ISD::FREM, VT, Expand);
669       setOperationAction(ISD::FPOW, VT, Expand);
670       setOperationAction(ISD::FCOS, VT, Expand);
671       setOperationAction(ISD::FSIN, VT, Expand);
672       setOperationAction(ISD::FSINCOS, VT, Expand);
673       setOperationAction(ISD::FEXP, VT, Expand);
674       setOperationAction(ISD::FEXP2, VT, Expand);
675       setOperationAction(ISD::FLOG, VT, Expand);
676       setOperationAction(ISD::FLOG2, VT, Expand);
677       setOperationAction(ISD::FLOG10, VT, Expand);
678       setOperationAction(ISD::FRINT, VT, Expand);
679       setOperationAction(ISD::FNEARBYINT, VT, Expand);
680 
681       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
682       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
683       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
684       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
685 
686       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
687 
688       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
689 
690       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
691                          VT, Custom);
692 
693       setOperationAction(
694           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
695           Custom);
696 
697       setOperationAction(ISD::SELECT, VT, Custom);
698       setOperationAction(ISD::SELECT_CC, VT, Expand);
699 
700       setOperationAction(
701           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
702           VT, Custom);
703 
704       setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom);
705 
706       setOperationAction(FloatingPointVPOps, VT, Custom);
707     };
708 
709     // Sets common extload/truncstore actions on RVV floating-point vector
710     // types.
711     const auto SetCommonVFPExtLoadTruncStoreActions =
712         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
713           for (auto SmallVT : SmallerVTs) {
714             setTruncStoreAction(VT, SmallVT, Expand);
715             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
716           }
717         };
718 
719     if (Subtarget.hasVInstructionsF16()) {
720       for (MVT VT : F16VecVTs) {
721         if (!isTypeLegal(VT))
722           continue;
723         SetCommonVFPActions(VT);
724       }
725     }
726 
727     if (Subtarget.hasVInstructionsF32()) {
728       for (MVT VT : F32VecVTs) {
729         if (!isTypeLegal(VT))
730           continue;
731         SetCommonVFPActions(VT);
732         SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
733       }
734     }
735 
736     if (Subtarget.hasVInstructionsF64()) {
737       for (MVT VT : F64VecVTs) {
738         if (!isTypeLegal(VT))
739           continue;
740         SetCommonVFPActions(VT);
741         SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
742         SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
743       }
744     }
745 
746     if (Subtarget.useRVVForFixedLengthVectors()) {
747       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
748         if (!useRVVForFixedLengthVectorVT(VT))
749           continue;
750 
751         // By default everything must be expanded.
752         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
753           setOperationAction(Op, VT, Expand);
754         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
755           setTruncStoreAction(VT, OtherVT, Expand);
756           setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD},
757                            OtherVT, VT, Expand);
758         }
759 
760         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
761         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
762                            Custom);
763 
764         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT,
765                            Custom);
766 
767         setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
768                            VT, Custom);
769 
770         setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
771 
772         setOperationAction(ISD::SETCC, VT, Custom);
773 
774         setOperationAction(ISD::SELECT, VT, Custom);
775 
776         setOperationAction(ISD::TRUNCATE, VT, Custom);
777 
778         setOperationAction(ISD::BITCAST, VT, Custom);
779 
780         setOperationAction(
781             {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
782             Custom);
783 
784         setOperationAction(
785             {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
786             Custom);
787 
788         setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT,
789                             ISD::FP_TO_UINT},
790                            VT, Custom);
791 
792         // Operations below are different for between masks and other vectors.
793         if (VT.getVectorElementType() == MVT::i1) {
794           setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND,
795                               ISD::OR, ISD::XOR},
796                              VT, Custom);
797 
798           setOperationAction(
799               {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE},
800               VT, Custom);
801           continue;
802         }
803 
804         // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
805         // it before type legalization for i64 vectors on RV32. It will then be
806         // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
807         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
808         // improvements first.
809         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
810           setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
811           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
812         }
813 
814         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
815         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
816 
817         setOperationAction(
818             {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom);
819 
820         setOperationAction(
821             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
822             Custom);
823 
824         setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR,
825                             ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV,
826                             ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL},
827                            VT, Custom);
828 
829         setOperationAction(
830             {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom);
831 
832         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
833         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV())
834           setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom);
835 
836         setOperationAction(
837             {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT,
838             Custom);
839 
840         setOperationAction(ISD::VSELECT, VT, Custom);
841         setOperationAction(ISD::SELECT_CC, VT, Expand);
842 
843         setOperationAction(
844             {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom);
845 
846         // Custom-lower reduction operations to set up the corresponding custom
847         // nodes' operands.
848         setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX,
849                             ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX,
850                             ISD::VECREDUCE_UMIN},
851                            VT, Custom);
852 
853         setOperationAction(IntegerVPOps, VT, Custom);
854 
855         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
856         // type that can represent the value exactly.
857         if (VT.getVectorElementType() != MVT::i64) {
858           MVT FloatEltVT =
859               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
860           EVT FloatVT =
861               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
862           if (isTypeLegal(FloatVT))
863             setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
864                                Custom);
865         }
866       }
867 
868       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
869         if (!useRVVForFixedLengthVectorVT(VT))
870           continue;
871 
872         // By default everything must be expanded.
873         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
874           setOperationAction(Op, VT, Expand);
875         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
876           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
877           setTruncStoreAction(VT, OtherVT, Expand);
878         }
879 
880         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
881         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
882                            Custom);
883 
884         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS,
885                             ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT,
886                             ISD::EXTRACT_VECTOR_ELT},
887                            VT, Custom);
888 
889         setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE,
890                             ISD::MGATHER, ISD::MSCATTER},
891                            VT, Custom);
892 
893         setOperationAction(
894             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
895             Custom);
896 
897         setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV,
898                             ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT,
899                             ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM},
900                            VT, Custom);
901 
902         setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
903 
904         setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
905                            VT, Custom);
906 
907         setCondCodeAction(VFPCCToExpand, VT, Expand);
908 
909         setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom);
910         setOperationAction(ISD::SELECT_CC, VT, Expand);
911 
912         setOperationAction(ISD::BITCAST, VT, Custom);
913 
914         setOperationAction(FloatingPointVecReduceOps, VT, Custom);
915 
916         setOperationAction(FloatingPointVPOps, VT, Custom);
917       }
918 
919       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
920       setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64},
921                          Custom);
922       if (Subtarget.hasStdExtZfh())
923         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
924       if (Subtarget.hasStdExtF())
925         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
926       if (Subtarget.hasStdExtD())
927         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
928     }
929   }
930 
931   // Function alignments.
932   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
933   setMinFunctionAlignment(FunctionAlignment);
934   setPrefFunctionAlignment(FunctionAlignment);
935 
936   setMinimumJumpTableEntries(5);
937 
938   // Jumps are expensive, compared to logic
939   setJumpIsExpensive();
940 
941   setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND,
942                        ISD::OR, ISD::XOR, ISD::SETCC});
943   if (Subtarget.is64Bit())
944     setTargetDAGCombine(ISD::SRA);
945 
946   if (Subtarget.hasStdExtF())
947     setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM});
948 
949   if (Subtarget.hasStdExtZbp())
950     setTargetDAGCombine({ISD::ROTL, ISD::ROTR});
951 
952   if (Subtarget.hasStdExtZbb())
953     setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN});
954 
955   if (Subtarget.hasStdExtZbkb())
956     setTargetDAGCombine(ISD::BITREVERSE);
957   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
958     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
959   if (Subtarget.hasStdExtF())
960     setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
961                          ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT});
962   if (Subtarget.hasVInstructions())
963     setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER,
964                          ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL,
965                          ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR});
966   if (Subtarget.useRVVForFixedLengthVectors())
967     setTargetDAGCombine(ISD::BITCAST);
968 
969   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
970   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
971 }
972 
973 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
974                                             LLVMContext &Context,
975                                             EVT VT) const {
976   if (!VT.isVector())
977     return getPointerTy(DL);
978   if (Subtarget.hasVInstructions() &&
979       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
980     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
981   return VT.changeVectorElementTypeToInteger();
982 }
983 
984 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
985   return Subtarget.getXLenVT();
986 }
987 
988 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
989                                              const CallInst &I,
990                                              MachineFunction &MF,
991                                              unsigned Intrinsic) const {
992   auto &DL = I.getModule()->getDataLayout();
993   switch (Intrinsic) {
994   default:
995     return false;
996   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
997   case Intrinsic::riscv_masked_atomicrmw_add_i32:
998   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
999   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1000   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1001   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1002   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1003   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1004   case Intrinsic::riscv_masked_cmpxchg_i32:
1005     Info.opc = ISD::INTRINSIC_W_CHAIN;
1006     Info.memVT = MVT::i32;
1007     Info.ptrVal = I.getArgOperand(0);
1008     Info.offset = 0;
1009     Info.align = Align(4);
1010     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1011                  MachineMemOperand::MOVolatile;
1012     return true;
1013   case Intrinsic::riscv_masked_strided_load:
1014     Info.opc = ISD::INTRINSIC_W_CHAIN;
1015     Info.ptrVal = I.getArgOperand(1);
1016     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1017     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1018     Info.size = MemoryLocation::UnknownSize;
1019     Info.flags |= MachineMemOperand::MOLoad;
1020     return true;
1021   case Intrinsic::riscv_masked_strided_store:
1022     Info.opc = ISD::INTRINSIC_VOID;
1023     Info.ptrVal = I.getArgOperand(1);
1024     Info.memVT =
1025         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1026     Info.align = Align(
1027         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1028         8);
1029     Info.size = MemoryLocation::UnknownSize;
1030     Info.flags |= MachineMemOperand::MOStore;
1031     return true;
1032   case Intrinsic::riscv_seg2_load:
1033   case Intrinsic::riscv_seg3_load:
1034   case Intrinsic::riscv_seg4_load:
1035   case Intrinsic::riscv_seg5_load:
1036   case Intrinsic::riscv_seg6_load:
1037   case Intrinsic::riscv_seg7_load:
1038   case Intrinsic::riscv_seg8_load:
1039     Info.opc = ISD::INTRINSIC_W_CHAIN;
1040     Info.ptrVal = I.getArgOperand(0);
1041     Info.memVT =
1042         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
1043     Info.align =
1044         Align(DL.getTypeSizeInBits(
1045                   I.getType()->getStructElementType(0)->getScalarType()) /
1046               8);
1047     Info.size = MemoryLocation::UnknownSize;
1048     Info.flags |= MachineMemOperand::MOLoad;
1049     return true;
1050   }
1051 }
1052 
1053 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1054                                                 const AddrMode &AM, Type *Ty,
1055                                                 unsigned AS,
1056                                                 Instruction *I) const {
1057   // No global is ever allowed as a base.
1058   if (AM.BaseGV)
1059     return false;
1060 
1061   // RVV instructions only support register addressing.
1062   if (Subtarget.hasVInstructions() && isa<VectorType>(Ty))
1063     return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs;
1064 
1065   // Require a 12-bit signed offset.
1066   if (!isInt<12>(AM.BaseOffs))
1067     return false;
1068 
1069   switch (AM.Scale) {
1070   case 0: // "r+i" or just "i", depending on HasBaseReg.
1071     break;
1072   case 1:
1073     if (!AM.HasBaseReg) // allow "r+i".
1074       break;
1075     return false; // disallow "r+r" or "r+r+i".
1076   default:
1077     return false;
1078   }
1079 
1080   return true;
1081 }
1082 
1083 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1084   return isInt<12>(Imm);
1085 }
1086 
1087 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1088   return isInt<12>(Imm);
1089 }
1090 
1091 // On RV32, 64-bit integers are split into their high and low parts and held
1092 // in two different registers, so the trunc is free since the low register can
1093 // just be used.
1094 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1095   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1096     return false;
1097   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1098   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1099   return (SrcBits == 64 && DestBits == 32);
1100 }
1101 
1102 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1103   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1104       !SrcVT.isInteger() || !DstVT.isInteger())
1105     return false;
1106   unsigned SrcBits = SrcVT.getSizeInBits();
1107   unsigned DestBits = DstVT.getSizeInBits();
1108   return (SrcBits == 64 && DestBits == 32);
1109 }
1110 
1111 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1112   // Zexts are free if they can be combined with a load.
1113   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1114   // poorly with type legalization of compares preferring sext.
1115   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1116     EVT MemVT = LD->getMemoryVT();
1117     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1118         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1119          LD->getExtensionType() == ISD::ZEXTLOAD))
1120       return true;
1121   }
1122 
1123   return TargetLowering::isZExtFree(Val, VT2);
1124 }
1125 
1126 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1127   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1128 }
1129 
1130 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const {
1131   return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
1132 }
1133 
1134 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1135   return Subtarget.hasStdExtZbb();
1136 }
1137 
1138 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1139   return Subtarget.hasStdExtZbb();
1140 }
1141 
1142 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1143   EVT VT = Y.getValueType();
1144 
1145   // FIXME: Support vectors once we have tests.
1146   if (VT.isVector())
1147     return false;
1148 
1149   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1150           Subtarget.hasStdExtZbkb()) &&
1151          !isa<ConstantSDNode>(Y);
1152 }
1153 
1154 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
1155   // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1156   auto *C = dyn_cast<ConstantSDNode>(Y);
1157   return C && C->getAPIntValue().ule(10);
1158 }
1159 
1160 bool RISCVTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1161                                                             Type *Ty) const {
1162   assert(Ty->isIntegerTy());
1163 
1164   unsigned BitSize = Ty->getIntegerBitWidth();
1165   if (BitSize > Subtarget.getXLen())
1166     return false;
1167 
1168   // Fast path, assume 32-bit immediates are cheap.
1169   int64_t Val = Imm.getSExtValue();
1170   if (isInt<32>(Val))
1171     return true;
1172 
1173   // A constant pool entry may be more aligned thant he load we're trying to
1174   // replace. If we don't support unaligned scalar mem, prefer the constant
1175   // pool.
1176   // TODO: Can the caller pass down the alignment?
1177   if (!Subtarget.enableUnalignedScalarMem())
1178     return true;
1179 
1180   // Prefer to keep the load if it would require many instructions.
1181   // This uses the same threshold we use for constant pools but doesn't
1182   // check useConstantPoolForLargeInts.
1183   // TODO: Should we keep the load only when we're definitely going to emit a
1184   // constant pool?
1185 
1186   RISCVMatInt::InstSeq Seq =
1187       RISCVMatInt::generateInstSeq(Val, Subtarget.getFeatureBits());
1188   return Seq.size() <= Subtarget.getMaxBuildIntsCost();
1189 }
1190 
1191 bool RISCVTargetLowering::
1192     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
1193         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
1194         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
1195         SelectionDAG &DAG) const {
1196   // One interesting pattern that we'd want to form is 'bit extract':
1197   //   ((1 >> Y) & 1) ==/!= 0
1198   // But we also need to be careful not to try to reverse that fold.
1199 
1200   // Is this '((1 >> Y) & 1)'?
1201   if (XC && OldShiftOpcode == ISD::SRL && XC->isOne())
1202     return false; // Keep the 'bit extract' pattern.
1203 
1204   // Will this be '((1 >> Y) & 1)' after the transform?
1205   if (NewShiftOpcode == ISD::SRL && CC->isOne())
1206     return true; // Do form the 'bit extract' pattern.
1207 
1208   // If 'X' is a constant, and we transform, then we will immediately
1209   // try to undo the fold, thus causing endless combine loop.
1210   // So only do the transform if X is not a constant. This matches the default
1211   // implementation of this function.
1212   return !XC;
1213 }
1214 
1215 /// Check if sinking \p I's operands to I's basic block is profitable, because
1216 /// the operands can be folded into a target instruction, e.g.
1217 /// splats of scalars can fold into vector instructions.
1218 bool RISCVTargetLowering::shouldSinkOperands(
1219     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1220   using namespace llvm::PatternMatch;
1221 
1222   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1223     return false;
1224 
1225   auto IsSinker = [&](Instruction *I, int Operand) {
1226     switch (I->getOpcode()) {
1227     case Instruction::Add:
1228     case Instruction::Sub:
1229     case Instruction::Mul:
1230     case Instruction::And:
1231     case Instruction::Or:
1232     case Instruction::Xor:
1233     case Instruction::FAdd:
1234     case Instruction::FSub:
1235     case Instruction::FMul:
1236     case Instruction::FDiv:
1237     case Instruction::ICmp:
1238     case Instruction::FCmp:
1239       return true;
1240     case Instruction::Shl:
1241     case Instruction::LShr:
1242     case Instruction::AShr:
1243     case Instruction::UDiv:
1244     case Instruction::SDiv:
1245     case Instruction::URem:
1246     case Instruction::SRem:
1247       return Operand == 1;
1248     case Instruction::Call:
1249       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1250         switch (II->getIntrinsicID()) {
1251         case Intrinsic::fma:
1252         case Intrinsic::vp_fma:
1253           return Operand == 0 || Operand == 1;
1254         // FIXME: Our patterns can only match vx/vf instructions when the splat
1255         // it on the RHS, because TableGen doesn't recognize our VP operations
1256         // as commutative.
1257         case Intrinsic::vp_add:
1258         case Intrinsic::vp_mul:
1259         case Intrinsic::vp_and:
1260         case Intrinsic::vp_or:
1261         case Intrinsic::vp_xor:
1262         case Intrinsic::vp_fadd:
1263         case Intrinsic::vp_fmul:
1264         case Intrinsic::vp_shl:
1265         case Intrinsic::vp_lshr:
1266         case Intrinsic::vp_ashr:
1267         case Intrinsic::vp_udiv:
1268         case Intrinsic::vp_sdiv:
1269         case Intrinsic::vp_urem:
1270         case Intrinsic::vp_srem:
1271           return Operand == 1;
1272         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1273         // explicit patterns for both LHS and RHS (as 'vr' versions).
1274         case Intrinsic::vp_sub:
1275         case Intrinsic::vp_fsub:
1276         case Intrinsic::vp_fdiv:
1277           return Operand == 0 || Operand == 1;
1278         default:
1279           return false;
1280         }
1281       }
1282       return false;
1283     default:
1284       return false;
1285     }
1286   };
1287 
1288   for (auto OpIdx : enumerate(I->operands())) {
1289     if (!IsSinker(I, OpIdx.index()))
1290       continue;
1291 
1292     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1293     // Make sure we are not already sinking this operand
1294     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1295       continue;
1296 
1297     // We are looking for a splat that can be sunk.
1298     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1299                              m_Undef(), m_ZeroMask())))
1300       continue;
1301 
1302     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1303     // and vector registers
1304     for (Use &U : Op->uses()) {
1305       Instruction *Insn = cast<Instruction>(U.getUser());
1306       if (!IsSinker(Insn, U.getOperandNo()))
1307         return false;
1308     }
1309 
1310     Ops.push_back(&Op->getOperandUse(0));
1311     Ops.push_back(&OpIdx.value());
1312   }
1313   return true;
1314 }
1315 
1316 bool RISCVTargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
1317   unsigned Opc = VecOp.getOpcode();
1318 
1319   // Assume target opcodes can't be scalarized.
1320   // TODO - do we have any exceptions?
1321   if (Opc >= ISD::BUILTIN_OP_END)
1322     return false;
1323 
1324   // If the vector op is not supported, try to convert to scalar.
1325   EVT VecVT = VecOp.getValueType();
1326   if (!isOperationLegalOrCustomOrPromote(Opc, VecVT))
1327     return true;
1328 
1329   // If the vector op is supported, but the scalar op is not, the transform may
1330   // not be worthwhile.
1331   EVT ScalarVT = VecVT.getScalarType();
1332   return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
1333 }
1334 
1335 bool RISCVTargetLowering::isOffsetFoldingLegal(
1336     const GlobalAddressSDNode *GA) const {
1337   // In order to maximise the opportunity for common subexpression elimination,
1338   // keep a separate ADD node for the global address offset instead of folding
1339   // it in the global address node. Later peephole optimisations may choose to
1340   // fold it back in when profitable.
1341   return false;
1342 }
1343 
1344 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1345                                        bool ForCodeSize) const {
1346   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1347   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1348     return false;
1349   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1350     return false;
1351   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1352     return false;
1353   return Imm.isZero();
1354 }
1355 
1356 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1357   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1358          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1359          (VT == MVT::f64 && Subtarget.hasStdExtD());
1360 }
1361 
1362 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1363                                                       CallingConv::ID CC,
1364                                                       EVT VT) const {
1365   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1366   // We might still end up using a GPR but that will be decided based on ABI.
1367   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1368   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1369     return MVT::f32;
1370 
1371   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1372 }
1373 
1374 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1375                                                            CallingConv::ID CC,
1376                                                            EVT VT) const {
1377   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1378   // We might still end up using a GPR but that will be decided based on ABI.
1379   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1380   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1381     return 1;
1382 
1383   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1384 }
1385 
1386 // Changes the condition code and swaps operands if necessary, so the SetCC
1387 // operation matches one of the comparisons supported directly by branches
1388 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1389 // with 1/-1.
1390 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1391                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1392   // If this is a single bit test that can't be handled by ANDI, shift the
1393   // bit to be tested to the MSB and perform a signed compare with 0.
1394   if (isIntEqualitySetCC(CC) && isNullConstant(RHS) &&
1395       LHS.getOpcode() == ISD::AND && LHS.hasOneUse() &&
1396       isa<ConstantSDNode>(LHS.getOperand(1))) {
1397     uint64_t Mask = LHS.getConstantOperandVal(1);
1398     if (isPowerOf2_64(Mask) && !isInt<12>(Mask)) {
1399       CC = CC == ISD::SETEQ ? ISD::SETGE : ISD::SETLT;
1400       unsigned ShAmt = LHS.getValueSizeInBits() - 1 - Log2_64(Mask);
1401       LHS = LHS.getOperand(0);
1402       if (ShAmt != 0)
1403         LHS = DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS,
1404                           DAG.getConstant(ShAmt, DL, LHS.getValueType()));
1405       return;
1406     }
1407   }
1408 
1409   if (auto *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1410     int64_t C = RHSC->getSExtValue();
1411     switch (CC) {
1412     default: break;
1413     case ISD::SETGT:
1414       // Convert X > -1 to X >= 0.
1415       if (C == -1) {
1416         RHS = DAG.getConstant(0, DL, RHS.getValueType());
1417         CC = ISD::SETGE;
1418         return;
1419       }
1420       break;
1421     case ISD::SETLT:
1422       // Convert X < 1 to 0 <= X.
1423       if (C == 1) {
1424         RHS = LHS;
1425         LHS = DAG.getConstant(0, DL, RHS.getValueType());
1426         CC = ISD::SETGE;
1427         return;
1428       }
1429       break;
1430     }
1431   }
1432 
1433   switch (CC) {
1434   default:
1435     break;
1436   case ISD::SETGT:
1437   case ISD::SETLE:
1438   case ISD::SETUGT:
1439   case ISD::SETULE:
1440     CC = ISD::getSetCCSwappedOperands(CC);
1441     std::swap(LHS, RHS);
1442     break;
1443   }
1444 }
1445 
1446 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1447   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1448   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1449   if (VT.getVectorElementType() == MVT::i1)
1450     KnownSize *= 8;
1451 
1452   switch (KnownSize) {
1453   default:
1454     llvm_unreachable("Invalid LMUL.");
1455   case 8:
1456     return RISCVII::VLMUL::LMUL_F8;
1457   case 16:
1458     return RISCVII::VLMUL::LMUL_F4;
1459   case 32:
1460     return RISCVII::VLMUL::LMUL_F2;
1461   case 64:
1462     return RISCVII::VLMUL::LMUL_1;
1463   case 128:
1464     return RISCVII::VLMUL::LMUL_2;
1465   case 256:
1466     return RISCVII::VLMUL::LMUL_4;
1467   case 512:
1468     return RISCVII::VLMUL::LMUL_8;
1469   }
1470 }
1471 
1472 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1473   switch (LMul) {
1474   default:
1475     llvm_unreachable("Invalid LMUL.");
1476   case RISCVII::VLMUL::LMUL_F8:
1477   case RISCVII::VLMUL::LMUL_F4:
1478   case RISCVII::VLMUL::LMUL_F2:
1479   case RISCVII::VLMUL::LMUL_1:
1480     return RISCV::VRRegClassID;
1481   case RISCVII::VLMUL::LMUL_2:
1482     return RISCV::VRM2RegClassID;
1483   case RISCVII::VLMUL::LMUL_4:
1484     return RISCV::VRM4RegClassID;
1485   case RISCVII::VLMUL::LMUL_8:
1486     return RISCV::VRM8RegClassID;
1487   }
1488 }
1489 
1490 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1491   RISCVII::VLMUL LMUL = getLMUL(VT);
1492   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1493       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1494       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1495       LMUL == RISCVII::VLMUL::LMUL_1) {
1496     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1497                   "Unexpected subreg numbering");
1498     return RISCV::sub_vrm1_0 + Index;
1499   }
1500   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1501     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1502                   "Unexpected subreg numbering");
1503     return RISCV::sub_vrm2_0 + Index;
1504   }
1505   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1506     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1507                   "Unexpected subreg numbering");
1508     return RISCV::sub_vrm4_0 + Index;
1509   }
1510   llvm_unreachable("Invalid vector type.");
1511 }
1512 
1513 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1514   if (VT.getVectorElementType() == MVT::i1)
1515     return RISCV::VRRegClassID;
1516   return getRegClassIDForLMUL(getLMUL(VT));
1517 }
1518 
1519 // Attempt to decompose a subvector insert/extract between VecVT and
1520 // SubVecVT via subregister indices. Returns the subregister index that
1521 // can perform the subvector insert/extract with the given element index, as
1522 // well as the index corresponding to any leftover subvectors that must be
1523 // further inserted/extracted within the register class for SubVecVT.
1524 std::pair<unsigned, unsigned>
1525 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1526     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1527     const RISCVRegisterInfo *TRI) {
1528   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1529                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1530                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1531                 "Register classes not ordered");
1532   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1533   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1534   // Try to compose a subregister index that takes us from the incoming
1535   // LMUL>1 register class down to the outgoing one. At each step we half
1536   // the LMUL:
1537   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1538   // Note that this is not guaranteed to find a subregister index, such as
1539   // when we are extracting from one VR type to another.
1540   unsigned SubRegIdx = RISCV::NoSubRegister;
1541   for (const unsigned RCID :
1542        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1543     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1544       VecVT = VecVT.getHalfNumVectorElementsVT();
1545       bool IsHi =
1546           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1547       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1548                                             getSubregIndexByMVT(VecVT, IsHi));
1549       if (IsHi)
1550         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1551     }
1552   return {SubRegIdx, InsertExtractIdx};
1553 }
1554 
1555 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1556 // stores for those types.
1557 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1558   return !Subtarget.useRVVForFixedLengthVectors() ||
1559          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1560 }
1561 
1562 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1563   if (ScalarTy->isPointerTy())
1564     return true;
1565 
1566   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1567       ScalarTy->isIntegerTy(32))
1568     return true;
1569 
1570   if (ScalarTy->isIntegerTy(64))
1571     return Subtarget.hasVInstructionsI64();
1572 
1573   if (ScalarTy->isHalfTy())
1574     return Subtarget.hasVInstructionsF16();
1575   if (ScalarTy->isFloatTy())
1576     return Subtarget.hasVInstructionsF32();
1577   if (ScalarTy->isDoubleTy())
1578     return Subtarget.hasVInstructionsF64();
1579 
1580   return false;
1581 }
1582 
1583 static SDValue getVLOperand(SDValue Op) {
1584   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1585           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1586          "Unexpected opcode");
1587   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1588   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1589   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1590       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1591   if (!II)
1592     return SDValue();
1593   return Op.getOperand(II->VLOperand + 1 + HasChain);
1594 }
1595 
1596 static bool useRVVForFixedLengthVectorVT(MVT VT,
1597                                          const RISCVSubtarget &Subtarget) {
1598   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1599   if (!Subtarget.useRVVForFixedLengthVectors())
1600     return false;
1601 
1602   // We only support a set of vector types with a consistent maximum fixed size
1603   // across all supported vector element types to avoid legalization issues.
1604   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1605   // fixed-length vector type we support is 1024 bytes.
1606   if (VT.getFixedSizeInBits() > 1024 * 8)
1607     return false;
1608 
1609   unsigned MinVLen = Subtarget.getRealMinVLen();
1610 
1611   MVT EltVT = VT.getVectorElementType();
1612 
1613   // Don't use RVV for vectors we cannot scalarize if required.
1614   switch (EltVT.SimpleTy) {
1615   // i1 is supported but has different rules.
1616   default:
1617     return false;
1618   case MVT::i1:
1619     // Masks can only use a single register.
1620     if (VT.getVectorNumElements() > MinVLen)
1621       return false;
1622     MinVLen /= 8;
1623     break;
1624   case MVT::i8:
1625   case MVT::i16:
1626   case MVT::i32:
1627     break;
1628   case MVT::i64:
1629     if (!Subtarget.hasVInstructionsI64())
1630       return false;
1631     break;
1632   case MVT::f16:
1633     if (!Subtarget.hasVInstructionsF16())
1634       return false;
1635     break;
1636   case MVT::f32:
1637     if (!Subtarget.hasVInstructionsF32())
1638       return false;
1639     break;
1640   case MVT::f64:
1641     if (!Subtarget.hasVInstructionsF64())
1642       return false;
1643     break;
1644   }
1645 
1646   // Reject elements larger than ELEN.
1647   if (EltVT.getSizeInBits() > Subtarget.getELEN())
1648     return false;
1649 
1650   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1651   // Don't use RVV for types that don't fit.
1652   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1653     return false;
1654 
1655   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1656   // the base fixed length RVV support in place.
1657   if (!VT.isPow2VectorType())
1658     return false;
1659 
1660   return true;
1661 }
1662 
1663 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1664   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1665 }
1666 
1667 // Return the largest legal scalable vector type that matches VT's element type.
1668 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1669                                             const RISCVSubtarget &Subtarget) {
1670   // This may be called before legal types are setup.
1671   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1672           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1673          "Expected legal fixed length vector!");
1674 
1675   unsigned MinVLen = Subtarget.getRealMinVLen();
1676   unsigned MaxELen = Subtarget.getELEN();
1677 
1678   MVT EltVT = VT.getVectorElementType();
1679   switch (EltVT.SimpleTy) {
1680   default:
1681     llvm_unreachable("unexpected element type for RVV container");
1682   case MVT::i1:
1683   case MVT::i8:
1684   case MVT::i16:
1685   case MVT::i32:
1686   case MVT::i64:
1687   case MVT::f16:
1688   case MVT::f32:
1689   case MVT::f64: {
1690     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1691     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1692     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1693     unsigned NumElts =
1694         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1695     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1696     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1697     return MVT::getScalableVectorVT(EltVT, NumElts);
1698   }
1699   }
1700 }
1701 
1702 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1703                                             const RISCVSubtarget &Subtarget) {
1704   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1705                                           Subtarget);
1706 }
1707 
1708 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1709   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1710 }
1711 
1712 // Grow V to consume an entire RVV register.
1713 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1714                                        const RISCVSubtarget &Subtarget) {
1715   assert(VT.isScalableVector() &&
1716          "Expected to convert into a scalable vector!");
1717   assert(V.getValueType().isFixedLengthVector() &&
1718          "Expected a fixed length vector operand!");
1719   SDLoc DL(V);
1720   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1721   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1722 }
1723 
1724 // Shrink V so it's just big enough to maintain a VT's worth of data.
1725 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1726                                          const RISCVSubtarget &Subtarget) {
1727   assert(VT.isFixedLengthVector() &&
1728          "Expected to convert into a fixed length vector!");
1729   assert(V.getValueType().isScalableVector() &&
1730          "Expected a scalable vector operand!");
1731   SDLoc DL(V);
1732   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1733   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1734 }
1735 
1736 /// Return the type of the mask type suitable for masking the provided
1737 /// vector type.  This is simply an i1 element type vector of the same
1738 /// (possibly scalable) length.
1739 static MVT getMaskTypeFor(MVT VecVT) {
1740   assert(VecVT.isVector());
1741   ElementCount EC = VecVT.getVectorElementCount();
1742   return MVT::getVectorVT(MVT::i1, EC);
1743 }
1744 
1745 /// Creates an all ones mask suitable for masking a vector of type VecTy with
1746 /// vector length VL.  .
1747 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL,
1748                               SelectionDAG &DAG) {
1749   MVT MaskVT = getMaskTypeFor(VecVT);
1750   return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1751 }
1752 
1753 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1754 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1755 // the vector type that it is contained in.
1756 static std::pair<SDValue, SDValue>
1757 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1758                 const RISCVSubtarget &Subtarget) {
1759   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1760   MVT XLenVT = Subtarget.getXLenVT();
1761   SDValue VL = VecVT.isFixedLengthVector()
1762                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1763                    : DAG.getRegister(RISCV::X0, XLenVT);
1764   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
1765   return {Mask, VL};
1766 }
1767 
1768 // As above but assuming the given type is a scalable vector type.
1769 static std::pair<SDValue, SDValue>
1770 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1771                         const RISCVSubtarget &Subtarget) {
1772   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1773   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1774 }
1775 
1776 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1777 // of either is (currently) supported. This can get us into an infinite loop
1778 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1779 // as a ..., etc.
1780 // Until either (or both) of these can reliably lower any node, reporting that
1781 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1782 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1783 // which is not desirable.
1784 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1785     EVT VT, unsigned DefinedValues) const {
1786   return false;
1787 }
1788 
1789 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1790                                   const RISCVSubtarget &Subtarget) {
1791   // RISCV FP-to-int conversions saturate to the destination register size, but
1792   // don't produce 0 for nan. We can use a conversion instruction and fix the
1793   // nan case with a compare and a select.
1794   SDValue Src = Op.getOperand(0);
1795 
1796   EVT DstVT = Op.getValueType();
1797   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1798 
1799   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1800   unsigned Opc;
1801   if (SatVT == DstVT)
1802     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1803   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1804     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1805   else
1806     return SDValue();
1807   // FIXME: Support other SatVTs by clamping before or after the conversion.
1808 
1809   SDLoc DL(Op);
1810   SDValue FpToInt = DAG.getNode(
1811       Opc, DL, DstVT, Src,
1812       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1813 
1814   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1815   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1816 }
1817 
1818 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1819 // and back. Taking care to avoid converting values that are nan or already
1820 // correct.
1821 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1822 // have FRM dependencies modeled yet.
1823 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1824   MVT VT = Op.getSimpleValueType();
1825   assert(VT.isVector() && "Unexpected type");
1826 
1827   SDLoc DL(Op);
1828 
1829   // Freeze the source since we are increasing the number of uses.
1830   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1831 
1832   // Truncate to integer and convert back to FP.
1833   MVT IntVT = VT.changeVectorElementTypeToInteger();
1834   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1835   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1836 
1837   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1838 
1839   if (Op.getOpcode() == ISD::FCEIL) {
1840     // If the truncated value is the greater than or equal to the original
1841     // value, we've computed the ceil. Otherwise, we went the wrong way and
1842     // need to increase by 1.
1843     // FIXME: This should use a masked operation. Handle here or in isel?
1844     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1845                                  DAG.getConstantFP(1.0, DL, VT));
1846     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1847     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1848   } else if (Op.getOpcode() == ISD::FFLOOR) {
1849     // If the truncated value is the less than or equal to the original value,
1850     // we've computed the floor. Otherwise, we went the wrong way and need to
1851     // decrease by 1.
1852     // FIXME: This should use a masked operation. Handle here or in isel?
1853     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1854                                  DAG.getConstantFP(1.0, DL, VT));
1855     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1856     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1857   }
1858 
1859   // Restore the original sign so that -0.0 is preserved.
1860   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1861 
1862   // Determine the largest integer that can be represented exactly. This and
1863   // values larger than it don't have any fractional bits so don't need to
1864   // be converted.
1865   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1866   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1867   APFloat MaxVal = APFloat(FltSem);
1868   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1869                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1870   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1871 
1872   // If abs(Src) was larger than MaxVal or nan, keep it.
1873   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1874   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1875   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1876 }
1877 
1878 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1879 // This mode isn't supported in vector hardware on RISCV. But as long as we
1880 // aren't compiling with trapping math, we can emulate this with
1881 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1882 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1883 // dependencies modeled yet.
1884 // FIXME: Use masked operations to avoid final merge.
1885 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1886   MVT VT = Op.getSimpleValueType();
1887   assert(VT.isVector() && "Unexpected type");
1888 
1889   SDLoc DL(Op);
1890 
1891   // Freeze the source since we are increasing the number of uses.
1892   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1893 
1894   // We do the conversion on the absolute value and fix the sign at the end.
1895   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1896 
1897   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1898   bool Ignored;
1899   APFloat Point5Pred = APFloat(0.5f);
1900   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1901   Point5Pred.next(/*nextDown*/ true);
1902 
1903   // Add the adjustment.
1904   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1905                                DAG.getConstantFP(Point5Pred, DL, VT));
1906 
1907   // Truncate to integer and convert back to fp.
1908   MVT IntVT = VT.changeVectorElementTypeToInteger();
1909   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1910   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1911 
1912   // Restore the original sign.
1913   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1914 
1915   // Determine the largest integer that can be represented exactly. This and
1916   // values larger than it don't have any fractional bits so don't need to
1917   // be converted.
1918   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1919   APFloat MaxVal = APFloat(FltSem);
1920   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1921                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1922   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1923 
1924   // If abs(Src) was larger than MaxVal or nan, keep it.
1925   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1926   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1927   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1928 }
1929 
1930 struct VIDSequence {
1931   int64_t StepNumerator;
1932   unsigned StepDenominator;
1933   int64_t Addend;
1934 };
1935 
1936 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1937 // to the (non-zero) step S and start value X. This can be then lowered as the
1938 // RVV sequence (VID * S) + X, for example.
1939 // The step S is represented as an integer numerator divided by a positive
1940 // denominator. Note that the implementation currently only identifies
1941 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1942 // cannot detect 2/3, for example.
1943 // Note that this method will also match potentially unappealing index
1944 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1945 // determine whether this is worth generating code for.
1946 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1947   unsigned NumElts = Op.getNumOperands();
1948   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1949   if (!Op.getValueType().isInteger())
1950     return None;
1951 
1952   Optional<unsigned> SeqStepDenom;
1953   Optional<int64_t> SeqStepNum, SeqAddend;
1954   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1955   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1956   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1957     // Assume undef elements match the sequence; we just have to be careful
1958     // when interpolating across them.
1959     if (Op.getOperand(Idx).isUndef())
1960       continue;
1961     // The BUILD_VECTOR must be all constants.
1962     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1963       return None;
1964 
1965     uint64_t Val = Op.getConstantOperandVal(Idx) &
1966                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1967 
1968     if (PrevElt) {
1969       // Calculate the step since the last non-undef element, and ensure
1970       // it's consistent across the entire sequence.
1971       unsigned IdxDiff = Idx - PrevElt->second;
1972       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1973 
1974       // A zero-value value difference means that we're somewhere in the middle
1975       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1976       // step change before evaluating the sequence.
1977       if (ValDiff == 0)
1978         continue;
1979 
1980       int64_t Remainder = ValDiff % IdxDiff;
1981       // Normalize the step if it's greater than 1.
1982       if (Remainder != ValDiff) {
1983         // The difference must cleanly divide the element span.
1984         if (Remainder != 0)
1985           return None;
1986         ValDiff /= IdxDiff;
1987         IdxDiff = 1;
1988       }
1989 
1990       if (!SeqStepNum)
1991         SeqStepNum = ValDiff;
1992       else if (ValDiff != SeqStepNum)
1993         return None;
1994 
1995       if (!SeqStepDenom)
1996         SeqStepDenom = IdxDiff;
1997       else if (IdxDiff != *SeqStepDenom)
1998         return None;
1999     }
2000 
2001     // Record this non-undef element for later.
2002     if (!PrevElt || PrevElt->first != Val)
2003       PrevElt = std::make_pair(Val, Idx);
2004   }
2005 
2006   // We need to have logged a step for this to count as a legal index sequence.
2007   if (!SeqStepNum || !SeqStepDenom)
2008     return None;
2009 
2010   // Loop back through the sequence and validate elements we might have skipped
2011   // while waiting for a valid step. While doing this, log any sequence addend.
2012   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
2013     if (Op.getOperand(Idx).isUndef())
2014       continue;
2015     uint64_t Val = Op.getConstantOperandVal(Idx) &
2016                    maskTrailingOnes<uint64_t>(EltSizeInBits);
2017     uint64_t ExpectedVal =
2018         (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
2019     int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
2020     if (!SeqAddend)
2021       SeqAddend = Addend;
2022     else if (Addend != SeqAddend)
2023       return None;
2024   }
2025 
2026   assert(SeqAddend && "Must have an addend if we have a step");
2027 
2028   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
2029 }
2030 
2031 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
2032 // and lower it as a VRGATHER_VX_VL from the source vector.
2033 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
2034                                   SelectionDAG &DAG,
2035                                   const RISCVSubtarget &Subtarget) {
2036   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
2037     return SDValue();
2038   SDValue Vec = SplatVal.getOperand(0);
2039   // Only perform this optimization on vectors of the same size for simplicity.
2040   // Don't perform this optimization for i1 vectors.
2041   // FIXME: Support i1 vectors, maybe by promoting to i8?
2042   if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1)
2043     return SDValue();
2044   SDValue Idx = SplatVal.getOperand(1);
2045   // The index must be a legal type.
2046   if (Idx.getValueType() != Subtarget.getXLenVT())
2047     return SDValue();
2048 
2049   MVT ContainerVT = VT;
2050   if (VT.isFixedLengthVector()) {
2051     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2052     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2053   }
2054 
2055   SDValue Mask, VL;
2056   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2057 
2058   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
2059                                Idx, Mask, DAG.getUNDEF(ContainerVT), VL);
2060 
2061   if (!VT.isFixedLengthVector())
2062     return Gather;
2063 
2064   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2065 }
2066 
2067 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
2068                                  const RISCVSubtarget &Subtarget) {
2069   MVT VT = Op.getSimpleValueType();
2070   assert(VT.isFixedLengthVector() && "Unexpected vector!");
2071 
2072   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2073 
2074   SDLoc DL(Op);
2075   SDValue Mask, VL;
2076   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2077 
2078   MVT XLenVT = Subtarget.getXLenVT();
2079   unsigned NumElts = Op.getNumOperands();
2080 
2081   if (VT.getVectorElementType() == MVT::i1) {
2082     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
2083       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
2084       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
2085     }
2086 
2087     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
2088       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
2089       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
2090     }
2091 
2092     // Lower constant mask BUILD_VECTORs via an integer vector type, in
2093     // scalar integer chunks whose bit-width depends on the number of mask
2094     // bits and XLEN.
2095     // First, determine the most appropriate scalar integer type to use. This
2096     // is at most XLenVT, but may be shrunk to a smaller vector element type
2097     // according to the size of the final vector - use i8 chunks rather than
2098     // XLenVT if we're producing a v8i1. This results in more consistent
2099     // codegen across RV32 and RV64.
2100     unsigned NumViaIntegerBits =
2101         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2102     NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN());
2103     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2104       // If we have to use more than one INSERT_VECTOR_ELT then this
2105       // optimization is likely to increase code size; avoid peforming it in
2106       // such a case. We can use a load from a constant pool in this case.
2107       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2108         return SDValue();
2109       // Now we can create our integer vector type. Note that it may be larger
2110       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2111       MVT IntegerViaVecVT =
2112           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2113                            divideCeil(NumElts, NumViaIntegerBits));
2114 
2115       uint64_t Bits = 0;
2116       unsigned BitPos = 0, IntegerEltIdx = 0;
2117       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2118 
2119       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2120         // Once we accumulate enough bits to fill our scalar type, insert into
2121         // our vector and clear our accumulated data.
2122         if (I != 0 && I % NumViaIntegerBits == 0) {
2123           if (NumViaIntegerBits <= 32)
2124             Bits = SignExtend64<32>(Bits);
2125           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2126           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2127                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2128           Bits = 0;
2129           BitPos = 0;
2130           IntegerEltIdx++;
2131         }
2132         SDValue V = Op.getOperand(I);
2133         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2134         Bits |= ((uint64_t)BitValue << BitPos);
2135       }
2136 
2137       // Insert the (remaining) scalar value into position in our integer
2138       // vector type.
2139       if (NumViaIntegerBits <= 32)
2140         Bits = SignExtend64<32>(Bits);
2141       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2142       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2143                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2144 
2145       if (NumElts < NumViaIntegerBits) {
2146         // If we're producing a smaller vector than our minimum legal integer
2147         // type, bitcast to the equivalent (known-legal) mask type, and extract
2148         // our final mask.
2149         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2150         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2151         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2152                           DAG.getConstant(0, DL, XLenVT));
2153       } else {
2154         // Else we must have produced an integer type with the same size as the
2155         // mask type; bitcast for the final result.
2156         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2157         Vec = DAG.getBitcast(VT, Vec);
2158       }
2159 
2160       return Vec;
2161     }
2162 
2163     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2164     // vector type, we have a legal equivalently-sized i8 type, so we can use
2165     // that.
2166     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2167     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2168 
2169     SDValue WideVec;
2170     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2171       // For a splat, perform a scalar truncate before creating the wider
2172       // vector.
2173       assert(Splat.getValueType() == XLenVT &&
2174              "Unexpected type for i1 splat value");
2175       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2176                           DAG.getConstant(1, DL, XLenVT));
2177       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2178     } else {
2179       SmallVector<SDValue, 8> Ops(Op->op_values());
2180       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2181       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2182       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2183     }
2184 
2185     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2186   }
2187 
2188   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2189     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2190       return Gather;
2191     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2192                                         : RISCVISD::VMV_V_X_VL;
2193     Splat =
2194         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2195     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2196   }
2197 
2198   // Try and match index sequences, which we can lower to the vid instruction
2199   // with optional modifications. An all-undef vector is matched by
2200   // getSplatValue, above.
2201   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2202     int64_t StepNumerator = SimpleVID->StepNumerator;
2203     unsigned StepDenominator = SimpleVID->StepDenominator;
2204     int64_t Addend = SimpleVID->Addend;
2205 
2206     assert(StepNumerator != 0 && "Invalid step");
2207     bool Negate = false;
2208     int64_t SplatStepVal = StepNumerator;
2209     unsigned StepOpcode = ISD::MUL;
2210     if (StepNumerator != 1) {
2211       if (isPowerOf2_64(std::abs(StepNumerator))) {
2212         Negate = StepNumerator < 0;
2213         StepOpcode = ISD::SHL;
2214         SplatStepVal = Log2_64(std::abs(StepNumerator));
2215       }
2216     }
2217 
2218     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2219     // threshold since it's the immediate value many RVV instructions accept.
2220     // There is no vmul.vi instruction so ensure multiply constant can fit in
2221     // a single addi instruction.
2222     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2223          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2224         isPowerOf2_32(StepDenominator) &&
2225         (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) {
2226       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2227       // Convert right out of the scalable type so we can use standard ISD
2228       // nodes for the rest of the computation. If we used scalable types with
2229       // these, we'd lose the fixed-length vector info and generate worse
2230       // vsetvli code.
2231       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2232       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2233           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2234         SDValue SplatStep = DAG.getSplatBuildVector(
2235             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2236         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2237       }
2238       if (StepDenominator != 1) {
2239         SDValue SplatStep = DAG.getSplatBuildVector(
2240             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2241         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2242       }
2243       if (Addend != 0 || Negate) {
2244         SDValue SplatAddend = DAG.getSplatBuildVector(
2245             VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2246         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2247       }
2248       return VID;
2249     }
2250   }
2251 
2252   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2253   // when re-interpreted as a vector with a larger element type. For example,
2254   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2255   // could be instead splat as
2256   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2257   // TODO: This optimization could also work on non-constant splats, but it
2258   // would require bit-manipulation instructions to construct the splat value.
2259   SmallVector<SDValue> Sequence;
2260   unsigned EltBitSize = VT.getScalarSizeInBits();
2261   const auto *BV = cast<BuildVectorSDNode>(Op);
2262   if (VT.isInteger() && EltBitSize < 64 &&
2263       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2264       BV->getRepeatedSequence(Sequence) &&
2265       (Sequence.size() * EltBitSize) <= 64) {
2266     unsigned SeqLen = Sequence.size();
2267     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2268     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2269     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2270             ViaIntVT == MVT::i64) &&
2271            "Unexpected sequence type");
2272 
2273     unsigned EltIdx = 0;
2274     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2275     uint64_t SplatValue = 0;
2276     // Construct the amalgamated value which can be splatted as this larger
2277     // vector type.
2278     for (const auto &SeqV : Sequence) {
2279       if (!SeqV.isUndef())
2280         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2281                        << (EltIdx * EltBitSize));
2282       EltIdx++;
2283     }
2284 
2285     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2286     // achieve better constant materializion.
2287     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2288       SplatValue = SignExtend64<32>(SplatValue);
2289 
2290     // Since we can't introduce illegal i64 types at this stage, we can only
2291     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2292     // way we can use RVV instructions to splat.
2293     assert((ViaIntVT.bitsLE(XLenVT) ||
2294             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2295            "Unexpected bitcast sequence");
2296     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2297       SDValue ViaVL =
2298           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2299       MVT ViaContainerVT =
2300           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2301       SDValue Splat =
2302           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2303                       DAG.getUNDEF(ViaContainerVT),
2304                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2305       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2306       return DAG.getBitcast(VT, Splat);
2307     }
2308   }
2309 
2310   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2311   // which constitute a large proportion of the elements. In such cases we can
2312   // splat a vector with the dominant element and make up the shortfall with
2313   // INSERT_VECTOR_ELTs.
2314   // Note that this includes vectors of 2 elements by association. The
2315   // upper-most element is the "dominant" one, allowing us to use a splat to
2316   // "insert" the upper element, and an insert of the lower element at position
2317   // 0, which improves codegen.
2318   SDValue DominantValue;
2319   unsigned MostCommonCount = 0;
2320   DenseMap<SDValue, unsigned> ValueCounts;
2321   unsigned NumUndefElts =
2322       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2323 
2324   // Track the number of scalar loads we know we'd be inserting, estimated as
2325   // any non-zero floating-point constant. Other kinds of element are either
2326   // already in registers or are materialized on demand. The threshold at which
2327   // a vector load is more desirable than several scalar materializion and
2328   // vector-insertion instructions is not known.
2329   unsigned NumScalarLoads = 0;
2330 
2331   for (SDValue V : Op->op_values()) {
2332     if (V.isUndef())
2333       continue;
2334 
2335     ValueCounts.insert(std::make_pair(V, 0));
2336     unsigned &Count = ValueCounts[V];
2337 
2338     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2339       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2340 
2341     // Is this value dominant? In case of a tie, prefer the highest element as
2342     // it's cheaper to insert near the beginning of a vector than it is at the
2343     // end.
2344     if (++Count >= MostCommonCount) {
2345       DominantValue = V;
2346       MostCommonCount = Count;
2347     }
2348   }
2349 
2350   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2351   unsigned NumDefElts = NumElts - NumUndefElts;
2352   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2353 
2354   // Don't perform this optimization when optimizing for size, since
2355   // materializing elements and inserting them tends to cause code bloat.
2356   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2357       ((MostCommonCount > DominantValueCountThreshold) ||
2358        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2359     // Start by splatting the most common element.
2360     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2361 
2362     DenseSet<SDValue> Processed{DominantValue};
2363     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2364     for (const auto &OpIdx : enumerate(Op->ops())) {
2365       const SDValue &V = OpIdx.value();
2366       if (V.isUndef() || !Processed.insert(V).second)
2367         continue;
2368       if (ValueCounts[V] == 1) {
2369         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2370                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2371       } else {
2372         // Blend in all instances of this value using a VSELECT, using a
2373         // mask where each bit signals whether that element is the one
2374         // we're after.
2375         SmallVector<SDValue> Ops;
2376         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2377           return DAG.getConstant(V == V1, DL, XLenVT);
2378         });
2379         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2380                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2381                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2382       }
2383     }
2384 
2385     return Vec;
2386   }
2387 
2388   return SDValue();
2389 }
2390 
2391 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2392                                    SDValue Lo, SDValue Hi, SDValue VL,
2393                                    SelectionDAG &DAG) {
2394   if (!Passthru)
2395     Passthru = DAG.getUNDEF(VT);
2396   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2397     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2398     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2399     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2400     // node in order to try and match RVV vector/scalar instructions.
2401     if ((LoC >> 31) == HiC)
2402       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2403 
2404     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2405     // vmv.v.x whose EEW = 32 to lower it.
2406     auto *Const = dyn_cast<ConstantSDNode>(VL);
2407     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2408       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2409       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2410       // access the subtarget here now.
2411       auto InterVec = DAG.getNode(
2412           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2413                                   DAG.getRegister(RISCV::X0, MVT::i32));
2414       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2415     }
2416   }
2417 
2418   // Fall back to a stack store and stride x0 vector load.
2419   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2420                      Hi, VL);
2421 }
2422 
2423 // Called by type legalization to handle splat of i64 on RV32.
2424 // FIXME: We can optimize this when the type has sign or zero bits in one
2425 // of the halves.
2426 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2427                                    SDValue Scalar, SDValue VL,
2428                                    SelectionDAG &DAG) {
2429   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2430   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2431                            DAG.getConstant(0, DL, MVT::i32));
2432   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2433                            DAG.getConstant(1, DL, MVT::i32));
2434   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2435 }
2436 
2437 // This function lowers a splat of a scalar operand Splat with the vector
2438 // length VL. It ensures the final sequence is type legal, which is useful when
2439 // lowering a splat after type legalization.
2440 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2441                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2442                                 const RISCVSubtarget &Subtarget) {
2443   bool HasPassthru = Passthru && !Passthru.isUndef();
2444   if (!HasPassthru && !Passthru)
2445     Passthru = DAG.getUNDEF(VT);
2446   if (VT.isFloatingPoint()) {
2447     // If VL is 1, we could use vfmv.s.f.
2448     if (isOneConstant(VL))
2449       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2450     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2451   }
2452 
2453   MVT XLenVT = Subtarget.getXLenVT();
2454 
2455   // Simplest case is that the operand needs to be promoted to XLenVT.
2456   if (Scalar.getValueType().bitsLE(XLenVT)) {
2457     // If the operand is a constant, sign extend to increase our chances
2458     // of being able to use a .vi instruction. ANY_EXTEND would become a
2459     // a zero extend and the simm5 check in isel would fail.
2460     // FIXME: Should we ignore the upper bits in isel instead?
2461     unsigned ExtOpc =
2462         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2463     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2464     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2465     // If VL is 1 and the scalar value won't benefit from immediate, we could
2466     // use vmv.s.x.
2467     if (isOneConstant(VL) &&
2468         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2469       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2470     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2471   }
2472 
2473   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2474          "Unexpected scalar for splat lowering!");
2475 
2476   if (isOneConstant(VL) && isNullConstant(Scalar))
2477     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2478                        DAG.getConstant(0, DL, XLenVT), VL);
2479 
2480   // Otherwise use the more complicated splatting algorithm.
2481   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2482 }
2483 
2484 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2485                                 const RISCVSubtarget &Subtarget) {
2486   // We need to be able to widen elements to the next larger integer type.
2487   if (VT.getScalarSizeInBits() >= Subtarget.getELEN())
2488     return false;
2489 
2490   int Size = Mask.size();
2491   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2492 
2493   int Srcs[] = {-1, -1};
2494   for (int i = 0; i != Size; ++i) {
2495     // Ignore undef elements.
2496     if (Mask[i] < 0)
2497       continue;
2498 
2499     // Is this an even or odd element.
2500     int Pol = i % 2;
2501 
2502     // Ensure we consistently use the same source for this element polarity.
2503     int Src = Mask[i] / Size;
2504     if (Srcs[Pol] < 0)
2505       Srcs[Pol] = Src;
2506     if (Srcs[Pol] != Src)
2507       return false;
2508 
2509     // Make sure the element within the source is appropriate for this element
2510     // in the destination.
2511     int Elt = Mask[i] % Size;
2512     if (Elt != i / 2)
2513       return false;
2514   }
2515 
2516   // We need to find a source for each polarity and they can't be the same.
2517   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2518     return false;
2519 
2520   // Swap the sources if the second source was in the even polarity.
2521   SwapSources = Srcs[0] > Srcs[1];
2522 
2523   return true;
2524 }
2525 
2526 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2527 /// and then extract the original number of elements from the rotated result.
2528 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2529 /// returned rotation amount is for a rotate right, where elements move from
2530 /// higher elements to lower elements. \p LoSrc indicates the first source
2531 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2532 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2533 /// 0 or 1 if a rotation is found.
2534 ///
2535 /// NOTE: We talk about rotate to the right which matches how bit shift and
2536 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2537 /// and the table below write vectors with the lowest elements on the left.
2538 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2539   int Size = Mask.size();
2540 
2541   // We need to detect various ways of spelling a rotation:
2542   //   [11, 12, 13, 14, 15,  0,  1,  2]
2543   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2544   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2545   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2546   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2547   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2548   int Rotation = 0;
2549   LoSrc = -1;
2550   HiSrc = -1;
2551   for (int i = 0; i != Size; ++i) {
2552     int M = Mask[i];
2553     if (M < 0)
2554       continue;
2555 
2556     // Determine where a rotate vector would have started.
2557     int StartIdx = i - (M % Size);
2558     // The identity rotation isn't interesting, stop.
2559     if (StartIdx == 0)
2560       return -1;
2561 
2562     // If we found the tail of a vector the rotation must be the missing
2563     // front. If we found the head of a vector, it must be how much of the
2564     // head.
2565     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2566 
2567     if (Rotation == 0)
2568       Rotation = CandidateRotation;
2569     else if (Rotation != CandidateRotation)
2570       // The rotations don't match, so we can't match this mask.
2571       return -1;
2572 
2573     // Compute which value this mask is pointing at.
2574     int MaskSrc = M < Size ? 0 : 1;
2575 
2576     // Compute which of the two target values this index should be assigned to.
2577     // This reflects whether the high elements are remaining or the low elemnts
2578     // are remaining.
2579     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2580 
2581     // Either set up this value if we've not encountered it before, or check
2582     // that it remains consistent.
2583     if (TargetSrc < 0)
2584       TargetSrc = MaskSrc;
2585     else if (TargetSrc != MaskSrc)
2586       // This may be a rotation, but it pulls from the inputs in some
2587       // unsupported interleaving.
2588       return -1;
2589   }
2590 
2591   // Check that we successfully analyzed the mask, and normalize the results.
2592   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2593   assert((LoSrc >= 0 || HiSrc >= 0) &&
2594          "Failed to find a rotated input vector!");
2595 
2596   return Rotation;
2597 }
2598 
2599 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2600                                    const RISCVSubtarget &Subtarget) {
2601   SDValue V1 = Op.getOperand(0);
2602   SDValue V2 = Op.getOperand(1);
2603   SDLoc DL(Op);
2604   MVT XLenVT = Subtarget.getXLenVT();
2605   MVT VT = Op.getSimpleValueType();
2606   unsigned NumElts = VT.getVectorNumElements();
2607   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2608 
2609   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2610 
2611   SDValue TrueMask, VL;
2612   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2613 
2614   if (SVN->isSplat()) {
2615     const int Lane = SVN->getSplatIndex();
2616     if (Lane >= 0) {
2617       MVT SVT = VT.getVectorElementType();
2618 
2619       // Turn splatted vector load into a strided load with an X0 stride.
2620       SDValue V = V1;
2621       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2622       // with undef.
2623       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2624       int Offset = Lane;
2625       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2626         int OpElements =
2627             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2628         V = V.getOperand(Offset / OpElements);
2629         Offset %= OpElements;
2630       }
2631 
2632       // We need to ensure the load isn't atomic or volatile.
2633       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2634         auto *Ld = cast<LoadSDNode>(V);
2635         Offset *= SVT.getStoreSize();
2636         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2637                                                    TypeSize::Fixed(Offset), DL);
2638 
2639         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2640         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2641           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2642           SDValue IntID =
2643               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2644           SDValue Ops[] = {Ld->getChain(),
2645                            IntID,
2646                            DAG.getUNDEF(ContainerVT),
2647                            NewAddr,
2648                            DAG.getRegister(RISCV::X0, XLenVT),
2649                            VL};
2650           SDValue NewLoad = DAG.getMemIntrinsicNode(
2651               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2652               DAG.getMachineFunction().getMachineMemOperand(
2653                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2654           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2655           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2656         }
2657 
2658         // Otherwise use a scalar load and splat. This will give the best
2659         // opportunity to fold a splat into the operation. ISel can turn it into
2660         // the x0 strided load if we aren't able to fold away the select.
2661         if (SVT.isFloatingPoint())
2662           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2663                           Ld->getPointerInfo().getWithOffset(Offset),
2664                           Ld->getOriginalAlign(),
2665                           Ld->getMemOperand()->getFlags());
2666         else
2667           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2668                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2669                              Ld->getOriginalAlign(),
2670                              Ld->getMemOperand()->getFlags());
2671         DAG.makeEquivalentMemoryOrdering(Ld, V);
2672 
2673         unsigned Opc =
2674             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2675         SDValue Splat =
2676             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2677         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2678       }
2679 
2680       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2681       assert(Lane < (int)NumElts && "Unexpected lane!");
2682       SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT,
2683                                    V1, DAG.getConstant(Lane, DL, XLenVT),
2684                                    TrueMask, DAG.getUNDEF(ContainerVT), VL);
2685       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2686     }
2687   }
2688 
2689   ArrayRef<int> Mask = SVN->getMask();
2690 
2691   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2692   // be undef which can be handled with a single SLIDEDOWN/UP.
2693   int LoSrc, HiSrc;
2694   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2695   if (Rotation > 0) {
2696     SDValue LoV, HiV;
2697     if (LoSrc >= 0) {
2698       LoV = LoSrc == 0 ? V1 : V2;
2699       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2700     }
2701     if (HiSrc >= 0) {
2702       HiV = HiSrc == 0 ? V1 : V2;
2703       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2704     }
2705 
2706     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2707     // to slide LoV up by (NumElts - Rotation).
2708     unsigned InvRotate = NumElts - Rotation;
2709 
2710     SDValue Res = DAG.getUNDEF(ContainerVT);
2711     if (HiV) {
2712       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2713       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2714       // causes multiple vsetvlis in some test cases such as lowering
2715       // reduce.mul
2716       SDValue DownVL = VL;
2717       if (LoV)
2718         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2719       Res =
2720           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2721                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2722     }
2723     if (LoV)
2724       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2725                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2726 
2727     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2728   }
2729 
2730   // Detect an interleave shuffle and lower to
2731   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2732   bool SwapSources;
2733   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2734     // Swap sources if needed.
2735     if (SwapSources)
2736       std::swap(V1, V2);
2737 
2738     // Extract the lower half of the vectors.
2739     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2740     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2741                      DAG.getConstant(0, DL, XLenVT));
2742     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2743                      DAG.getConstant(0, DL, XLenVT));
2744 
2745     // Double the element width and halve the number of elements in an int type.
2746     unsigned EltBits = VT.getScalarSizeInBits();
2747     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2748     MVT WideIntVT =
2749         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2750     // Convert this to a scalable vector. We need to base this on the
2751     // destination size to ensure there's always a type with a smaller LMUL.
2752     MVT WideIntContainerVT =
2753         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2754 
2755     // Convert sources to scalable vectors with the same element count as the
2756     // larger type.
2757     MVT HalfContainerVT = MVT::getVectorVT(
2758         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2759     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2760     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2761 
2762     // Cast sources to integer.
2763     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2764     MVT IntHalfVT =
2765         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2766     V1 = DAG.getBitcast(IntHalfVT, V1);
2767     V2 = DAG.getBitcast(IntHalfVT, V2);
2768 
2769     // Freeze V2 since we use it twice and we need to be sure that the add and
2770     // multiply see the same value.
2771     V2 = DAG.getFreeze(V2);
2772 
2773     // Recreate TrueMask using the widened type's element count.
2774     TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG);
2775 
2776     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2777     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2778                               V2, TrueMask, VL);
2779     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2780     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2781                                      DAG.getUNDEF(IntHalfVT),
2782                                      DAG.getAllOnesConstant(DL, XLenVT));
2783     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2784                                    V2, Multiplier, TrueMask, VL);
2785     // Add the new copies to our previous addition giving us 2^eltbits copies of
2786     // V2. This is equivalent to shifting V2 left by eltbits. This should
2787     // combine with the vwmulu.vv above to form vwmaccu.vv.
2788     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2789                       TrueMask, VL);
2790     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2791     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2792     // vector VT.
2793     ContainerVT =
2794         MVT::getVectorVT(VT.getVectorElementType(),
2795                          WideIntContainerVT.getVectorElementCount() * 2);
2796     Add = DAG.getBitcast(ContainerVT, Add);
2797     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2798   }
2799 
2800   // Detect shuffles which can be re-expressed as vector selects; these are
2801   // shuffles in which each element in the destination is taken from an element
2802   // at the corresponding index in either source vectors.
2803   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2804     int MaskIndex = MaskIdx.value();
2805     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2806   });
2807 
2808   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2809 
2810   SmallVector<SDValue> MaskVals;
2811   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2812   // merged with a second vrgather.
2813   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2814 
2815   // By default we preserve the original operand order, and use a mask to
2816   // select LHS as true and RHS as false. However, since RVV vector selects may
2817   // feature splats but only on the LHS, we may choose to invert our mask and
2818   // instead select between RHS and LHS.
2819   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2820   bool InvertMask = IsSelect == SwapOps;
2821 
2822   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2823   // half.
2824   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2825 
2826   // Now construct the mask that will be used by the vselect or blended
2827   // vrgather operation. For vrgathers, construct the appropriate indices into
2828   // each vector.
2829   for (int MaskIndex : Mask) {
2830     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2831     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2832     if (!IsSelect) {
2833       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2834       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2835                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2836                                      : DAG.getUNDEF(XLenVT));
2837       GatherIndicesRHS.push_back(
2838           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2839                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2840       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2841         ++LHSIndexCounts[MaskIndex];
2842       if (!IsLHSOrUndefIndex)
2843         ++RHSIndexCounts[MaskIndex - NumElts];
2844     }
2845   }
2846 
2847   if (SwapOps) {
2848     std::swap(V1, V2);
2849     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2850   }
2851 
2852   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2853   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2854   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2855 
2856   if (IsSelect)
2857     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2858 
2859   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2860     // On such a large vector we're unable to use i8 as the index type.
2861     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2862     // may involve vector splitting if we're already at LMUL=8, or our
2863     // user-supplied maximum fixed-length LMUL.
2864     return SDValue();
2865   }
2866 
2867   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2868   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2869   MVT IndexVT = VT.changeTypeToInteger();
2870   // Since we can't introduce illegal index types at this stage, use i16 and
2871   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2872   // than XLenVT.
2873   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2874     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2875     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2876   }
2877 
2878   MVT IndexContainerVT =
2879       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2880 
2881   SDValue Gather;
2882   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2883   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2884   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2885     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2886                               Subtarget);
2887   } else {
2888     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2889     // If only one index is used, we can use a "splat" vrgather.
2890     // TODO: We can splat the most-common index and fix-up any stragglers, if
2891     // that's beneficial.
2892     if (LHSIndexCounts.size() == 1) {
2893       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2894       Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2895                            DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask,
2896                            DAG.getUNDEF(ContainerVT), VL);
2897     } else {
2898       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2899       LHSIndices =
2900           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2901 
2902       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2903                            TrueMask, DAG.getUNDEF(ContainerVT), VL);
2904     }
2905   }
2906 
2907   // If a second vector operand is used by this shuffle, blend it in with an
2908   // additional vrgather.
2909   if (!V2.isUndef()) {
2910     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2911 
2912     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2913     SelectMask =
2914         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2915 
2916     // If only one index is used, we can use a "splat" vrgather.
2917     // TODO: We can splat the most-common index and fix-up any stragglers, if
2918     // that's beneficial.
2919     if (RHSIndexCounts.size() == 1) {
2920       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2921       Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2922                            DAG.getConstant(SplatIndex, DL, XLenVT), SelectMask,
2923                            Gather, VL);
2924     } else {
2925       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2926       RHSIndices =
2927           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2928       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices,
2929                            SelectMask, Gather, VL);
2930     }
2931   }
2932 
2933   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2934 }
2935 
2936 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2937   // Support splats for any type. These should type legalize well.
2938   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2939     return true;
2940 
2941   // Only support legal VTs for other shuffles for now.
2942   if (!isTypeLegal(VT))
2943     return false;
2944 
2945   MVT SVT = VT.getSimpleVT();
2946 
2947   bool SwapSources;
2948   int LoSrc, HiSrc;
2949   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2950          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2951 }
2952 
2953 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2954 // the exponent.
2955 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2956   MVT VT = Op.getSimpleValueType();
2957   unsigned EltSize = VT.getScalarSizeInBits();
2958   SDValue Src = Op.getOperand(0);
2959   SDLoc DL(Op);
2960 
2961   // We need a FP type that can represent the value.
2962   // TODO: Use f16 for i8 when possible?
2963   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2964   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2965 
2966   // Legal types should have been checked in the RISCVTargetLowering
2967   // constructor.
2968   // TODO: Splitting may make sense in some cases.
2969   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2970          "Expected legal float type!");
2971 
2972   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2973   // The trailing zero count is equal to log2 of this single bit value.
2974   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2975     SDValue Neg =
2976         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2977     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2978   }
2979 
2980   // We have a legal FP type, convert to it.
2981   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2982   // Bitcast to integer and shift the exponent to the LSB.
2983   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2984   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2985   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2986   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2987                               DAG.getConstant(ShiftAmt, DL, IntVT));
2988   // Truncate back to original type to allow vnsrl.
2989   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2990   // The exponent contains log2 of the value in biased form.
2991   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2992 
2993   // For trailing zeros, we just need to subtract the bias.
2994   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2995     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2996                        DAG.getConstant(ExponentBias, DL, VT));
2997 
2998   // For leading zeros, we need to remove the bias and convert from log2 to
2999   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
3000   unsigned Adjust = ExponentBias + (EltSize - 1);
3001   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
3002 }
3003 
3004 // While RVV has alignment restrictions, we should always be able to load as a
3005 // legal equivalently-sized byte-typed vector instead. This method is
3006 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
3007 // the load is already correctly-aligned, it returns SDValue().
3008 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
3009                                                     SelectionDAG &DAG) const {
3010   auto *Load = cast<LoadSDNode>(Op);
3011   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
3012 
3013   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3014                                      Load->getMemoryVT(),
3015                                      *Load->getMemOperand()))
3016     return SDValue();
3017 
3018   SDLoc DL(Op);
3019   MVT VT = Op.getSimpleValueType();
3020   unsigned EltSizeBits = VT.getScalarSizeInBits();
3021   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3022          "Unexpected unaligned RVV load type");
3023   MVT NewVT =
3024       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3025   assert(NewVT.isValid() &&
3026          "Expecting equally-sized RVV vector types to be legal");
3027   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
3028                           Load->getPointerInfo(), Load->getOriginalAlign(),
3029                           Load->getMemOperand()->getFlags());
3030   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
3031 }
3032 
3033 // While RVV has alignment restrictions, we should always be able to store as a
3034 // legal equivalently-sized byte-typed vector instead. This method is
3035 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
3036 // returns SDValue() if the store is already correctly aligned.
3037 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
3038                                                      SelectionDAG &DAG) const {
3039   auto *Store = cast<StoreSDNode>(Op);
3040   assert(Store && Store->getValue().getValueType().isVector() &&
3041          "Expected vector store");
3042 
3043   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3044                                      Store->getMemoryVT(),
3045                                      *Store->getMemOperand()))
3046     return SDValue();
3047 
3048   SDLoc DL(Op);
3049   SDValue StoredVal = Store->getValue();
3050   MVT VT = StoredVal.getSimpleValueType();
3051   unsigned EltSizeBits = VT.getScalarSizeInBits();
3052   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3053          "Unexpected unaligned RVV store type");
3054   MVT NewVT =
3055       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3056   assert(NewVT.isValid() &&
3057          "Expecting equally-sized RVV vector types to be legal");
3058   StoredVal = DAG.getBitcast(NewVT, StoredVal);
3059   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
3060                       Store->getPointerInfo(), Store->getOriginalAlign(),
3061                       Store->getMemOperand()->getFlags());
3062 }
3063 
3064 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG,
3065                              const RISCVSubtarget &Subtarget) {
3066   assert(Op.getValueType() == MVT::i64 && "Unexpected VT");
3067 
3068   int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue();
3069 
3070   // All simm32 constants should be handled by isel.
3071   // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making
3072   // this check redundant, but small immediates are common so this check
3073   // should have better compile time.
3074   if (isInt<32>(Imm))
3075     return Op;
3076 
3077   // We only need to cost the immediate, if constant pool lowering is enabled.
3078   if (!Subtarget.useConstantPoolForLargeInts())
3079     return Op;
3080 
3081   RISCVMatInt::InstSeq Seq =
3082       RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits());
3083   if (Seq.size() <= Subtarget.getMaxBuildIntsCost())
3084     return Op;
3085 
3086   // Expand to a constant pool using the default expansion code.
3087   return SDValue();
3088 }
3089 
3090 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
3091                                             SelectionDAG &DAG) const {
3092   switch (Op.getOpcode()) {
3093   default:
3094     report_fatal_error("unimplemented operand");
3095   case ISD::GlobalAddress:
3096     return lowerGlobalAddress(Op, DAG);
3097   case ISD::BlockAddress:
3098     return lowerBlockAddress(Op, DAG);
3099   case ISD::ConstantPool:
3100     return lowerConstantPool(Op, DAG);
3101   case ISD::JumpTable:
3102     return lowerJumpTable(Op, DAG);
3103   case ISD::GlobalTLSAddress:
3104     return lowerGlobalTLSAddress(Op, DAG);
3105   case ISD::Constant:
3106     return lowerConstant(Op, DAG, Subtarget);
3107   case ISD::SELECT:
3108     return lowerSELECT(Op, DAG);
3109   case ISD::BRCOND:
3110     return lowerBRCOND(Op, DAG);
3111   case ISD::VASTART:
3112     return lowerVASTART(Op, DAG);
3113   case ISD::FRAMEADDR:
3114     return lowerFRAMEADDR(Op, DAG);
3115   case ISD::RETURNADDR:
3116     return lowerRETURNADDR(Op, DAG);
3117   case ISD::SHL_PARTS:
3118     return lowerShiftLeftParts(Op, DAG);
3119   case ISD::SRA_PARTS:
3120     return lowerShiftRightParts(Op, DAG, true);
3121   case ISD::SRL_PARTS:
3122     return lowerShiftRightParts(Op, DAG, false);
3123   case ISD::BITCAST: {
3124     SDLoc DL(Op);
3125     EVT VT = Op.getValueType();
3126     SDValue Op0 = Op.getOperand(0);
3127     EVT Op0VT = Op0.getValueType();
3128     MVT XLenVT = Subtarget.getXLenVT();
3129     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3130       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3131       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3132       return FPConv;
3133     }
3134     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3135         Subtarget.hasStdExtF()) {
3136       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3137       SDValue FPConv =
3138           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3139       return FPConv;
3140     }
3141 
3142     // Consider other scalar<->scalar casts as legal if the types are legal.
3143     // Otherwise expand them.
3144     if (!VT.isVector() && !Op0VT.isVector()) {
3145       if (isTypeLegal(VT) && isTypeLegal(Op0VT))
3146         return Op;
3147       return SDValue();
3148     }
3149 
3150     assert(!VT.isScalableVector() && !Op0VT.isScalableVector() &&
3151            "Unexpected types");
3152 
3153     if (VT.isFixedLengthVector()) {
3154       // We can handle fixed length vector bitcasts with a simple replacement
3155       // in isel.
3156       if (Op0VT.isFixedLengthVector())
3157         return Op;
3158       // When bitcasting from scalar to fixed-length vector, insert the scalar
3159       // into a one-element vector of the result type, and perform a vector
3160       // bitcast.
3161       if (!Op0VT.isVector()) {
3162         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3163         if (!isTypeLegal(BVT))
3164           return SDValue();
3165         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3166                                               DAG.getUNDEF(BVT), Op0,
3167                                               DAG.getConstant(0, DL, XLenVT)));
3168       }
3169       return SDValue();
3170     }
3171     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3172     // thus: bitcast the vector to a one-element vector type whose element type
3173     // is the same as the result type, and extract the first element.
3174     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3175       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3176       if (!isTypeLegal(BVT))
3177         return SDValue();
3178       SDValue BVec = DAG.getBitcast(BVT, Op0);
3179       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3180                          DAG.getConstant(0, DL, XLenVT));
3181     }
3182     return SDValue();
3183   }
3184   case ISD::INTRINSIC_WO_CHAIN:
3185     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3186   case ISD::INTRINSIC_W_CHAIN:
3187     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3188   case ISD::INTRINSIC_VOID:
3189     return LowerINTRINSIC_VOID(Op, DAG);
3190   case ISD::BSWAP:
3191   case ISD::BITREVERSE: {
3192     MVT VT = Op.getSimpleValueType();
3193     SDLoc DL(Op);
3194     if (Subtarget.hasStdExtZbp()) {
3195       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3196       // Start with the maximum immediate value which is the bitwidth - 1.
3197       unsigned Imm = VT.getSizeInBits() - 1;
3198       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3199       if (Op.getOpcode() == ISD::BSWAP)
3200         Imm &= ~0x7U;
3201       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3202                          DAG.getConstant(Imm, DL, VT));
3203     }
3204     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3205     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3206     // Expand bitreverse to a bswap(rev8) followed by brev8.
3207     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3208     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3209     // as brev8 by an isel pattern.
3210     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3211                        DAG.getConstant(7, DL, VT));
3212   }
3213   case ISD::FSHL:
3214   case ISD::FSHR: {
3215     MVT VT = Op.getSimpleValueType();
3216     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3217     SDLoc DL(Op);
3218     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3219     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3220     // accidentally setting the extra bit.
3221     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3222     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3223                                 DAG.getConstant(ShAmtWidth, DL, VT));
3224     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3225     // instruction use different orders. fshl will return its first operand for
3226     // shift of zero, fshr will return its second operand. fsl and fsr both
3227     // return rs1 so the ISD nodes need to have different operand orders.
3228     // Shift amount is in rs2.
3229     SDValue Op0 = Op.getOperand(0);
3230     SDValue Op1 = Op.getOperand(1);
3231     unsigned Opc = RISCVISD::FSL;
3232     if (Op.getOpcode() == ISD::FSHR) {
3233       std::swap(Op0, Op1);
3234       Opc = RISCVISD::FSR;
3235     }
3236     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3237   }
3238   case ISD::TRUNCATE:
3239     // Only custom-lower vector truncates
3240     if (!Op.getSimpleValueType().isVector())
3241       return Op;
3242     return lowerVectorTruncLike(Op, DAG);
3243   case ISD::ANY_EXTEND:
3244   case ISD::ZERO_EXTEND:
3245     if (Op.getOperand(0).getValueType().isVector() &&
3246         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3247       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3248     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3249   case ISD::SIGN_EXTEND:
3250     if (Op.getOperand(0).getValueType().isVector() &&
3251         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3252       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3253     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3254   case ISD::SPLAT_VECTOR_PARTS:
3255     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3256   case ISD::INSERT_VECTOR_ELT:
3257     return lowerINSERT_VECTOR_ELT(Op, DAG);
3258   case ISD::EXTRACT_VECTOR_ELT:
3259     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3260   case ISD::VSCALE: {
3261     MVT VT = Op.getSimpleValueType();
3262     SDLoc DL(Op);
3263     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3264     // We define our scalable vector types for lmul=1 to use a 64 bit known
3265     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3266     // vscale as VLENB / 8.
3267     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3268     if (Subtarget.getRealMinVLen() < RISCV::RVVBitsPerBlock)
3269       report_fatal_error("Support for VLEN==32 is incomplete.");
3270     // We assume VLENB is a multiple of 8. We manually choose the best shift
3271     // here because SimplifyDemandedBits isn't always able to simplify it.
3272     uint64_t Val = Op.getConstantOperandVal(0);
3273     if (isPowerOf2_64(Val)) {
3274       uint64_t Log2 = Log2_64(Val);
3275       if (Log2 < 3)
3276         return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3277                            DAG.getConstant(3 - Log2, DL, VT));
3278       if (Log2 > 3)
3279         return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3280                            DAG.getConstant(Log2 - 3, DL, VT));
3281       return VLENB;
3282     }
3283     // If the multiplier is a multiple of 8, scale it down to avoid needing
3284     // to shift the VLENB value.
3285     if ((Val % 8) == 0)
3286       return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3287                          DAG.getConstant(Val / 8, DL, VT));
3288 
3289     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3290                                  DAG.getConstant(3, DL, VT));
3291     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3292   }
3293   case ISD::FPOWI: {
3294     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3295     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3296     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3297         Op.getOperand(1).getValueType() == MVT::i32) {
3298       SDLoc DL(Op);
3299       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3300       SDValue Powi =
3301           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3302       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3303                          DAG.getIntPtrConstant(0, DL));
3304     }
3305     return SDValue();
3306   }
3307   case ISD::FP_EXTEND:
3308   case ISD::FP_ROUND:
3309     if (!Op.getValueType().isVector())
3310       return Op;
3311     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3312   case ISD::FP_TO_SINT:
3313   case ISD::FP_TO_UINT:
3314   case ISD::SINT_TO_FP:
3315   case ISD::UINT_TO_FP: {
3316     // RVV can only do fp<->int conversions to types half/double the size as
3317     // the source. We custom-lower any conversions that do two hops into
3318     // sequences.
3319     MVT VT = Op.getSimpleValueType();
3320     if (!VT.isVector())
3321       return Op;
3322     SDLoc DL(Op);
3323     SDValue Src = Op.getOperand(0);
3324     MVT EltVT = VT.getVectorElementType();
3325     MVT SrcVT = Src.getSimpleValueType();
3326     MVT SrcEltVT = SrcVT.getVectorElementType();
3327     unsigned EltSize = EltVT.getSizeInBits();
3328     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3329     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3330            "Unexpected vector element types");
3331 
3332     bool IsInt2FP = SrcEltVT.isInteger();
3333     // Widening conversions
3334     if (EltSize > (2 * SrcEltSize)) {
3335       if (IsInt2FP) {
3336         // Do a regular integer sign/zero extension then convert to float.
3337         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize),
3338                                       VT.getVectorElementCount());
3339         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3340                                  ? ISD::ZERO_EXTEND
3341                                  : ISD::SIGN_EXTEND;
3342         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3343         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3344       }
3345       // FP2Int
3346       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3347       // Do one doubling fp_extend then complete the operation by converting
3348       // to int.
3349       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3350       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3351       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3352     }
3353 
3354     // Narrowing conversions
3355     if (SrcEltSize > (2 * EltSize)) {
3356       if (IsInt2FP) {
3357         // One narrowing int_to_fp, then an fp_round.
3358         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3359         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3360         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3361         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3362       }
3363       // FP2Int
3364       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3365       // representable by the integer, the result is poison.
3366       MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
3367                                     VT.getVectorElementCount());
3368       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3369       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3370     }
3371 
3372     // Scalable vectors can exit here. Patterns will handle equally-sized
3373     // conversions halving/doubling ones.
3374     if (!VT.isFixedLengthVector())
3375       return Op;
3376 
3377     // For fixed-length vectors we lower to a custom "VL" node.
3378     unsigned RVVOpc = 0;
3379     switch (Op.getOpcode()) {
3380     default:
3381       llvm_unreachable("Impossible opcode");
3382     case ISD::FP_TO_SINT:
3383       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3384       break;
3385     case ISD::FP_TO_UINT:
3386       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3387       break;
3388     case ISD::SINT_TO_FP:
3389       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3390       break;
3391     case ISD::UINT_TO_FP:
3392       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3393       break;
3394     }
3395 
3396     MVT ContainerVT, SrcContainerVT;
3397     // Derive the reference container type from the larger vector type.
3398     if (SrcEltSize > EltSize) {
3399       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3400       ContainerVT =
3401           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3402     } else {
3403       ContainerVT = getContainerForFixedLengthVector(VT);
3404       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3405     }
3406 
3407     SDValue Mask, VL;
3408     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3409 
3410     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3411     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3412     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3413   }
3414   case ISD::FP_TO_SINT_SAT:
3415   case ISD::FP_TO_UINT_SAT:
3416     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3417   case ISD::FTRUNC:
3418   case ISD::FCEIL:
3419   case ISD::FFLOOR:
3420     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3421   case ISD::FROUND:
3422     return lowerFROUND(Op, DAG);
3423   case ISD::VECREDUCE_ADD:
3424   case ISD::VECREDUCE_UMAX:
3425   case ISD::VECREDUCE_SMAX:
3426   case ISD::VECREDUCE_UMIN:
3427   case ISD::VECREDUCE_SMIN:
3428     return lowerVECREDUCE(Op, DAG);
3429   case ISD::VECREDUCE_AND:
3430   case ISD::VECREDUCE_OR:
3431   case ISD::VECREDUCE_XOR:
3432     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3433       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3434     return lowerVECREDUCE(Op, DAG);
3435   case ISD::VECREDUCE_FADD:
3436   case ISD::VECREDUCE_SEQ_FADD:
3437   case ISD::VECREDUCE_FMIN:
3438   case ISD::VECREDUCE_FMAX:
3439     return lowerFPVECREDUCE(Op, DAG);
3440   case ISD::VP_REDUCE_ADD:
3441   case ISD::VP_REDUCE_UMAX:
3442   case ISD::VP_REDUCE_SMAX:
3443   case ISD::VP_REDUCE_UMIN:
3444   case ISD::VP_REDUCE_SMIN:
3445   case ISD::VP_REDUCE_FADD:
3446   case ISD::VP_REDUCE_SEQ_FADD:
3447   case ISD::VP_REDUCE_FMIN:
3448   case ISD::VP_REDUCE_FMAX:
3449     return lowerVPREDUCE(Op, DAG);
3450   case ISD::VP_REDUCE_AND:
3451   case ISD::VP_REDUCE_OR:
3452   case ISD::VP_REDUCE_XOR:
3453     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3454       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3455     return lowerVPREDUCE(Op, DAG);
3456   case ISD::INSERT_SUBVECTOR:
3457     return lowerINSERT_SUBVECTOR(Op, DAG);
3458   case ISD::EXTRACT_SUBVECTOR:
3459     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3460   case ISD::STEP_VECTOR:
3461     return lowerSTEP_VECTOR(Op, DAG);
3462   case ISD::VECTOR_REVERSE:
3463     return lowerVECTOR_REVERSE(Op, DAG);
3464   case ISD::VECTOR_SPLICE:
3465     return lowerVECTOR_SPLICE(Op, DAG);
3466   case ISD::BUILD_VECTOR:
3467     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3468   case ISD::SPLAT_VECTOR:
3469     if (Op.getValueType().getVectorElementType() == MVT::i1)
3470       return lowerVectorMaskSplat(Op, DAG);
3471     return SDValue();
3472   case ISD::VECTOR_SHUFFLE:
3473     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3474   case ISD::CONCAT_VECTORS: {
3475     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3476     // better than going through the stack, as the default expansion does.
3477     SDLoc DL(Op);
3478     MVT VT = Op.getSimpleValueType();
3479     unsigned NumOpElts =
3480         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3481     SDValue Vec = DAG.getUNDEF(VT);
3482     for (const auto &OpIdx : enumerate(Op->ops())) {
3483       SDValue SubVec = OpIdx.value();
3484       // Don't insert undef subvectors.
3485       if (SubVec.isUndef())
3486         continue;
3487       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3488                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3489     }
3490     return Vec;
3491   }
3492   case ISD::LOAD:
3493     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3494       return V;
3495     if (Op.getValueType().isFixedLengthVector())
3496       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3497     return Op;
3498   case ISD::STORE:
3499     if (auto V = expandUnalignedRVVStore(Op, DAG))
3500       return V;
3501     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3502       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3503     return Op;
3504   case ISD::MLOAD:
3505   case ISD::VP_LOAD:
3506     return lowerMaskedLoad(Op, DAG);
3507   case ISD::MSTORE:
3508   case ISD::VP_STORE:
3509     return lowerMaskedStore(Op, DAG);
3510   case ISD::SETCC:
3511     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3512   case ISD::ADD:
3513     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3514   case ISD::SUB:
3515     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3516   case ISD::MUL:
3517     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3518   case ISD::MULHS:
3519     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3520   case ISD::MULHU:
3521     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3522   case ISD::AND:
3523     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3524                                               RISCVISD::AND_VL);
3525   case ISD::OR:
3526     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3527                                               RISCVISD::OR_VL);
3528   case ISD::XOR:
3529     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3530                                               RISCVISD::XOR_VL);
3531   case ISD::SDIV:
3532     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3533   case ISD::SREM:
3534     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3535   case ISD::UDIV:
3536     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3537   case ISD::UREM:
3538     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3539   case ISD::SHL:
3540   case ISD::SRA:
3541   case ISD::SRL:
3542     if (Op.getSimpleValueType().isFixedLengthVector())
3543       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3544     // This can be called for an i32 shift amount that needs to be promoted.
3545     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3546            "Unexpected custom legalisation");
3547     return SDValue();
3548   case ISD::SADDSAT:
3549     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3550   case ISD::UADDSAT:
3551     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3552   case ISD::SSUBSAT:
3553     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3554   case ISD::USUBSAT:
3555     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3556   case ISD::FADD:
3557     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3558   case ISD::FSUB:
3559     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3560   case ISD::FMUL:
3561     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3562   case ISD::FDIV:
3563     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3564   case ISD::FNEG:
3565     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3566   case ISD::FABS:
3567     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3568   case ISD::FSQRT:
3569     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3570   case ISD::FMA:
3571     return lowerToScalableOp(Op, DAG, RISCVISD::VFMADD_VL);
3572   case ISD::SMIN:
3573     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3574   case ISD::SMAX:
3575     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3576   case ISD::UMIN:
3577     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3578   case ISD::UMAX:
3579     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3580   case ISD::FMINNUM:
3581     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3582   case ISD::FMAXNUM:
3583     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3584   case ISD::ABS:
3585     return lowerABS(Op, DAG);
3586   case ISD::CTLZ_ZERO_UNDEF:
3587   case ISD::CTTZ_ZERO_UNDEF:
3588     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3589   case ISD::VSELECT:
3590     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3591   case ISD::FCOPYSIGN:
3592     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3593   case ISD::MGATHER:
3594   case ISD::VP_GATHER:
3595     return lowerMaskedGather(Op, DAG);
3596   case ISD::MSCATTER:
3597   case ISD::VP_SCATTER:
3598     return lowerMaskedScatter(Op, DAG);
3599   case ISD::FLT_ROUNDS_:
3600     return lowerGET_ROUNDING(Op, DAG);
3601   case ISD::SET_ROUNDING:
3602     return lowerSET_ROUNDING(Op, DAG);
3603   case ISD::EH_DWARF_CFA:
3604     return lowerEH_DWARF_CFA(Op, DAG);
3605   case ISD::VP_SELECT:
3606     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3607   case ISD::VP_MERGE:
3608     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3609   case ISD::VP_ADD:
3610     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3611   case ISD::VP_SUB:
3612     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3613   case ISD::VP_MUL:
3614     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3615   case ISD::VP_SDIV:
3616     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3617   case ISD::VP_UDIV:
3618     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3619   case ISD::VP_SREM:
3620     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3621   case ISD::VP_UREM:
3622     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3623   case ISD::VP_AND:
3624     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3625   case ISD::VP_OR:
3626     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3627   case ISD::VP_XOR:
3628     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3629   case ISD::VP_ASHR:
3630     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3631   case ISD::VP_LSHR:
3632     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3633   case ISD::VP_SHL:
3634     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3635   case ISD::VP_FADD:
3636     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3637   case ISD::VP_FSUB:
3638     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3639   case ISD::VP_FMUL:
3640     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3641   case ISD::VP_FDIV:
3642     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3643   case ISD::VP_FNEG:
3644     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3645   case ISD::VP_FMA:
3646     return lowerVPOp(Op, DAG, RISCVISD::VFMADD_VL);
3647   case ISD::VP_SIGN_EXTEND:
3648   case ISD::VP_ZERO_EXTEND:
3649     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3650       return lowerVPExtMaskOp(Op, DAG);
3651     return lowerVPOp(Op, DAG,
3652                      Op.getOpcode() == ISD::VP_SIGN_EXTEND
3653                          ? RISCVISD::VSEXT_VL
3654                          : RISCVISD::VZEXT_VL);
3655   case ISD::VP_TRUNCATE:
3656     return lowerVectorTruncLike(Op, DAG);
3657   case ISD::VP_FP_EXTEND:
3658   case ISD::VP_FP_ROUND:
3659     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3660   case ISD::VP_FPTOSI:
3661     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL);
3662   case ISD::VP_FPTOUI:
3663     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL);
3664   case ISD::VP_SITOFP:
3665     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
3666   case ISD::VP_UITOFP:
3667     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL);
3668   case ISD::VP_SETCC:
3669     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3670       return lowerVPSetCCMaskOp(Op, DAG);
3671     return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL);
3672   }
3673 }
3674 
3675 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3676                              SelectionDAG &DAG, unsigned Flags) {
3677   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3678 }
3679 
3680 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3681                              SelectionDAG &DAG, unsigned Flags) {
3682   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3683                                    Flags);
3684 }
3685 
3686 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3687                              SelectionDAG &DAG, unsigned Flags) {
3688   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3689                                    N->getOffset(), Flags);
3690 }
3691 
3692 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3693                              SelectionDAG &DAG, unsigned Flags) {
3694   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3695 }
3696 
3697 template <class NodeTy>
3698 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3699                                      bool IsLocal) const {
3700   SDLoc DL(N);
3701   EVT Ty = getPointerTy(DAG.getDataLayout());
3702 
3703   if (isPositionIndependent()) {
3704     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3705     if (IsLocal)
3706       // Use PC-relative addressing to access the symbol. This generates the
3707       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3708       // %pcrel_lo(auipc)).
3709       return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
3710 
3711     // Use PC-relative addressing to access the GOT for this symbol, then load
3712     // the address from the GOT. This generates the pattern (PseudoLA sym),
3713     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3714     MachineFunction &MF = DAG.getMachineFunction();
3715     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3716         MachinePointerInfo::getGOT(MF),
3717         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3718             MachineMemOperand::MOInvariant,
3719         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3720     SDValue Load =
3721         DAG.getMemIntrinsicNode(RISCVISD::LA, DL, DAG.getVTList(Ty, MVT::Other),
3722                                 {DAG.getEntryNode(), Addr}, Ty, MemOp);
3723     return Load;
3724   }
3725 
3726   switch (getTargetMachine().getCodeModel()) {
3727   default:
3728     report_fatal_error("Unsupported code model for lowering");
3729   case CodeModel::Small: {
3730     // Generate a sequence for accessing addresses within the first 2 GiB of
3731     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3732     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3733     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3734     SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
3735     return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo);
3736   }
3737   case CodeModel::Medium: {
3738     // Generate a sequence for accessing addresses within any 2GiB range within
3739     // the address space. This generates the pattern (PseudoLLA sym), which
3740     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3741     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3742     return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
3743   }
3744   }
3745 }
3746 
3747 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3748                                                 SelectionDAG &DAG) const {
3749   SDLoc DL(Op);
3750   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3751   assert(N->getOffset() == 0 && "unexpected offset in global node");
3752   return getAddr(N, DAG, N->getGlobal()->isDSOLocal());
3753 }
3754 
3755 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3756                                                SelectionDAG &DAG) const {
3757   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3758 
3759   return getAddr(N, DAG);
3760 }
3761 
3762 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3763                                                SelectionDAG &DAG) const {
3764   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3765 
3766   return getAddr(N, DAG);
3767 }
3768 
3769 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3770                                             SelectionDAG &DAG) const {
3771   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3772 
3773   return getAddr(N, DAG);
3774 }
3775 
3776 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3777                                               SelectionDAG &DAG,
3778                                               bool UseGOT) const {
3779   SDLoc DL(N);
3780   EVT Ty = getPointerTy(DAG.getDataLayout());
3781   const GlobalValue *GV = N->getGlobal();
3782   MVT XLenVT = Subtarget.getXLenVT();
3783 
3784   if (UseGOT) {
3785     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3786     // load the address from the GOT and add the thread pointer. This generates
3787     // the pattern (PseudoLA_TLS_IE sym), which expands to
3788     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3789     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3790     MachineFunction &MF = DAG.getMachineFunction();
3791     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3792         MachinePointerInfo::getGOT(MF),
3793         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3794             MachineMemOperand::MOInvariant,
3795         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3796     SDValue Load = DAG.getMemIntrinsicNode(
3797         RISCVISD::LA_TLS_IE, DL, DAG.getVTList(Ty, MVT::Other),
3798         {DAG.getEntryNode(), Addr}, Ty, MemOp);
3799 
3800     // Add the thread pointer.
3801     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3802     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3803   }
3804 
3805   // Generate a sequence for accessing the address relative to the thread
3806   // pointer, with the appropriate adjustment for the thread pointer offset.
3807   // This generates the pattern
3808   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3809   SDValue AddrHi =
3810       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3811   SDValue AddrAdd =
3812       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3813   SDValue AddrLo =
3814       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3815 
3816   SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
3817   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3818   SDValue MNAdd =
3819       DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd);
3820   return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo);
3821 }
3822 
3823 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3824                                                SelectionDAG &DAG) const {
3825   SDLoc DL(N);
3826   EVT Ty = getPointerTy(DAG.getDataLayout());
3827   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3828   const GlobalValue *GV = N->getGlobal();
3829 
3830   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3831   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3832   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3833   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3834   SDValue Load = DAG.getNode(RISCVISD::LA_TLS_GD, DL, Ty, Addr);
3835 
3836   // Prepare argument list to generate call.
3837   ArgListTy Args;
3838   ArgListEntry Entry;
3839   Entry.Node = Load;
3840   Entry.Ty = CallTy;
3841   Args.push_back(Entry);
3842 
3843   // Setup call to __tls_get_addr.
3844   TargetLowering::CallLoweringInfo CLI(DAG);
3845   CLI.setDebugLoc(DL)
3846       .setChain(DAG.getEntryNode())
3847       .setLibCallee(CallingConv::C, CallTy,
3848                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3849                     std::move(Args));
3850 
3851   return LowerCallTo(CLI).first;
3852 }
3853 
3854 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3855                                                    SelectionDAG &DAG) const {
3856   SDLoc DL(Op);
3857   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3858   assert(N->getOffset() == 0 && "unexpected offset in global node");
3859 
3860   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3861 
3862   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3863       CallingConv::GHC)
3864     report_fatal_error("In GHC calling convention TLS is not supported");
3865 
3866   SDValue Addr;
3867   switch (Model) {
3868   case TLSModel::LocalExec:
3869     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3870     break;
3871   case TLSModel::InitialExec:
3872     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3873     break;
3874   case TLSModel::LocalDynamic:
3875   case TLSModel::GeneralDynamic:
3876     Addr = getDynamicTLSAddr(N, DAG);
3877     break;
3878   }
3879 
3880   return Addr;
3881 }
3882 
3883 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3884   SDValue CondV = Op.getOperand(0);
3885   SDValue TrueV = Op.getOperand(1);
3886   SDValue FalseV = Op.getOperand(2);
3887   SDLoc DL(Op);
3888   MVT VT = Op.getSimpleValueType();
3889   MVT XLenVT = Subtarget.getXLenVT();
3890 
3891   // Lower vector SELECTs to VSELECTs by splatting the condition.
3892   if (VT.isVector()) {
3893     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3894     SDValue CondSplat = VT.isScalableVector()
3895                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3896                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3897     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3898   }
3899 
3900   // If the result type is XLenVT and CondV is the output of a SETCC node
3901   // which also operated on XLenVT inputs, then merge the SETCC node into the
3902   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3903   // compare+branch instructions. i.e.:
3904   // (select (setcc lhs, rhs, cc), truev, falsev)
3905   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3906   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3907       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3908     SDValue LHS = CondV.getOperand(0);
3909     SDValue RHS = CondV.getOperand(1);
3910     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3911     ISD::CondCode CCVal = CC->get();
3912 
3913     // Special case for a select of 2 constants that have a diffence of 1.
3914     // Normally this is done by DAGCombine, but if the select is introduced by
3915     // type legalization or op legalization, we miss it. Restricting to SETLT
3916     // case for now because that is what signed saturating add/sub need.
3917     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3918     // but we would probably want to swap the true/false values if the condition
3919     // is SETGE/SETLE to avoid an XORI.
3920     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3921         CCVal == ISD::SETLT) {
3922       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3923       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3924       if (TrueVal - 1 == FalseVal)
3925         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3926       if (TrueVal + 1 == FalseVal)
3927         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3928     }
3929 
3930     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3931 
3932     SDValue TargetCC = DAG.getCondCode(CCVal);
3933     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3934     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3935   }
3936 
3937   // Otherwise:
3938   // (select condv, truev, falsev)
3939   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3940   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3941   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3942 
3943   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3944 
3945   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3946 }
3947 
3948 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3949   SDValue CondV = Op.getOperand(1);
3950   SDLoc DL(Op);
3951   MVT XLenVT = Subtarget.getXLenVT();
3952 
3953   if (CondV.getOpcode() == ISD::SETCC &&
3954       CondV.getOperand(0).getValueType() == XLenVT) {
3955     SDValue LHS = CondV.getOperand(0);
3956     SDValue RHS = CondV.getOperand(1);
3957     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3958 
3959     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3960 
3961     SDValue TargetCC = DAG.getCondCode(CCVal);
3962     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3963                        LHS, RHS, TargetCC, Op.getOperand(2));
3964   }
3965 
3966   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3967                      CondV, DAG.getConstant(0, DL, XLenVT),
3968                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3969 }
3970 
3971 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3972   MachineFunction &MF = DAG.getMachineFunction();
3973   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3974 
3975   SDLoc DL(Op);
3976   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3977                                  getPointerTy(MF.getDataLayout()));
3978 
3979   // vastart just stores the address of the VarArgsFrameIndex slot into the
3980   // memory location argument.
3981   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3982   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3983                       MachinePointerInfo(SV));
3984 }
3985 
3986 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3987                                             SelectionDAG &DAG) const {
3988   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3989   MachineFunction &MF = DAG.getMachineFunction();
3990   MachineFrameInfo &MFI = MF.getFrameInfo();
3991   MFI.setFrameAddressIsTaken(true);
3992   Register FrameReg = RI.getFrameRegister(MF);
3993   int XLenInBytes = Subtarget.getXLen() / 8;
3994 
3995   EVT VT = Op.getValueType();
3996   SDLoc DL(Op);
3997   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3998   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3999   while (Depth--) {
4000     int Offset = -(XLenInBytes * 2);
4001     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
4002                               DAG.getIntPtrConstant(Offset, DL));
4003     FrameAddr =
4004         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
4005   }
4006   return FrameAddr;
4007 }
4008 
4009 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
4010                                              SelectionDAG &DAG) const {
4011   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4012   MachineFunction &MF = DAG.getMachineFunction();
4013   MachineFrameInfo &MFI = MF.getFrameInfo();
4014   MFI.setReturnAddressIsTaken(true);
4015   MVT XLenVT = Subtarget.getXLenVT();
4016   int XLenInBytes = Subtarget.getXLen() / 8;
4017 
4018   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4019     return SDValue();
4020 
4021   EVT VT = Op.getValueType();
4022   SDLoc DL(Op);
4023   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4024   if (Depth) {
4025     int Off = -XLenInBytes;
4026     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4027     SDValue Offset = DAG.getConstant(Off, DL, VT);
4028     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4029                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4030                        MachinePointerInfo());
4031   }
4032 
4033   // Return the value of the return address register, marking it an implicit
4034   // live-in.
4035   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
4036   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
4037 }
4038 
4039 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
4040                                                  SelectionDAG &DAG) const {
4041   SDLoc DL(Op);
4042   SDValue Lo = Op.getOperand(0);
4043   SDValue Hi = Op.getOperand(1);
4044   SDValue Shamt = Op.getOperand(2);
4045   EVT VT = Lo.getValueType();
4046 
4047   // if Shamt-XLEN < 0: // Shamt < XLEN
4048   //   Lo = Lo << Shamt
4049   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
4050   // else:
4051   //   Lo = 0
4052   //   Hi = Lo << (Shamt-XLEN)
4053 
4054   SDValue Zero = DAG.getConstant(0, DL, VT);
4055   SDValue One = DAG.getConstant(1, DL, VT);
4056   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4057   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4058   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4059   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4060 
4061   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
4062   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
4063   SDValue ShiftRightLo =
4064       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
4065   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
4066   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
4067   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
4068 
4069   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4070 
4071   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
4072   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4073 
4074   SDValue Parts[2] = {Lo, Hi};
4075   return DAG.getMergeValues(Parts, DL);
4076 }
4077 
4078 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
4079                                                   bool IsSRA) const {
4080   SDLoc DL(Op);
4081   SDValue Lo = Op.getOperand(0);
4082   SDValue Hi = Op.getOperand(1);
4083   SDValue Shamt = Op.getOperand(2);
4084   EVT VT = Lo.getValueType();
4085 
4086   // SRA expansion:
4087   //   if Shamt-XLEN < 0: // Shamt < XLEN
4088   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4089   //     Hi = Hi >>s Shamt
4090   //   else:
4091   //     Lo = Hi >>s (Shamt-XLEN);
4092   //     Hi = Hi >>s (XLEN-1)
4093   //
4094   // SRL expansion:
4095   //   if Shamt-XLEN < 0: // Shamt < XLEN
4096   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4097   //     Hi = Hi >>u Shamt
4098   //   else:
4099   //     Lo = Hi >>u (Shamt-XLEN);
4100   //     Hi = 0;
4101 
4102   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4103 
4104   SDValue Zero = DAG.getConstant(0, DL, VT);
4105   SDValue One = DAG.getConstant(1, DL, VT);
4106   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4107   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4108   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4109   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4110 
4111   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4112   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4113   SDValue ShiftLeftHi =
4114       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4115   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4116   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4117   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4118   SDValue HiFalse =
4119       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4120 
4121   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4122 
4123   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4124   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4125 
4126   SDValue Parts[2] = {Lo, Hi};
4127   return DAG.getMergeValues(Parts, DL);
4128 }
4129 
4130 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4131 // legal equivalently-sized i8 type, so we can use that as a go-between.
4132 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4133                                                   SelectionDAG &DAG) const {
4134   SDLoc DL(Op);
4135   MVT VT = Op.getSimpleValueType();
4136   SDValue SplatVal = Op.getOperand(0);
4137   // All-zeros or all-ones splats are handled specially.
4138   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4139     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4140     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4141   }
4142   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4143     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4144     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4145   }
4146   MVT XLenVT = Subtarget.getXLenVT();
4147   assert(SplatVal.getValueType() == XLenVT &&
4148          "Unexpected type for i1 splat value");
4149   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4150   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4151                          DAG.getConstant(1, DL, XLenVT));
4152   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4153   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4154   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4155 }
4156 
4157 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4158 // illegal (currently only vXi64 RV32).
4159 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4160 // them to VMV_V_X_VL.
4161 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4162                                                      SelectionDAG &DAG) const {
4163   SDLoc DL(Op);
4164   MVT VecVT = Op.getSimpleValueType();
4165   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4166          "Unexpected SPLAT_VECTOR_PARTS lowering");
4167 
4168   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4169   SDValue Lo = Op.getOperand(0);
4170   SDValue Hi = Op.getOperand(1);
4171 
4172   if (VecVT.isFixedLengthVector()) {
4173     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4174     SDLoc DL(Op);
4175     SDValue Mask, VL;
4176     std::tie(Mask, VL) =
4177         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4178 
4179     SDValue Res =
4180         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4181     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4182   }
4183 
4184   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4185     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4186     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4187     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4188     // node in order to try and match RVV vector/scalar instructions.
4189     if ((LoC >> 31) == HiC)
4190       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4191                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4192   }
4193 
4194   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4195   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4196       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4197       Hi.getConstantOperandVal(1) == 31)
4198     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4199                        DAG.getRegister(RISCV::X0, MVT::i32));
4200 
4201   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4202   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4203                      DAG.getUNDEF(VecVT), Lo, Hi,
4204                      DAG.getRegister(RISCV::X0, MVT::i32));
4205 }
4206 
4207 // Custom-lower extensions from mask vectors by using a vselect either with 1
4208 // for zero/any-extension or -1 for sign-extension:
4209 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4210 // Note that any-extension is lowered identically to zero-extension.
4211 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4212                                                 int64_t ExtTrueVal) const {
4213   SDLoc DL(Op);
4214   MVT VecVT = Op.getSimpleValueType();
4215   SDValue Src = Op.getOperand(0);
4216   // Only custom-lower extensions from mask types
4217   assert(Src.getValueType().isVector() &&
4218          Src.getValueType().getVectorElementType() == MVT::i1);
4219 
4220   if (VecVT.isScalableVector()) {
4221     SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
4222     SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
4223     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4224   }
4225 
4226   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4227   MVT I1ContainerVT =
4228       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4229 
4230   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4231 
4232   SDValue Mask, VL;
4233   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4234 
4235   MVT XLenVT = Subtarget.getXLenVT();
4236   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4237   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4238 
4239   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4240                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4241   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4242                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4243   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4244                                SplatTrueVal, SplatZero, VL);
4245 
4246   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4247 }
4248 
4249 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4250     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4251   MVT ExtVT = Op.getSimpleValueType();
4252   // Only custom-lower extensions from fixed-length vector types.
4253   if (!ExtVT.isFixedLengthVector())
4254     return Op;
4255   MVT VT = Op.getOperand(0).getSimpleValueType();
4256   // Grab the canonical container type for the extended type. Infer the smaller
4257   // type from that to ensure the same number of vector elements, as we know
4258   // the LMUL will be sufficient to hold the smaller type.
4259   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4260   // Get the extended container type manually to ensure the same number of
4261   // vector elements between source and dest.
4262   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4263                                      ContainerExtVT.getVectorElementCount());
4264 
4265   SDValue Op1 =
4266       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4267 
4268   SDLoc DL(Op);
4269   SDValue Mask, VL;
4270   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4271 
4272   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4273 
4274   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4275 }
4276 
4277 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4278 // setcc operation:
4279 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4280 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op,
4281                                                       SelectionDAG &DAG) const {
4282   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4283   SDLoc DL(Op);
4284   EVT MaskVT = Op.getValueType();
4285   // Only expect to custom-lower truncations to mask types
4286   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4287          "Unexpected type for vector mask lowering");
4288   SDValue Src = Op.getOperand(0);
4289   MVT VecVT = Src.getSimpleValueType();
4290   SDValue Mask, VL;
4291   if (IsVPTrunc) {
4292     Mask = Op.getOperand(1);
4293     VL = Op.getOperand(2);
4294   }
4295   // If this is a fixed vector, we need to convert it to a scalable vector.
4296   MVT ContainerVT = VecVT;
4297 
4298   if (VecVT.isFixedLengthVector()) {
4299     ContainerVT = getContainerForFixedLengthVector(VecVT);
4300     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4301     if (IsVPTrunc) {
4302       MVT MaskContainerVT =
4303           getContainerForFixedLengthVector(Mask.getSimpleValueType());
4304       Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget);
4305     }
4306   }
4307 
4308   if (!IsVPTrunc) {
4309     std::tie(Mask, VL) =
4310         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4311   }
4312 
4313   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4314   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4315 
4316   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4317                          DAG.getUNDEF(ContainerVT), SplatOne, VL);
4318   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4319                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4320 
4321   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4322   SDValue Trunc =
4323       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4324   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4325                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4326   if (MaskVT.isFixedLengthVector())
4327     Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4328   return Trunc;
4329 }
4330 
4331 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op,
4332                                                   SelectionDAG &DAG) const {
4333   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4334   SDLoc DL(Op);
4335 
4336   MVT VT = Op.getSimpleValueType();
4337   // Only custom-lower vector truncates
4338   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4339 
4340   // Truncates to mask types are handled differently
4341   if (VT.getVectorElementType() == MVT::i1)
4342     return lowerVectorMaskTruncLike(Op, DAG);
4343 
4344   // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
4345   // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
4346   // truncate by one power of two at a time.
4347   MVT DstEltVT = VT.getVectorElementType();
4348 
4349   SDValue Src = Op.getOperand(0);
4350   MVT SrcVT = Src.getSimpleValueType();
4351   MVT SrcEltVT = SrcVT.getVectorElementType();
4352 
4353   assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) &&
4354          isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
4355          "Unexpected vector truncate lowering");
4356 
4357   MVT ContainerVT = SrcVT;
4358   SDValue Mask, VL;
4359   if (IsVPTrunc) {
4360     Mask = Op.getOperand(1);
4361     VL = Op.getOperand(2);
4362   }
4363   if (SrcVT.isFixedLengthVector()) {
4364     ContainerVT = getContainerForFixedLengthVector(SrcVT);
4365     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4366     if (IsVPTrunc) {
4367       MVT MaskVT = getMaskTypeFor(ContainerVT);
4368       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4369     }
4370   }
4371 
4372   SDValue Result = Src;
4373   if (!IsVPTrunc) {
4374     std::tie(Mask, VL) =
4375         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4376   }
4377 
4378   LLVMContext &Context = *DAG.getContext();
4379   const ElementCount Count = ContainerVT.getVectorElementCount();
4380   do {
4381     SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
4382     EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
4383     Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
4384                          Mask, VL);
4385   } while (SrcEltVT != DstEltVT);
4386 
4387   if (SrcVT.isFixedLengthVector())
4388     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4389 
4390   return Result;
4391 }
4392 
4393 SDValue
4394 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op,
4395                                                     SelectionDAG &DAG) const {
4396   bool IsVP =
4397       Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND;
4398   bool IsExtend =
4399       Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND;
4400   // RVV can only do truncate fp to types half the size as the source. We
4401   // custom-lower f64->f16 rounds via RVV's round-to-odd float
4402   // conversion instruction.
4403   SDLoc DL(Op);
4404   MVT VT = Op.getSimpleValueType();
4405 
4406   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4407 
4408   SDValue Src = Op.getOperand(0);
4409   MVT SrcVT = Src.getSimpleValueType();
4410 
4411   bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 ||
4412                                      SrcVT.getVectorElementType() != MVT::f16);
4413   bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 ||
4414                                      SrcVT.getVectorElementType() != MVT::f64);
4415 
4416   bool IsDirectConv = IsDirectExtend || IsDirectTrunc;
4417 
4418   // Prepare any fixed-length vector operands.
4419   MVT ContainerVT = VT;
4420   SDValue Mask, VL;
4421   if (IsVP) {
4422     Mask = Op.getOperand(1);
4423     VL = Op.getOperand(2);
4424   }
4425   if (VT.isFixedLengthVector()) {
4426     MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
4427     ContainerVT =
4428         SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
4429     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
4430     if (IsVP) {
4431       MVT MaskVT = getMaskTypeFor(ContainerVT);
4432       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4433     }
4434   }
4435 
4436   if (!IsVP)
4437     std::tie(Mask, VL) =
4438         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4439 
4440   unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL;
4441 
4442   if (IsDirectConv) {
4443     Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL);
4444     if (VT.isFixedLengthVector())
4445       Src = convertFromScalableVector(VT, Src, DAG, Subtarget);
4446     return Src;
4447   }
4448 
4449   unsigned InterConvOpc =
4450       IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL;
4451 
4452   MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
4453   SDValue IntermediateConv =
4454       DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL);
4455   SDValue Result =
4456       DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL);
4457   if (VT.isFixedLengthVector())
4458     return convertFromScalableVector(VT, Result, DAG, Subtarget);
4459   return Result;
4460 }
4461 
4462 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4463 // first position of a vector, and that vector is slid up to the insert index.
4464 // By limiting the active vector length to index+1 and merging with the
4465 // original vector (with an undisturbed tail policy for elements >= VL), we
4466 // achieve the desired result of leaving all elements untouched except the one
4467 // at VL-1, which is replaced with the desired value.
4468 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4469                                                     SelectionDAG &DAG) const {
4470   SDLoc DL(Op);
4471   MVT VecVT = Op.getSimpleValueType();
4472   SDValue Vec = Op.getOperand(0);
4473   SDValue Val = Op.getOperand(1);
4474   SDValue Idx = Op.getOperand(2);
4475 
4476   if (VecVT.getVectorElementType() == MVT::i1) {
4477     // FIXME: For now we just promote to an i8 vector and insert into that,
4478     // but this is probably not optimal.
4479     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4480     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4481     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4482     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4483   }
4484 
4485   MVT ContainerVT = VecVT;
4486   // If the operand is a fixed-length vector, convert to a scalable one.
4487   if (VecVT.isFixedLengthVector()) {
4488     ContainerVT = getContainerForFixedLengthVector(VecVT);
4489     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4490   }
4491 
4492   MVT XLenVT = Subtarget.getXLenVT();
4493 
4494   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4495   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4496   // Even i64-element vectors on RV32 can be lowered without scalar
4497   // legalization if the most-significant 32 bits of the value are not affected
4498   // by the sign-extension of the lower 32 bits.
4499   // TODO: We could also catch sign extensions of a 32-bit value.
4500   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4501     const auto *CVal = cast<ConstantSDNode>(Val);
4502     if (isInt<32>(CVal->getSExtValue())) {
4503       IsLegalInsert = true;
4504       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4505     }
4506   }
4507 
4508   SDValue Mask, VL;
4509   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4510 
4511   SDValue ValInVec;
4512 
4513   if (IsLegalInsert) {
4514     unsigned Opc =
4515         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4516     if (isNullConstant(Idx)) {
4517       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4518       if (!VecVT.isFixedLengthVector())
4519         return Vec;
4520       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4521     }
4522     ValInVec =
4523         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4524   } else {
4525     // On RV32, i64-element vectors must be specially handled to place the
4526     // value at element 0, by using two vslide1up instructions in sequence on
4527     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4528     // this.
4529     SDValue One = DAG.getConstant(1, DL, XLenVT);
4530     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4531     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4532     MVT I32ContainerVT =
4533         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4534     SDValue I32Mask =
4535         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4536     // Limit the active VL to two.
4537     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4538     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4539     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4540     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4541                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4542     // First slide in the hi value, then the lo in underneath it.
4543     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4544                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4545                            I32Mask, InsertI64VL);
4546     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4547                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4548                            I32Mask, InsertI64VL);
4549     // Bitcast back to the right container type.
4550     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4551   }
4552 
4553   // Now that the value is in a vector, slide it into position.
4554   SDValue InsertVL =
4555       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4556   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4557                                 ValInVec, Idx, Mask, InsertVL);
4558   if (!VecVT.isFixedLengthVector())
4559     return Slideup;
4560   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4561 }
4562 
4563 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4564 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4565 // types this is done using VMV_X_S to allow us to glean information about the
4566 // sign bits of the result.
4567 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4568                                                      SelectionDAG &DAG) const {
4569   SDLoc DL(Op);
4570   SDValue Idx = Op.getOperand(1);
4571   SDValue Vec = Op.getOperand(0);
4572   EVT EltVT = Op.getValueType();
4573   MVT VecVT = Vec.getSimpleValueType();
4574   MVT XLenVT = Subtarget.getXLenVT();
4575 
4576   if (VecVT.getVectorElementType() == MVT::i1) {
4577     if (VecVT.isFixedLengthVector()) {
4578       unsigned NumElts = VecVT.getVectorNumElements();
4579       if (NumElts >= 8) {
4580         MVT WideEltVT;
4581         unsigned WidenVecLen;
4582         SDValue ExtractElementIdx;
4583         SDValue ExtractBitIdx;
4584         unsigned MaxEEW = Subtarget.getELEN();
4585         MVT LargestEltVT = MVT::getIntegerVT(
4586             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4587         if (NumElts <= LargestEltVT.getSizeInBits()) {
4588           assert(isPowerOf2_32(NumElts) &&
4589                  "the number of elements should be power of 2");
4590           WideEltVT = MVT::getIntegerVT(NumElts);
4591           WidenVecLen = 1;
4592           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4593           ExtractBitIdx = Idx;
4594         } else {
4595           WideEltVT = LargestEltVT;
4596           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4597           // extract element index = index / element width
4598           ExtractElementIdx = DAG.getNode(
4599               ISD::SRL, DL, XLenVT, Idx,
4600               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4601           // mask bit index = index % element width
4602           ExtractBitIdx = DAG.getNode(
4603               ISD::AND, DL, XLenVT, Idx,
4604               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4605         }
4606         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4607         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4608         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4609                                          Vec, ExtractElementIdx);
4610         // Extract the bit from GPR.
4611         SDValue ShiftRight =
4612             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4613         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4614                            DAG.getConstant(1, DL, XLenVT));
4615       }
4616     }
4617     // Otherwise, promote to an i8 vector and extract from that.
4618     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4619     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4620     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4621   }
4622 
4623   // If this is a fixed vector, we need to convert it to a scalable vector.
4624   MVT ContainerVT = VecVT;
4625   if (VecVT.isFixedLengthVector()) {
4626     ContainerVT = getContainerForFixedLengthVector(VecVT);
4627     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4628   }
4629 
4630   // If the index is 0, the vector is already in the right position.
4631   if (!isNullConstant(Idx)) {
4632     // Use a VL of 1 to avoid processing more elements than we need.
4633     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4634     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
4635     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4636                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4637   }
4638 
4639   if (!EltVT.isInteger()) {
4640     // Floating-point extracts are handled in TableGen.
4641     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4642                        DAG.getConstant(0, DL, XLenVT));
4643   }
4644 
4645   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4646   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4647 }
4648 
4649 // Some RVV intrinsics may claim that they want an integer operand to be
4650 // promoted or expanded.
4651 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4652                                            const RISCVSubtarget &Subtarget) {
4653   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4654           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4655          "Unexpected opcode");
4656 
4657   if (!Subtarget.hasVInstructions())
4658     return SDValue();
4659 
4660   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4661   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4662   SDLoc DL(Op);
4663 
4664   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4665       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4666   if (!II || !II->hasScalarOperand())
4667     return SDValue();
4668 
4669   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4670   assert(SplatOp < Op.getNumOperands());
4671 
4672   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4673   SDValue &ScalarOp = Operands[SplatOp];
4674   MVT OpVT = ScalarOp.getSimpleValueType();
4675   MVT XLenVT = Subtarget.getXLenVT();
4676 
4677   // If this isn't a scalar, or its type is XLenVT we're done.
4678   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4679     return SDValue();
4680 
4681   // Simplest case is that the operand needs to be promoted to XLenVT.
4682   if (OpVT.bitsLT(XLenVT)) {
4683     // If the operand is a constant, sign extend to increase our chances
4684     // of being able to use a .vi instruction. ANY_EXTEND would become a
4685     // a zero extend and the simm5 check in isel would fail.
4686     // FIXME: Should we ignore the upper bits in isel instead?
4687     unsigned ExtOpc =
4688         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4689     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4690     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4691   }
4692 
4693   // Use the previous operand to get the vXi64 VT. The result might be a mask
4694   // VT for compares. Using the previous operand assumes that the previous
4695   // operand will never have a smaller element size than a scalar operand and
4696   // that a widening operation never uses SEW=64.
4697   // NOTE: If this fails the below assert, we can probably just find the
4698   // element count from any operand or result and use it to construct the VT.
4699   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4700   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4701 
4702   // The more complex case is when the scalar is larger than XLenVT.
4703   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4704          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4705 
4706   // If this is a sign-extended 32-bit value, we can truncate it and rely on the
4707   // instruction to sign-extend since SEW>XLEN.
4708   if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
4709     ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
4710     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4711   }
4712 
4713   switch (IntNo) {
4714   case Intrinsic::riscv_vslide1up:
4715   case Intrinsic::riscv_vslide1down:
4716   case Intrinsic::riscv_vslide1up_mask:
4717   case Intrinsic::riscv_vslide1down_mask: {
4718     // We need to special case these when the scalar is larger than XLen.
4719     unsigned NumOps = Op.getNumOperands();
4720     bool IsMasked = NumOps == 7;
4721 
4722     // Convert the vector source to the equivalent nxvXi32 vector.
4723     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4724     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4725 
4726     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4727                                    DAG.getConstant(0, DL, XLenVT));
4728     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4729                                    DAG.getConstant(1, DL, XLenVT));
4730 
4731     // Double the VL since we halved SEW.
4732     SDValue AVL = getVLOperand(Op);
4733     SDValue I32VL;
4734 
4735     // Optimize for constant AVL
4736     if (isa<ConstantSDNode>(AVL)) {
4737       unsigned EltSize = VT.getScalarSizeInBits();
4738       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4739 
4740       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4741       unsigned MaxVLMAX =
4742           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4743 
4744       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4745       unsigned MinVLMAX =
4746           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4747 
4748       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4749       if (AVLInt <= MinVLMAX) {
4750         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4751       } else if (AVLInt >= 2 * MaxVLMAX) {
4752         // Just set vl to VLMAX in this situation
4753         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4754         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4755         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4756         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4757         SDValue SETVLMAX = DAG.getTargetConstant(
4758             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4759         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4760                             LMUL);
4761       } else {
4762         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4763         // is related to the hardware implementation.
4764         // So let the following code handle
4765       }
4766     }
4767     if (!I32VL) {
4768       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4769       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4770       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4771       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4772       SDValue SETVL =
4773           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4774       // Using vsetvli instruction to get actually used length which related to
4775       // the hardware implementation
4776       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4777                                SEW, LMUL);
4778       I32VL =
4779           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4780     }
4781 
4782     SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG);
4783 
4784     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4785     // instructions.
4786     SDValue Passthru;
4787     if (IsMasked)
4788       Passthru = DAG.getUNDEF(I32VT);
4789     else
4790       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4791 
4792     if (IntNo == Intrinsic::riscv_vslide1up ||
4793         IntNo == Intrinsic::riscv_vslide1up_mask) {
4794       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4795                         ScalarHi, I32Mask, I32VL);
4796       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4797                         ScalarLo, I32Mask, I32VL);
4798     } else {
4799       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4800                         ScalarLo, I32Mask, I32VL);
4801       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4802                         ScalarHi, I32Mask, I32VL);
4803     }
4804 
4805     // Convert back to nxvXi64.
4806     Vec = DAG.getBitcast(VT, Vec);
4807 
4808     if (!IsMasked)
4809       return Vec;
4810     // Apply mask after the operation.
4811     SDValue Mask = Operands[NumOps - 3];
4812     SDValue MaskedOff = Operands[1];
4813     // Assume Policy operand is the last operand.
4814     uint64_t Policy =
4815         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4816     // We don't need to select maskedoff if it's undef.
4817     if (MaskedOff.isUndef())
4818       return Vec;
4819     // TAMU
4820     if (Policy == RISCVII::TAIL_AGNOSTIC)
4821       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4822                          AVL);
4823     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4824     // It's fine because vmerge does not care mask policy.
4825     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4826                        AVL);
4827   }
4828   }
4829 
4830   // We need to convert the scalar to a splat vector.
4831   SDValue VL = getVLOperand(Op);
4832   assert(VL.getValueType() == XLenVT);
4833   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4834   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4835 }
4836 
4837 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4838                                                      SelectionDAG &DAG) const {
4839   unsigned IntNo = Op.getConstantOperandVal(0);
4840   SDLoc DL(Op);
4841   MVT XLenVT = Subtarget.getXLenVT();
4842 
4843   switch (IntNo) {
4844   default:
4845     break; // Don't custom lower most intrinsics.
4846   case Intrinsic::thread_pointer: {
4847     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4848     return DAG.getRegister(RISCV::X4, PtrVT);
4849   }
4850   case Intrinsic::riscv_orc_b:
4851   case Intrinsic::riscv_brev8: {
4852     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4853     unsigned Opc =
4854         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4855     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4856                        DAG.getConstant(7, DL, XLenVT));
4857   }
4858   case Intrinsic::riscv_grev:
4859   case Intrinsic::riscv_gorc: {
4860     unsigned Opc =
4861         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4862     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4863   }
4864   case Intrinsic::riscv_zip:
4865   case Intrinsic::riscv_unzip: {
4866     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4867     // For i32 the immediate is 15. For i64 the immediate is 31.
4868     unsigned Opc =
4869         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4870     unsigned BitWidth = Op.getValueSizeInBits();
4871     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4872     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4873                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4874   }
4875   case Intrinsic::riscv_shfl:
4876   case Intrinsic::riscv_unshfl: {
4877     unsigned Opc =
4878         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4879     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4880   }
4881   case Intrinsic::riscv_bcompress:
4882   case Intrinsic::riscv_bdecompress: {
4883     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4884                                                        : RISCVISD::BDECOMPRESS;
4885     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4886   }
4887   case Intrinsic::riscv_bfp:
4888     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4889                        Op.getOperand(2));
4890   case Intrinsic::riscv_fsl:
4891     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4892                        Op.getOperand(2), Op.getOperand(3));
4893   case Intrinsic::riscv_fsr:
4894     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4895                        Op.getOperand(2), Op.getOperand(3));
4896   case Intrinsic::riscv_vmv_x_s:
4897     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4898     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4899                        Op.getOperand(1));
4900   case Intrinsic::riscv_vmv_v_x:
4901     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4902                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4903                             Subtarget);
4904   case Intrinsic::riscv_vfmv_v_f:
4905     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4906                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4907   case Intrinsic::riscv_vmv_s_x: {
4908     SDValue Scalar = Op.getOperand(2);
4909 
4910     if (Scalar.getValueType().bitsLE(XLenVT)) {
4911       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4912       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4913                          Op.getOperand(1), Scalar, Op.getOperand(3));
4914     }
4915 
4916     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4917 
4918     // This is an i64 value that lives in two scalar registers. We have to
4919     // insert this in a convoluted way. First we build vXi64 splat containing
4920     // the two values that we assemble using some bit math. Next we'll use
4921     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4922     // to merge element 0 from our splat into the source vector.
4923     // FIXME: This is probably not the best way to do this, but it is
4924     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4925     // point.
4926     //   sw lo, (a0)
4927     //   sw hi, 4(a0)
4928     //   vlse vX, (a0)
4929     //
4930     //   vid.v      vVid
4931     //   vmseq.vx   mMask, vVid, 0
4932     //   vmerge.vvm vDest, vSrc, vVal, mMask
4933     MVT VT = Op.getSimpleValueType();
4934     SDValue Vec = Op.getOperand(1);
4935     SDValue VL = getVLOperand(Op);
4936 
4937     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4938     if (Op.getOperand(1).isUndef())
4939       return SplattedVal;
4940     SDValue SplattedIdx =
4941         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4942                     DAG.getConstant(0, DL, MVT::i32), VL);
4943 
4944     MVT MaskVT = getMaskTypeFor(VT);
4945     SDValue Mask = getAllOnesMask(VT, VL, DL, DAG);
4946     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4947     SDValue SelectCond =
4948         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4949                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4950     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4951                        Vec, VL);
4952   }
4953   }
4954 
4955   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4956 }
4957 
4958 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4959                                                     SelectionDAG &DAG) const {
4960   unsigned IntNo = Op.getConstantOperandVal(1);
4961   switch (IntNo) {
4962   default:
4963     break;
4964   case Intrinsic::riscv_masked_strided_load: {
4965     SDLoc DL(Op);
4966     MVT XLenVT = Subtarget.getXLenVT();
4967 
4968     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4969     // the selection of the masked intrinsics doesn't do this for us.
4970     SDValue Mask = Op.getOperand(5);
4971     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4972 
4973     MVT VT = Op->getSimpleValueType(0);
4974     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4975 
4976     SDValue PassThru = Op.getOperand(2);
4977     if (!IsUnmasked) {
4978       MVT MaskVT = getMaskTypeFor(ContainerVT);
4979       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4980       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4981     }
4982 
4983     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4984 
4985     SDValue IntID = DAG.getTargetConstant(
4986         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4987         XLenVT);
4988 
4989     auto *Load = cast<MemIntrinsicSDNode>(Op);
4990     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4991     if (IsUnmasked)
4992       Ops.push_back(DAG.getUNDEF(ContainerVT));
4993     else
4994       Ops.push_back(PassThru);
4995     Ops.push_back(Op.getOperand(3)); // Ptr
4996     Ops.push_back(Op.getOperand(4)); // Stride
4997     if (!IsUnmasked)
4998       Ops.push_back(Mask);
4999     Ops.push_back(VL);
5000     if (!IsUnmasked) {
5001       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
5002       Ops.push_back(Policy);
5003     }
5004 
5005     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5006     SDValue Result =
5007         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5008                                 Load->getMemoryVT(), Load->getMemOperand());
5009     SDValue Chain = Result.getValue(1);
5010     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5011     return DAG.getMergeValues({Result, Chain}, DL);
5012   }
5013   case Intrinsic::riscv_seg2_load:
5014   case Intrinsic::riscv_seg3_load:
5015   case Intrinsic::riscv_seg4_load:
5016   case Intrinsic::riscv_seg5_load:
5017   case Intrinsic::riscv_seg6_load:
5018   case Intrinsic::riscv_seg7_load:
5019   case Intrinsic::riscv_seg8_load: {
5020     SDLoc DL(Op);
5021     static const Intrinsic::ID VlsegInts[7] = {
5022         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
5023         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
5024         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
5025         Intrinsic::riscv_vlseg8};
5026     unsigned NF = Op->getNumValues() - 1;
5027     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
5028     MVT XLenVT = Subtarget.getXLenVT();
5029     MVT VT = Op->getSimpleValueType(0);
5030     MVT ContainerVT = getContainerForFixedLengthVector(VT);
5031 
5032     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5033     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
5034     auto *Load = cast<MemIntrinsicSDNode>(Op);
5035     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
5036     ContainerVTs.push_back(MVT::Other);
5037     SDVTList VTs = DAG.getVTList(ContainerVTs);
5038     SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID};
5039     Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT));
5040     Ops.push_back(Op.getOperand(2));
5041     Ops.push_back(VL);
5042     SDValue Result =
5043         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5044                                 Load->getMemoryVT(), Load->getMemOperand());
5045     SmallVector<SDValue, 9> Results;
5046     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
5047       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
5048                                                   DAG, Subtarget));
5049     Results.push_back(Result.getValue(NF));
5050     return DAG.getMergeValues(Results, DL);
5051   }
5052   }
5053 
5054   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
5055 }
5056 
5057 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
5058                                                  SelectionDAG &DAG) const {
5059   unsigned IntNo = Op.getConstantOperandVal(1);
5060   switch (IntNo) {
5061   default:
5062     break;
5063   case Intrinsic::riscv_masked_strided_store: {
5064     SDLoc DL(Op);
5065     MVT XLenVT = Subtarget.getXLenVT();
5066 
5067     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5068     // the selection of the masked intrinsics doesn't do this for us.
5069     SDValue Mask = Op.getOperand(5);
5070     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5071 
5072     SDValue Val = Op.getOperand(2);
5073     MVT VT = Val.getSimpleValueType();
5074     MVT ContainerVT = getContainerForFixedLengthVector(VT);
5075 
5076     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5077     if (!IsUnmasked) {
5078       MVT MaskVT = getMaskTypeFor(ContainerVT);
5079       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5080     }
5081 
5082     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5083 
5084     SDValue IntID = DAG.getTargetConstant(
5085         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
5086         XLenVT);
5087 
5088     auto *Store = cast<MemIntrinsicSDNode>(Op);
5089     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
5090     Ops.push_back(Val);
5091     Ops.push_back(Op.getOperand(3)); // Ptr
5092     Ops.push_back(Op.getOperand(4)); // Stride
5093     if (!IsUnmasked)
5094       Ops.push_back(Mask);
5095     Ops.push_back(VL);
5096 
5097     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
5098                                    Ops, Store->getMemoryVT(),
5099                                    Store->getMemOperand());
5100   }
5101   }
5102 
5103   return SDValue();
5104 }
5105 
5106 static MVT getLMUL1VT(MVT VT) {
5107   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
5108          "Unexpected vector MVT");
5109   return MVT::getScalableVectorVT(
5110       VT.getVectorElementType(),
5111       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
5112 }
5113 
5114 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
5115   switch (ISDOpcode) {
5116   default:
5117     llvm_unreachable("Unhandled reduction");
5118   case ISD::VECREDUCE_ADD:
5119     return RISCVISD::VECREDUCE_ADD_VL;
5120   case ISD::VECREDUCE_UMAX:
5121     return RISCVISD::VECREDUCE_UMAX_VL;
5122   case ISD::VECREDUCE_SMAX:
5123     return RISCVISD::VECREDUCE_SMAX_VL;
5124   case ISD::VECREDUCE_UMIN:
5125     return RISCVISD::VECREDUCE_UMIN_VL;
5126   case ISD::VECREDUCE_SMIN:
5127     return RISCVISD::VECREDUCE_SMIN_VL;
5128   case ISD::VECREDUCE_AND:
5129     return RISCVISD::VECREDUCE_AND_VL;
5130   case ISD::VECREDUCE_OR:
5131     return RISCVISD::VECREDUCE_OR_VL;
5132   case ISD::VECREDUCE_XOR:
5133     return RISCVISD::VECREDUCE_XOR_VL;
5134   }
5135 }
5136 
5137 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
5138                                                          SelectionDAG &DAG,
5139                                                          bool IsVP) const {
5140   SDLoc DL(Op);
5141   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5142   MVT VecVT = Vec.getSimpleValueType();
5143   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5144           Op.getOpcode() == ISD::VECREDUCE_OR ||
5145           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5146           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5147           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5148           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5149          "Unexpected reduction lowering");
5150 
5151   MVT XLenVT = Subtarget.getXLenVT();
5152   assert(Op.getValueType() == XLenVT &&
5153          "Expected reduction output to be legalized to XLenVT");
5154 
5155   MVT ContainerVT = VecVT;
5156   if (VecVT.isFixedLengthVector()) {
5157     ContainerVT = getContainerForFixedLengthVector(VecVT);
5158     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5159   }
5160 
5161   SDValue Mask, VL;
5162   if (IsVP) {
5163     Mask = Op.getOperand(2);
5164     VL = Op.getOperand(3);
5165   } else {
5166     std::tie(Mask, VL) =
5167         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5168   }
5169 
5170   unsigned BaseOpc;
5171   ISD::CondCode CC;
5172   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5173 
5174   switch (Op.getOpcode()) {
5175   default:
5176     llvm_unreachable("Unhandled reduction");
5177   case ISD::VECREDUCE_AND:
5178   case ISD::VP_REDUCE_AND: {
5179     // vcpop ~x == 0
5180     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5181     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5182     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5183     CC = ISD::SETEQ;
5184     BaseOpc = ISD::AND;
5185     break;
5186   }
5187   case ISD::VECREDUCE_OR:
5188   case ISD::VP_REDUCE_OR:
5189     // vcpop x != 0
5190     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5191     CC = ISD::SETNE;
5192     BaseOpc = ISD::OR;
5193     break;
5194   case ISD::VECREDUCE_XOR:
5195   case ISD::VP_REDUCE_XOR: {
5196     // ((vcpop x) & 1) != 0
5197     SDValue One = DAG.getConstant(1, DL, XLenVT);
5198     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5199     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5200     CC = ISD::SETNE;
5201     BaseOpc = ISD::XOR;
5202     break;
5203   }
5204   }
5205 
5206   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5207 
5208   if (!IsVP)
5209     return SetCC;
5210 
5211   // Now include the start value in the operation.
5212   // Note that we must return the start value when no elements are operated
5213   // upon. The vcpop instructions we've emitted in each case above will return
5214   // 0 for an inactive vector, and so we've already received the neutral value:
5215   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5216   // can simply include the start value.
5217   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5218 }
5219 
5220 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5221                                             SelectionDAG &DAG) const {
5222   SDLoc DL(Op);
5223   SDValue Vec = Op.getOperand(0);
5224   EVT VecEVT = Vec.getValueType();
5225 
5226   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5227 
5228   // Due to ordering in legalize types we may have a vector type that needs to
5229   // be split. Do that manually so we can get down to a legal type.
5230   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5231          TargetLowering::TypeSplitVector) {
5232     SDValue Lo, Hi;
5233     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5234     VecEVT = Lo.getValueType();
5235     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5236   }
5237 
5238   // TODO: The type may need to be widened rather than split. Or widened before
5239   // it can be split.
5240   if (!isTypeLegal(VecEVT))
5241     return SDValue();
5242 
5243   MVT VecVT = VecEVT.getSimpleVT();
5244   MVT VecEltVT = VecVT.getVectorElementType();
5245   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5246 
5247   MVT ContainerVT = VecVT;
5248   if (VecVT.isFixedLengthVector()) {
5249     ContainerVT = getContainerForFixedLengthVector(VecVT);
5250     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5251   }
5252 
5253   MVT M1VT = getLMUL1VT(ContainerVT);
5254   MVT XLenVT = Subtarget.getXLenVT();
5255 
5256   SDValue Mask, VL;
5257   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5258 
5259   SDValue NeutralElem =
5260       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5261   SDValue IdentitySplat =
5262       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5263                        M1VT, DL, DAG, Subtarget);
5264   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5265                                   IdentitySplat, Mask, VL);
5266   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5267                              DAG.getConstant(0, DL, XLenVT));
5268   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5269 }
5270 
5271 // Given a reduction op, this function returns the matching reduction opcode,
5272 // the vector SDValue and the scalar SDValue required to lower this to a
5273 // RISCVISD node.
5274 static std::tuple<unsigned, SDValue, SDValue>
5275 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5276   SDLoc DL(Op);
5277   auto Flags = Op->getFlags();
5278   unsigned Opcode = Op.getOpcode();
5279   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5280   switch (Opcode) {
5281   default:
5282     llvm_unreachable("Unhandled reduction");
5283   case ISD::VECREDUCE_FADD: {
5284     // Use positive zero if we can. It is cheaper to materialize.
5285     SDValue Zero =
5286         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5287     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5288   }
5289   case ISD::VECREDUCE_SEQ_FADD:
5290     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5291                            Op.getOperand(0));
5292   case ISD::VECREDUCE_FMIN:
5293     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5294                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5295   case ISD::VECREDUCE_FMAX:
5296     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5297                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5298   }
5299 }
5300 
5301 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5302                                               SelectionDAG &DAG) const {
5303   SDLoc DL(Op);
5304   MVT VecEltVT = Op.getSimpleValueType();
5305 
5306   unsigned RVVOpcode;
5307   SDValue VectorVal, ScalarVal;
5308   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5309       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5310   MVT VecVT = VectorVal.getSimpleValueType();
5311 
5312   MVT ContainerVT = VecVT;
5313   if (VecVT.isFixedLengthVector()) {
5314     ContainerVT = getContainerForFixedLengthVector(VecVT);
5315     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5316   }
5317 
5318   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5319   MVT XLenVT = Subtarget.getXLenVT();
5320 
5321   SDValue Mask, VL;
5322   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5323 
5324   SDValue ScalarSplat =
5325       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5326                        M1VT, DL, DAG, Subtarget);
5327   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5328                                   VectorVal, ScalarSplat, Mask, VL);
5329   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5330                      DAG.getConstant(0, DL, XLenVT));
5331 }
5332 
5333 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5334   switch (ISDOpcode) {
5335   default:
5336     llvm_unreachable("Unhandled reduction");
5337   case ISD::VP_REDUCE_ADD:
5338     return RISCVISD::VECREDUCE_ADD_VL;
5339   case ISD::VP_REDUCE_UMAX:
5340     return RISCVISD::VECREDUCE_UMAX_VL;
5341   case ISD::VP_REDUCE_SMAX:
5342     return RISCVISD::VECREDUCE_SMAX_VL;
5343   case ISD::VP_REDUCE_UMIN:
5344     return RISCVISD::VECREDUCE_UMIN_VL;
5345   case ISD::VP_REDUCE_SMIN:
5346     return RISCVISD::VECREDUCE_SMIN_VL;
5347   case ISD::VP_REDUCE_AND:
5348     return RISCVISD::VECREDUCE_AND_VL;
5349   case ISD::VP_REDUCE_OR:
5350     return RISCVISD::VECREDUCE_OR_VL;
5351   case ISD::VP_REDUCE_XOR:
5352     return RISCVISD::VECREDUCE_XOR_VL;
5353   case ISD::VP_REDUCE_FADD:
5354     return RISCVISD::VECREDUCE_FADD_VL;
5355   case ISD::VP_REDUCE_SEQ_FADD:
5356     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5357   case ISD::VP_REDUCE_FMAX:
5358     return RISCVISD::VECREDUCE_FMAX_VL;
5359   case ISD::VP_REDUCE_FMIN:
5360     return RISCVISD::VECREDUCE_FMIN_VL;
5361   }
5362 }
5363 
5364 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5365                                            SelectionDAG &DAG) const {
5366   SDLoc DL(Op);
5367   SDValue Vec = Op.getOperand(1);
5368   EVT VecEVT = Vec.getValueType();
5369 
5370   // TODO: The type may need to be widened rather than split. Or widened before
5371   // it can be split.
5372   if (!isTypeLegal(VecEVT))
5373     return SDValue();
5374 
5375   MVT VecVT = VecEVT.getSimpleVT();
5376   MVT VecEltVT = VecVT.getVectorElementType();
5377   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5378 
5379   MVT ContainerVT = VecVT;
5380   if (VecVT.isFixedLengthVector()) {
5381     ContainerVT = getContainerForFixedLengthVector(VecVT);
5382     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5383   }
5384 
5385   SDValue VL = Op.getOperand(3);
5386   SDValue Mask = Op.getOperand(2);
5387 
5388   MVT M1VT = getLMUL1VT(ContainerVT);
5389   MVT XLenVT = Subtarget.getXLenVT();
5390   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5391 
5392   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5393                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5394                                         DL, DAG, Subtarget);
5395   SDValue Reduction =
5396       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5397   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5398                              DAG.getConstant(0, DL, XLenVT));
5399   if (!VecVT.isInteger())
5400     return Elt0;
5401   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5402 }
5403 
5404 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5405                                                    SelectionDAG &DAG) const {
5406   SDValue Vec = Op.getOperand(0);
5407   SDValue SubVec = Op.getOperand(1);
5408   MVT VecVT = Vec.getSimpleValueType();
5409   MVT SubVecVT = SubVec.getSimpleValueType();
5410 
5411   SDLoc DL(Op);
5412   MVT XLenVT = Subtarget.getXLenVT();
5413   unsigned OrigIdx = Op.getConstantOperandVal(2);
5414   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5415 
5416   // We don't have the ability to slide mask vectors up indexed by their i1
5417   // elements; the smallest we can do is i8. Often we are able to bitcast to
5418   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5419   // into a scalable one, we might not necessarily have enough scalable
5420   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5421   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5422       (OrigIdx != 0 || !Vec.isUndef())) {
5423     if (VecVT.getVectorMinNumElements() >= 8 &&
5424         SubVecVT.getVectorMinNumElements() >= 8) {
5425       assert(OrigIdx % 8 == 0 && "Invalid index");
5426       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5427              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5428              "Unexpected mask vector lowering");
5429       OrigIdx /= 8;
5430       SubVecVT =
5431           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5432                            SubVecVT.isScalableVector());
5433       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5434                                VecVT.isScalableVector());
5435       Vec = DAG.getBitcast(VecVT, Vec);
5436       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5437     } else {
5438       // We can't slide this mask vector up indexed by its i1 elements.
5439       // This poses a problem when we wish to insert a scalable vector which
5440       // can't be re-expressed as a larger type. Just choose the slow path and
5441       // extend to a larger type, then truncate back down.
5442       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5443       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5444       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5445       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5446       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5447                         Op.getOperand(2));
5448       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5449       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5450     }
5451   }
5452 
5453   // If the subvector vector is a fixed-length type, we cannot use subregister
5454   // manipulation to simplify the codegen; we don't know which register of a
5455   // LMUL group contains the specific subvector as we only know the minimum
5456   // register size. Therefore we must slide the vector group up the full
5457   // amount.
5458   if (SubVecVT.isFixedLengthVector()) {
5459     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5460       return Op;
5461     MVT ContainerVT = VecVT;
5462     if (VecVT.isFixedLengthVector()) {
5463       ContainerVT = getContainerForFixedLengthVector(VecVT);
5464       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5465     }
5466     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5467                          DAG.getUNDEF(ContainerVT), SubVec,
5468                          DAG.getConstant(0, DL, XLenVT));
5469     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5470       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5471       return DAG.getBitcast(Op.getValueType(), SubVec);
5472     }
5473     SDValue Mask =
5474         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5475     // Set the vector length to only the number of elements we care about. Note
5476     // that for slideup this includes the offset.
5477     SDValue VL =
5478         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5479     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5480     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5481                                   SubVec, SlideupAmt, Mask, VL);
5482     if (VecVT.isFixedLengthVector())
5483       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5484     return DAG.getBitcast(Op.getValueType(), Slideup);
5485   }
5486 
5487   unsigned SubRegIdx, RemIdx;
5488   std::tie(SubRegIdx, RemIdx) =
5489       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5490           VecVT, SubVecVT, OrigIdx, TRI);
5491 
5492   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5493   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5494                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5495                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5496 
5497   // 1. If the Idx has been completely eliminated and this subvector's size is
5498   // a vector register or a multiple thereof, or the surrounding elements are
5499   // undef, then this is a subvector insert which naturally aligns to a vector
5500   // register. These can easily be handled using subregister manipulation.
5501   // 2. If the subvector is smaller than a vector register, then the insertion
5502   // must preserve the undisturbed elements of the register. We do this by
5503   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5504   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5505   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5506   // LMUL=1 type back into the larger vector (resolving to another subregister
5507   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5508   // to avoid allocating a large register group to hold our subvector.
5509   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5510     return Op;
5511 
5512   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5513   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5514   // (in our case undisturbed). This means we can set up a subvector insertion
5515   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5516   // size of the subvector.
5517   MVT InterSubVT = VecVT;
5518   SDValue AlignedExtract = Vec;
5519   unsigned AlignedIdx = OrigIdx - RemIdx;
5520   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5521     InterSubVT = getLMUL1VT(VecVT);
5522     // Extract a subvector equal to the nearest full vector register type. This
5523     // should resolve to a EXTRACT_SUBREG instruction.
5524     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5525                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5526   }
5527 
5528   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5529   // For scalable vectors this must be further multiplied by vscale.
5530   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5531 
5532   SDValue Mask, VL;
5533   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5534 
5535   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5536   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5537   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5538   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5539 
5540   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5541                        DAG.getUNDEF(InterSubVT), SubVec,
5542                        DAG.getConstant(0, DL, XLenVT));
5543 
5544   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5545                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5546 
5547   // If required, insert this subvector back into the correct vector register.
5548   // This should resolve to an INSERT_SUBREG instruction.
5549   if (VecVT.bitsGT(InterSubVT))
5550     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5551                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5552 
5553   // We might have bitcast from a mask type: cast back to the original type if
5554   // required.
5555   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5556 }
5557 
5558 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5559                                                     SelectionDAG &DAG) const {
5560   SDValue Vec = Op.getOperand(0);
5561   MVT SubVecVT = Op.getSimpleValueType();
5562   MVT VecVT = Vec.getSimpleValueType();
5563 
5564   SDLoc DL(Op);
5565   MVT XLenVT = Subtarget.getXLenVT();
5566   unsigned OrigIdx = Op.getConstantOperandVal(1);
5567   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5568 
5569   // We don't have the ability to slide mask vectors down indexed by their i1
5570   // elements; the smallest we can do is i8. Often we are able to bitcast to
5571   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5572   // from a scalable one, we might not necessarily have enough scalable
5573   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5574   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5575     if (VecVT.getVectorMinNumElements() >= 8 &&
5576         SubVecVT.getVectorMinNumElements() >= 8) {
5577       assert(OrigIdx % 8 == 0 && "Invalid index");
5578       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5579              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5580              "Unexpected mask vector lowering");
5581       OrigIdx /= 8;
5582       SubVecVT =
5583           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5584                            SubVecVT.isScalableVector());
5585       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5586                                VecVT.isScalableVector());
5587       Vec = DAG.getBitcast(VecVT, Vec);
5588     } else {
5589       // We can't slide this mask vector down, indexed by its i1 elements.
5590       // This poses a problem when we wish to extract a scalable vector which
5591       // can't be re-expressed as a larger type. Just choose the slow path and
5592       // extend to a larger type, then truncate back down.
5593       // TODO: We could probably improve this when extracting certain fixed
5594       // from fixed, where we can extract as i8 and shift the correct element
5595       // right to reach the desired subvector?
5596       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5597       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5598       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5599       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5600                         Op.getOperand(1));
5601       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5602       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5603     }
5604   }
5605 
5606   // If the subvector vector is a fixed-length type, we cannot use subregister
5607   // manipulation to simplify the codegen; we don't know which register of a
5608   // LMUL group contains the specific subvector as we only know the minimum
5609   // register size. Therefore we must slide the vector group down the full
5610   // amount.
5611   if (SubVecVT.isFixedLengthVector()) {
5612     // With an index of 0 this is a cast-like subvector, which can be performed
5613     // with subregister operations.
5614     if (OrigIdx == 0)
5615       return Op;
5616     MVT ContainerVT = VecVT;
5617     if (VecVT.isFixedLengthVector()) {
5618       ContainerVT = getContainerForFixedLengthVector(VecVT);
5619       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5620     }
5621     SDValue Mask =
5622         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5623     // Set the vector length to only the number of elements we care about. This
5624     // avoids sliding down elements we're going to discard straight away.
5625     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5626     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5627     SDValue Slidedown =
5628         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5629                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5630     // Now we can use a cast-like subvector extract to get the result.
5631     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5632                             DAG.getConstant(0, DL, XLenVT));
5633     return DAG.getBitcast(Op.getValueType(), Slidedown);
5634   }
5635 
5636   unsigned SubRegIdx, RemIdx;
5637   std::tie(SubRegIdx, RemIdx) =
5638       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5639           VecVT, SubVecVT, OrigIdx, TRI);
5640 
5641   // If the Idx has been completely eliminated then this is a subvector extract
5642   // which naturally aligns to a vector register. These can easily be handled
5643   // using subregister manipulation.
5644   if (RemIdx == 0)
5645     return Op;
5646 
5647   // Else we must shift our vector register directly to extract the subvector.
5648   // Do this using VSLIDEDOWN.
5649 
5650   // If the vector type is an LMUL-group type, extract a subvector equal to the
5651   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5652   // instruction.
5653   MVT InterSubVT = VecVT;
5654   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5655     InterSubVT = getLMUL1VT(VecVT);
5656     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5657                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5658   }
5659 
5660   // Slide this vector register down by the desired number of elements in order
5661   // to place the desired subvector starting at element 0.
5662   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5663   // For scalable vectors this must be further multiplied by vscale.
5664   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5665 
5666   SDValue Mask, VL;
5667   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5668   SDValue Slidedown =
5669       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5670                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5671 
5672   // Now the vector is in the right position, extract our final subvector. This
5673   // should resolve to a COPY.
5674   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5675                           DAG.getConstant(0, DL, XLenVT));
5676 
5677   // We might have bitcast from a mask type: cast back to the original type if
5678   // required.
5679   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5680 }
5681 
5682 // Lower step_vector to the vid instruction. Any non-identity step value must
5683 // be accounted for my manual expansion.
5684 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5685                                               SelectionDAG &DAG) const {
5686   SDLoc DL(Op);
5687   MVT VT = Op.getSimpleValueType();
5688   MVT XLenVT = Subtarget.getXLenVT();
5689   SDValue Mask, VL;
5690   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5691   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5692   uint64_t StepValImm = Op.getConstantOperandVal(0);
5693   if (StepValImm != 1) {
5694     if (isPowerOf2_64(StepValImm)) {
5695       SDValue StepVal =
5696           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5697                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5698       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5699     } else {
5700       SDValue StepVal = lowerScalarSplat(
5701           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5702           VL, VT, DL, DAG, Subtarget);
5703       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5704     }
5705   }
5706   return StepVec;
5707 }
5708 
5709 // Implement vector_reverse using vrgather.vv with indices determined by
5710 // subtracting the id of each element from (VLMAX-1). This will convert
5711 // the indices like so:
5712 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5713 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5714 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5715                                                  SelectionDAG &DAG) const {
5716   SDLoc DL(Op);
5717   MVT VecVT = Op.getSimpleValueType();
5718   if (VecVT.getVectorElementType() == MVT::i1) {
5719     MVT WidenVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
5720     SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenVT, Op.getOperand(0));
5721     SDValue Op2 = DAG.getNode(ISD::VECTOR_REVERSE, DL, WidenVT, Op1);
5722     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Op2);
5723   }
5724   unsigned EltSize = VecVT.getScalarSizeInBits();
5725   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5726   unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
5727   unsigned MaxVLMAX =
5728     RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5729 
5730   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5731   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5732 
5733   // If this is SEW=8 and VLMAX is potentially more than 256, we need
5734   // to use vrgatherei16.vv.
5735   // TODO: It's also possible to use vrgatherei16.vv for other types to
5736   // decrease register width for the index calculation.
5737   if (MaxVLMAX > 256 && EltSize == 8) {
5738     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5739     // Reverse each half, then reassemble them in reverse order.
5740     // NOTE: It's also possible that after splitting that VLMAX no longer
5741     // requires vrgatherei16.vv.
5742     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5743       SDValue Lo, Hi;
5744       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5745       EVT LoVT, HiVT;
5746       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5747       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5748       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5749       // Reassemble the low and high pieces reversed.
5750       // FIXME: This is a CONCAT_VECTORS.
5751       SDValue Res =
5752           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5753                       DAG.getIntPtrConstant(0, DL));
5754       return DAG.getNode(
5755           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5756           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5757     }
5758 
5759     // Just promote the int type to i16 which will double the LMUL.
5760     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5761     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5762   }
5763 
5764   MVT XLenVT = Subtarget.getXLenVT();
5765   SDValue Mask, VL;
5766   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5767 
5768   // Calculate VLMAX-1 for the desired SEW.
5769   unsigned MinElts = VecVT.getVectorMinNumElements();
5770   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5771                               DAG.getConstant(MinElts, DL, XLenVT));
5772   SDValue VLMinus1 =
5773       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5774 
5775   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5776   bool IsRV32E64 =
5777       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5778   SDValue SplatVL;
5779   if (!IsRV32E64)
5780     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5781   else
5782     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5783                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5784 
5785   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5786   SDValue Indices =
5787       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5788 
5789   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask,
5790                      DAG.getUNDEF(VecVT), VL);
5791 }
5792 
5793 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5794                                                 SelectionDAG &DAG) const {
5795   SDLoc DL(Op);
5796   SDValue V1 = Op.getOperand(0);
5797   SDValue V2 = Op.getOperand(1);
5798   MVT XLenVT = Subtarget.getXLenVT();
5799   MVT VecVT = Op.getSimpleValueType();
5800 
5801   unsigned MinElts = VecVT.getVectorMinNumElements();
5802   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5803                               DAG.getConstant(MinElts, DL, XLenVT));
5804 
5805   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5806   SDValue DownOffset, UpOffset;
5807   if (ImmValue >= 0) {
5808     // The operand is a TargetConstant, we need to rebuild it as a regular
5809     // constant.
5810     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5811     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5812   } else {
5813     // The operand is a TargetConstant, we need to rebuild it as a regular
5814     // constant rather than negating the original operand.
5815     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5816     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5817   }
5818 
5819   SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG);
5820 
5821   SDValue SlideDown =
5822       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5823                   DownOffset, TrueMask, UpOffset);
5824   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5825                      TrueMask, DAG.getRegister(RISCV::X0, XLenVT));
5826 }
5827 
5828 SDValue
5829 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5830                                                      SelectionDAG &DAG) const {
5831   SDLoc DL(Op);
5832   auto *Load = cast<LoadSDNode>(Op);
5833 
5834   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5835                                         Load->getMemoryVT(),
5836                                         *Load->getMemOperand()) &&
5837          "Expecting a correctly-aligned load");
5838 
5839   MVT VT = Op.getSimpleValueType();
5840   MVT XLenVT = Subtarget.getXLenVT();
5841   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5842 
5843   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5844 
5845   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5846   SDValue IntID = DAG.getTargetConstant(
5847       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5848   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5849   if (!IsMaskOp)
5850     Ops.push_back(DAG.getUNDEF(ContainerVT));
5851   Ops.push_back(Load->getBasePtr());
5852   Ops.push_back(VL);
5853   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5854   SDValue NewLoad =
5855       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5856                               Load->getMemoryVT(), Load->getMemOperand());
5857 
5858   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5859   return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL);
5860 }
5861 
5862 SDValue
5863 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5864                                                       SelectionDAG &DAG) const {
5865   SDLoc DL(Op);
5866   auto *Store = cast<StoreSDNode>(Op);
5867 
5868   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5869                                         Store->getMemoryVT(),
5870                                         *Store->getMemOperand()) &&
5871          "Expecting a correctly-aligned store");
5872 
5873   SDValue StoreVal = Store->getValue();
5874   MVT VT = StoreVal.getSimpleValueType();
5875   MVT XLenVT = Subtarget.getXLenVT();
5876 
5877   // If the size less than a byte, we need to pad with zeros to make a byte.
5878   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5879     VT = MVT::v8i1;
5880     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5881                            DAG.getConstant(0, DL, VT), StoreVal,
5882                            DAG.getIntPtrConstant(0, DL));
5883   }
5884 
5885   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5886 
5887   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5888 
5889   SDValue NewValue =
5890       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5891 
5892   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5893   SDValue IntID = DAG.getTargetConstant(
5894       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5895   return DAG.getMemIntrinsicNode(
5896       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5897       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5898       Store->getMemoryVT(), Store->getMemOperand());
5899 }
5900 
5901 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5902                                              SelectionDAG &DAG) const {
5903   SDLoc DL(Op);
5904   MVT VT = Op.getSimpleValueType();
5905 
5906   const auto *MemSD = cast<MemSDNode>(Op);
5907   EVT MemVT = MemSD->getMemoryVT();
5908   MachineMemOperand *MMO = MemSD->getMemOperand();
5909   SDValue Chain = MemSD->getChain();
5910   SDValue BasePtr = MemSD->getBasePtr();
5911 
5912   SDValue Mask, PassThru, VL;
5913   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5914     Mask = VPLoad->getMask();
5915     PassThru = DAG.getUNDEF(VT);
5916     VL = VPLoad->getVectorLength();
5917   } else {
5918     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5919     Mask = MLoad->getMask();
5920     PassThru = MLoad->getPassThru();
5921   }
5922 
5923   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5924 
5925   MVT XLenVT = Subtarget.getXLenVT();
5926 
5927   MVT ContainerVT = VT;
5928   if (VT.isFixedLengthVector()) {
5929     ContainerVT = getContainerForFixedLengthVector(VT);
5930     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5931     if (!IsUnmasked) {
5932       MVT MaskVT = getMaskTypeFor(ContainerVT);
5933       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5934     }
5935   }
5936 
5937   if (!VL)
5938     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5939 
5940   unsigned IntID =
5941       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5942   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5943   if (IsUnmasked)
5944     Ops.push_back(DAG.getUNDEF(ContainerVT));
5945   else
5946     Ops.push_back(PassThru);
5947   Ops.push_back(BasePtr);
5948   if (!IsUnmasked)
5949     Ops.push_back(Mask);
5950   Ops.push_back(VL);
5951   if (!IsUnmasked)
5952     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5953 
5954   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5955 
5956   SDValue Result =
5957       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5958   Chain = Result.getValue(1);
5959 
5960   if (VT.isFixedLengthVector())
5961     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5962 
5963   return DAG.getMergeValues({Result, Chain}, DL);
5964 }
5965 
5966 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5967                                               SelectionDAG &DAG) const {
5968   SDLoc DL(Op);
5969 
5970   const auto *MemSD = cast<MemSDNode>(Op);
5971   EVT MemVT = MemSD->getMemoryVT();
5972   MachineMemOperand *MMO = MemSD->getMemOperand();
5973   SDValue Chain = MemSD->getChain();
5974   SDValue BasePtr = MemSD->getBasePtr();
5975   SDValue Val, Mask, VL;
5976 
5977   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5978     Val = VPStore->getValue();
5979     Mask = VPStore->getMask();
5980     VL = VPStore->getVectorLength();
5981   } else {
5982     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5983     Val = MStore->getValue();
5984     Mask = MStore->getMask();
5985   }
5986 
5987   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5988 
5989   MVT VT = Val.getSimpleValueType();
5990   MVT XLenVT = Subtarget.getXLenVT();
5991 
5992   MVT ContainerVT = VT;
5993   if (VT.isFixedLengthVector()) {
5994     ContainerVT = getContainerForFixedLengthVector(VT);
5995 
5996     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5997     if (!IsUnmasked) {
5998       MVT MaskVT = getMaskTypeFor(ContainerVT);
5999       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6000     }
6001   }
6002 
6003   if (!VL)
6004     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6005 
6006   unsigned IntID =
6007       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
6008   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6009   Ops.push_back(Val);
6010   Ops.push_back(BasePtr);
6011   if (!IsUnmasked)
6012     Ops.push_back(Mask);
6013   Ops.push_back(VL);
6014 
6015   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6016                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6017 }
6018 
6019 SDValue
6020 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
6021                                                       SelectionDAG &DAG) const {
6022   MVT InVT = Op.getOperand(0).getSimpleValueType();
6023   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
6024 
6025   MVT VT = Op.getSimpleValueType();
6026 
6027   SDValue Op1 =
6028       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
6029   SDValue Op2 =
6030       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6031 
6032   SDLoc DL(Op);
6033   SDValue VL =
6034       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
6035 
6036   MVT MaskVT = getMaskTypeFor(ContainerVT);
6037   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
6038 
6039   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
6040                             Op.getOperand(2), Mask, VL);
6041 
6042   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
6043 }
6044 
6045 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
6046     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
6047   MVT VT = Op.getSimpleValueType();
6048 
6049   if (VT.getVectorElementType() == MVT::i1)
6050     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
6051 
6052   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
6053 }
6054 
6055 SDValue
6056 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
6057                                                       SelectionDAG &DAG) const {
6058   unsigned Opc;
6059   switch (Op.getOpcode()) {
6060   default: llvm_unreachable("Unexpected opcode!");
6061   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
6062   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
6063   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
6064   }
6065 
6066   return lowerToScalableOp(Op, DAG, Opc);
6067 }
6068 
6069 // Lower vector ABS to smax(X, sub(0, X)).
6070 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
6071   SDLoc DL(Op);
6072   MVT VT = Op.getSimpleValueType();
6073   SDValue X = Op.getOperand(0);
6074 
6075   assert(VT.isFixedLengthVector() && "Unexpected type");
6076 
6077   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6078   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
6079 
6080   SDValue Mask, VL;
6081   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6082 
6083   SDValue SplatZero = DAG.getNode(
6084       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
6085       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
6086   SDValue NegX =
6087       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
6088   SDValue Max =
6089       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
6090 
6091   return convertFromScalableVector(VT, Max, DAG, Subtarget);
6092 }
6093 
6094 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
6095     SDValue Op, SelectionDAG &DAG) const {
6096   SDLoc DL(Op);
6097   MVT VT = Op.getSimpleValueType();
6098   SDValue Mag = Op.getOperand(0);
6099   SDValue Sign = Op.getOperand(1);
6100   assert(Mag.getValueType() == Sign.getValueType() &&
6101          "Can only handle COPYSIGN with matching types.");
6102 
6103   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6104   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
6105   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
6106 
6107   SDValue Mask, VL;
6108   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6109 
6110   SDValue CopySign =
6111       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
6112 
6113   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
6114 }
6115 
6116 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
6117     SDValue Op, SelectionDAG &DAG) const {
6118   MVT VT = Op.getSimpleValueType();
6119   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6120 
6121   MVT I1ContainerVT =
6122       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6123 
6124   SDValue CC =
6125       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
6126   SDValue Op1 =
6127       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6128   SDValue Op2 =
6129       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
6130 
6131   SDLoc DL(Op);
6132   SDValue Mask, VL;
6133   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6134 
6135   SDValue Select =
6136       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
6137 
6138   return convertFromScalableVector(VT, Select, DAG, Subtarget);
6139 }
6140 
6141 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
6142                                                unsigned NewOpc,
6143                                                bool HasMask) const {
6144   MVT VT = Op.getSimpleValueType();
6145   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6146 
6147   // Create list of operands by converting existing ones to scalable types.
6148   SmallVector<SDValue, 6> Ops;
6149   for (const SDValue &V : Op->op_values()) {
6150     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6151 
6152     // Pass through non-vector operands.
6153     if (!V.getValueType().isVector()) {
6154       Ops.push_back(V);
6155       continue;
6156     }
6157 
6158     // "cast" fixed length vector to a scalable vector.
6159     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6160            "Only fixed length vectors are supported!");
6161     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6162   }
6163 
6164   SDLoc DL(Op);
6165   SDValue Mask, VL;
6166   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6167   if (HasMask)
6168     Ops.push_back(Mask);
6169   Ops.push_back(VL);
6170 
6171   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6172   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6173 }
6174 
6175 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6176 // * Operands of each node are assumed to be in the same order.
6177 // * The EVL operand is promoted from i32 to i64 on RV64.
6178 // * Fixed-length vectors are converted to their scalable-vector container
6179 //   types.
6180 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6181                                        unsigned RISCVISDOpc) const {
6182   SDLoc DL(Op);
6183   MVT VT = Op.getSimpleValueType();
6184   SmallVector<SDValue, 4> Ops;
6185 
6186   for (const auto &OpIdx : enumerate(Op->ops())) {
6187     SDValue V = OpIdx.value();
6188     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6189     // Pass through operands which aren't fixed-length vectors.
6190     if (!V.getValueType().isFixedLengthVector()) {
6191       Ops.push_back(V);
6192       continue;
6193     }
6194     // "cast" fixed length vector to a scalable vector.
6195     MVT OpVT = V.getSimpleValueType();
6196     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6197     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6198            "Only fixed length vectors are supported!");
6199     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6200   }
6201 
6202   if (!VT.isFixedLengthVector())
6203     return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags());
6204 
6205   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6206 
6207   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags());
6208 
6209   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6210 }
6211 
6212 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op,
6213                                               SelectionDAG &DAG) const {
6214   SDLoc DL(Op);
6215   MVT VT = Op.getSimpleValueType();
6216 
6217   SDValue Src = Op.getOperand(0);
6218   // NOTE: Mask is dropped.
6219   SDValue VL = Op.getOperand(2);
6220 
6221   MVT ContainerVT = VT;
6222   if (VT.isFixedLengthVector()) {
6223     ContainerVT = getContainerForFixedLengthVector(VT);
6224     MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6225     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6226   }
6227 
6228   MVT XLenVT = Subtarget.getXLenVT();
6229   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6230   SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6231                                   DAG.getUNDEF(ContainerVT), Zero, VL);
6232 
6233   SDValue SplatValue = DAG.getConstant(
6234       Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT);
6235   SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6236                               DAG.getUNDEF(ContainerVT), SplatValue, VL);
6237 
6238   SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src,
6239                                Splat, ZeroSplat, VL);
6240   if (!VT.isFixedLengthVector())
6241     return Result;
6242   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6243 }
6244 
6245 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op,
6246                                                 SelectionDAG &DAG) const {
6247   SDLoc DL(Op);
6248   MVT VT = Op.getSimpleValueType();
6249 
6250   SDValue Op1 = Op.getOperand(0);
6251   SDValue Op2 = Op.getOperand(1);
6252   ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6253   // NOTE: Mask is dropped.
6254   SDValue VL = Op.getOperand(4);
6255 
6256   MVT ContainerVT = VT;
6257   if (VT.isFixedLengthVector()) {
6258     ContainerVT = getContainerForFixedLengthVector(VT);
6259     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6260     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6261   }
6262 
6263   SDValue Result;
6264   SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
6265 
6266   switch (Condition) {
6267   default:
6268     break;
6269   // X != Y  --> (X^Y)
6270   case ISD::SETNE:
6271     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6272     break;
6273   // X == Y  --> ~(X^Y)
6274   case ISD::SETEQ: {
6275     SDValue Temp =
6276         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6277     Result =
6278         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL);
6279     break;
6280   }
6281   // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
6282   // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
6283   case ISD::SETGT:
6284   case ISD::SETULT: {
6285     SDValue Temp =
6286         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6287     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL);
6288     break;
6289   }
6290   // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
6291   // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
6292   case ISD::SETLT:
6293   case ISD::SETUGT: {
6294     SDValue Temp =
6295         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6296     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL);
6297     break;
6298   }
6299   // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
6300   // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
6301   case ISD::SETGE:
6302   case ISD::SETULE: {
6303     SDValue Temp =
6304         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6305     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL);
6306     break;
6307   }
6308   // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
6309   // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
6310   case ISD::SETLE:
6311   case ISD::SETUGE: {
6312     SDValue Temp =
6313         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6314     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL);
6315     break;
6316   }
6317   }
6318 
6319   if (!VT.isFixedLengthVector())
6320     return Result;
6321   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6322 }
6323 
6324 // Lower Floating-Point/Integer Type-Convert VP SDNodes
6325 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
6326                                                 unsigned RISCVISDOpc) const {
6327   SDLoc DL(Op);
6328 
6329   SDValue Src = Op.getOperand(0);
6330   SDValue Mask = Op.getOperand(1);
6331   SDValue VL = Op.getOperand(2);
6332 
6333   MVT DstVT = Op.getSimpleValueType();
6334   MVT SrcVT = Src.getSimpleValueType();
6335   if (DstVT.isFixedLengthVector()) {
6336     DstVT = getContainerForFixedLengthVector(DstVT);
6337     SrcVT = getContainerForFixedLengthVector(SrcVT);
6338     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6339     MVT MaskVT = getMaskTypeFor(DstVT);
6340     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6341   }
6342 
6343   unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL ||
6344                              RISCVISDOpc == RISCVISD::FP_TO_SINT_VL)
6345                                 ? RISCVISD::VSEXT_VL
6346                                 : RISCVISD::VZEXT_VL;
6347 
6348   unsigned DstEltSize = DstVT.getScalarSizeInBits();
6349   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
6350 
6351   SDValue Result;
6352   if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
6353     if (SrcVT.isInteger()) {
6354       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6355 
6356       // Do we need to do any pre-widening before converting?
6357       if (SrcEltSize == 1) {
6358         MVT IntVT = DstVT.changeVectorElementTypeToInteger();
6359         MVT XLenVT = Subtarget.getXLenVT();
6360         SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6361         SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6362                                         DAG.getUNDEF(IntVT), Zero, VL);
6363         SDValue One = DAG.getConstant(
6364             RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
6365         SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6366                                        DAG.getUNDEF(IntVT), One, VL);
6367         Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
6368                           ZeroSplat, VL);
6369       } else if (DstEltSize > (2 * SrcEltSize)) {
6370         // Widen before converting.
6371         MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
6372                                      DstVT.getVectorElementCount());
6373         Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL);
6374       }
6375 
6376       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6377     } else {
6378       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6379              "Wrong input/output vector types");
6380 
6381       // Convert f16 to f32 then convert f32 to i64.
6382       if (DstEltSize > (2 * SrcEltSize)) {
6383         assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6384         MVT InterimFVT =
6385             MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6386         Src =
6387             DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL);
6388       }
6389 
6390       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6391     }
6392   } else { // Narrowing + Conversion
6393     if (SrcVT.isInteger()) {
6394       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6395       // First do a narrowing convert to an FP type half the size, then round
6396       // the FP type to a small FP type if needed.
6397 
6398       MVT InterimFVT = DstVT;
6399       if (SrcEltSize > (2 * DstEltSize)) {
6400         assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
6401         assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6402         InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6403       }
6404 
6405       Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL);
6406 
6407       if (InterimFVT != DstVT) {
6408         Src = Result;
6409         Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL);
6410       }
6411     } else {
6412       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6413              "Wrong input/output vector types");
6414       // First do a narrowing conversion to an integer half the size, then
6415       // truncate if needed.
6416 
6417       if (DstEltSize == 1) {
6418         // First convert to the same size integer, then convert to mask using
6419         // setcc.
6420         assert(SrcEltSize >= 16 && "Unexpected FP type!");
6421         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize),
6422                                           DstVT.getVectorElementCount());
6423         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6424 
6425         // Compare the integer result to 0. The integer should be 0 or 1/-1,
6426         // otherwise the conversion was undefined.
6427         MVT XLenVT = Subtarget.getXLenVT();
6428         SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
6429         SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT,
6430                                 DAG.getUNDEF(InterimIVT), SplatZero);
6431         Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero,
6432                              DAG.getCondCode(ISD::SETNE), Mask, VL);
6433       } else {
6434         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6435                                           DstVT.getVectorElementCount());
6436 
6437         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6438 
6439         while (InterimIVT != DstVT) {
6440           SrcEltSize /= 2;
6441           Src = Result;
6442           InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6443                                         DstVT.getVectorElementCount());
6444           Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
6445                                Src, Mask, VL);
6446         }
6447       }
6448     }
6449   }
6450 
6451   MVT VT = Op.getSimpleValueType();
6452   if (!VT.isFixedLengthVector())
6453     return Result;
6454   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6455 }
6456 
6457 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6458                                             unsigned MaskOpc,
6459                                             unsigned VecOpc) const {
6460   MVT VT = Op.getSimpleValueType();
6461   if (VT.getVectorElementType() != MVT::i1)
6462     return lowerVPOp(Op, DAG, VecOpc);
6463 
6464   // It is safe to drop mask parameter as masked-off elements are undef.
6465   SDValue Op1 = Op->getOperand(0);
6466   SDValue Op2 = Op->getOperand(1);
6467   SDValue VL = Op->getOperand(3);
6468 
6469   MVT ContainerVT = VT;
6470   const bool IsFixed = VT.isFixedLengthVector();
6471   if (IsFixed) {
6472     ContainerVT = getContainerForFixedLengthVector(VT);
6473     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6474     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6475   }
6476 
6477   SDLoc DL(Op);
6478   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6479   if (!IsFixed)
6480     return Val;
6481   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6482 }
6483 
6484 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6485 // matched to a RVV indexed load. The RVV indexed load instructions only
6486 // support the "unsigned unscaled" addressing mode; indices are implicitly
6487 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6488 // signed or scaled indexing is extended to the XLEN value type and scaled
6489 // accordingly.
6490 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6491                                                SelectionDAG &DAG) const {
6492   SDLoc DL(Op);
6493   MVT VT = Op.getSimpleValueType();
6494 
6495   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6496   EVT MemVT = MemSD->getMemoryVT();
6497   MachineMemOperand *MMO = MemSD->getMemOperand();
6498   SDValue Chain = MemSD->getChain();
6499   SDValue BasePtr = MemSD->getBasePtr();
6500 
6501   ISD::LoadExtType LoadExtType;
6502   SDValue Index, Mask, PassThru, VL;
6503 
6504   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6505     Index = VPGN->getIndex();
6506     Mask = VPGN->getMask();
6507     PassThru = DAG.getUNDEF(VT);
6508     VL = VPGN->getVectorLength();
6509     // VP doesn't support extending loads.
6510     LoadExtType = ISD::NON_EXTLOAD;
6511   } else {
6512     // Else it must be a MGATHER.
6513     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6514     Index = MGN->getIndex();
6515     Mask = MGN->getMask();
6516     PassThru = MGN->getPassThru();
6517     LoadExtType = MGN->getExtensionType();
6518   }
6519 
6520   MVT IndexVT = Index.getSimpleValueType();
6521   MVT XLenVT = Subtarget.getXLenVT();
6522 
6523   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6524          "Unexpected VTs!");
6525   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6526   // Targets have to explicitly opt-in for extending vector loads.
6527   assert(LoadExtType == ISD::NON_EXTLOAD &&
6528          "Unexpected extending MGATHER/VP_GATHER");
6529   (void)LoadExtType;
6530 
6531   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6532   // the selection of the masked intrinsics doesn't do this for us.
6533   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6534 
6535   MVT ContainerVT = VT;
6536   if (VT.isFixedLengthVector()) {
6537     ContainerVT = getContainerForFixedLengthVector(VT);
6538     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6539                                ContainerVT.getVectorElementCount());
6540 
6541     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6542 
6543     if (!IsUnmasked) {
6544       MVT MaskVT = getMaskTypeFor(ContainerVT);
6545       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6546       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6547     }
6548   }
6549 
6550   if (!VL)
6551     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6552 
6553   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6554     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6555     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6556                                    VL);
6557     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6558                         TrueMask, VL);
6559   }
6560 
6561   unsigned IntID =
6562       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6563   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6564   if (IsUnmasked)
6565     Ops.push_back(DAG.getUNDEF(ContainerVT));
6566   else
6567     Ops.push_back(PassThru);
6568   Ops.push_back(BasePtr);
6569   Ops.push_back(Index);
6570   if (!IsUnmasked)
6571     Ops.push_back(Mask);
6572   Ops.push_back(VL);
6573   if (!IsUnmasked)
6574     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6575 
6576   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6577   SDValue Result =
6578       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6579   Chain = Result.getValue(1);
6580 
6581   if (VT.isFixedLengthVector())
6582     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6583 
6584   return DAG.getMergeValues({Result, Chain}, DL);
6585 }
6586 
6587 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6588 // matched to a RVV indexed store. The RVV indexed store instructions only
6589 // support the "unsigned unscaled" addressing mode; indices are implicitly
6590 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6591 // signed or scaled indexing is extended to the XLEN value type and scaled
6592 // accordingly.
6593 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6594                                                 SelectionDAG &DAG) const {
6595   SDLoc DL(Op);
6596   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6597   EVT MemVT = MemSD->getMemoryVT();
6598   MachineMemOperand *MMO = MemSD->getMemOperand();
6599   SDValue Chain = MemSD->getChain();
6600   SDValue BasePtr = MemSD->getBasePtr();
6601 
6602   bool IsTruncatingStore = false;
6603   SDValue Index, Mask, Val, VL;
6604 
6605   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6606     Index = VPSN->getIndex();
6607     Mask = VPSN->getMask();
6608     Val = VPSN->getValue();
6609     VL = VPSN->getVectorLength();
6610     // VP doesn't support truncating stores.
6611     IsTruncatingStore = false;
6612   } else {
6613     // Else it must be a MSCATTER.
6614     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6615     Index = MSN->getIndex();
6616     Mask = MSN->getMask();
6617     Val = MSN->getValue();
6618     IsTruncatingStore = MSN->isTruncatingStore();
6619   }
6620 
6621   MVT VT = Val.getSimpleValueType();
6622   MVT IndexVT = Index.getSimpleValueType();
6623   MVT XLenVT = Subtarget.getXLenVT();
6624 
6625   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6626          "Unexpected VTs!");
6627   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6628   // Targets have to explicitly opt-in for extending vector loads and
6629   // truncating vector stores.
6630   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6631   (void)IsTruncatingStore;
6632 
6633   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6634   // the selection of the masked intrinsics doesn't do this for us.
6635   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6636 
6637   MVT ContainerVT = VT;
6638   if (VT.isFixedLengthVector()) {
6639     ContainerVT = getContainerForFixedLengthVector(VT);
6640     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6641                                ContainerVT.getVectorElementCount());
6642 
6643     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6644     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6645 
6646     if (!IsUnmasked) {
6647       MVT MaskVT = getMaskTypeFor(ContainerVT);
6648       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6649     }
6650   }
6651 
6652   if (!VL)
6653     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6654 
6655   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6656     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6657     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6658                                    VL);
6659     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6660                         TrueMask, VL);
6661   }
6662 
6663   unsigned IntID =
6664       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6665   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6666   Ops.push_back(Val);
6667   Ops.push_back(BasePtr);
6668   Ops.push_back(Index);
6669   if (!IsUnmasked)
6670     Ops.push_back(Mask);
6671   Ops.push_back(VL);
6672 
6673   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6674                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6675 }
6676 
6677 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6678                                                SelectionDAG &DAG) const {
6679   const MVT XLenVT = Subtarget.getXLenVT();
6680   SDLoc DL(Op);
6681   SDValue Chain = Op->getOperand(0);
6682   SDValue SysRegNo = DAG.getTargetConstant(
6683       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6684   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6685   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6686 
6687   // Encoding used for rounding mode in RISCV differs from that used in
6688   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6689   // table, which consists of a sequence of 4-bit fields, each representing
6690   // corresponding FLT_ROUNDS mode.
6691   static const int Table =
6692       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6693       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6694       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6695       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6696       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6697 
6698   SDValue Shift =
6699       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6700   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6701                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6702   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6703                                DAG.getConstant(7, DL, XLenVT));
6704 
6705   return DAG.getMergeValues({Masked, Chain}, DL);
6706 }
6707 
6708 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6709                                                SelectionDAG &DAG) const {
6710   const MVT XLenVT = Subtarget.getXLenVT();
6711   SDLoc DL(Op);
6712   SDValue Chain = Op->getOperand(0);
6713   SDValue RMValue = Op->getOperand(1);
6714   SDValue SysRegNo = DAG.getTargetConstant(
6715       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6716 
6717   // Encoding used for rounding mode in RISCV differs from that used in
6718   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6719   // a table, which consists of a sequence of 4-bit fields, each representing
6720   // corresponding RISCV mode.
6721   static const unsigned Table =
6722       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6723       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6724       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6725       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6726       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6727 
6728   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6729                               DAG.getConstant(2, DL, XLenVT));
6730   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6731                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6732   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6733                         DAG.getConstant(0x7, DL, XLenVT));
6734   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6735                      RMValue);
6736 }
6737 
6738 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
6739                                                SelectionDAG &DAG) const {
6740   MachineFunction &MF = DAG.getMachineFunction();
6741 
6742   bool isRISCV64 = Subtarget.is64Bit();
6743   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6744 
6745   int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false);
6746   return DAG.getFrameIndex(FI, PtrVT);
6747 }
6748 
6749 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6750   switch (IntNo) {
6751   default:
6752     llvm_unreachable("Unexpected Intrinsic");
6753   case Intrinsic::riscv_bcompress:
6754     return RISCVISD::BCOMPRESSW;
6755   case Intrinsic::riscv_bdecompress:
6756     return RISCVISD::BDECOMPRESSW;
6757   case Intrinsic::riscv_bfp:
6758     return RISCVISD::BFPW;
6759   case Intrinsic::riscv_fsl:
6760     return RISCVISD::FSLW;
6761   case Intrinsic::riscv_fsr:
6762     return RISCVISD::FSRW;
6763   }
6764 }
6765 
6766 // Converts the given intrinsic to a i64 operation with any extension.
6767 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6768                                          unsigned IntNo) {
6769   SDLoc DL(N);
6770   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6771   // Deal with the Instruction Operands
6772   SmallVector<SDValue, 3> NewOps;
6773   for (SDValue Op : drop_begin(N->ops()))
6774     // Promote the operand to i64 type
6775     NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op));
6776   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps);
6777   // ReplaceNodeResults requires we maintain the same type for the return value.
6778   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6779 }
6780 
6781 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6782 // form of the given Opcode.
6783 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6784   switch (Opcode) {
6785   default:
6786     llvm_unreachable("Unexpected opcode");
6787   case ISD::SHL:
6788     return RISCVISD::SLLW;
6789   case ISD::SRA:
6790     return RISCVISD::SRAW;
6791   case ISD::SRL:
6792     return RISCVISD::SRLW;
6793   case ISD::SDIV:
6794     return RISCVISD::DIVW;
6795   case ISD::UDIV:
6796     return RISCVISD::DIVUW;
6797   case ISD::UREM:
6798     return RISCVISD::REMUW;
6799   case ISD::ROTL:
6800     return RISCVISD::ROLW;
6801   case ISD::ROTR:
6802     return RISCVISD::RORW;
6803   }
6804 }
6805 
6806 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6807 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6808 // otherwise be promoted to i64, making it difficult to select the
6809 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6810 // type i8/i16/i32 is lost.
6811 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6812                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6813   SDLoc DL(N);
6814   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6815   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6816   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6817   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6818   // ReplaceNodeResults requires we maintain the same type for the return value.
6819   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6820 }
6821 
6822 // Converts the given 32-bit operation to a i64 operation with signed extension
6823 // semantic to reduce the signed extension instructions.
6824 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6825   SDLoc DL(N);
6826   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6827   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6828   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6829   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6830                                DAG.getValueType(MVT::i32));
6831   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6832 }
6833 
6834 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6835                                              SmallVectorImpl<SDValue> &Results,
6836                                              SelectionDAG &DAG) const {
6837   SDLoc DL(N);
6838   switch (N->getOpcode()) {
6839   default:
6840     llvm_unreachable("Don't know how to custom type legalize this operation!");
6841   case ISD::STRICT_FP_TO_SINT:
6842   case ISD::STRICT_FP_TO_UINT:
6843   case ISD::FP_TO_SINT:
6844   case ISD::FP_TO_UINT: {
6845     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6846            "Unexpected custom legalisation");
6847     bool IsStrict = N->isStrictFPOpcode();
6848     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6849                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6850     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6851     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6852         TargetLowering::TypeSoftenFloat) {
6853       if (!isTypeLegal(Op0.getValueType()))
6854         return;
6855       if (IsStrict) {
6856         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6857                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6858         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6859         SDValue Res = DAG.getNode(
6860             Opc, DL, VTs, N->getOperand(0), Op0,
6861             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6862         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6863         Results.push_back(Res.getValue(1));
6864         return;
6865       }
6866       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6867       SDValue Res =
6868           DAG.getNode(Opc, DL, MVT::i64, Op0,
6869                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6870       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6871       return;
6872     }
6873     // If the FP type needs to be softened, emit a library call using the 'si'
6874     // version. If we left it to default legalization we'd end up with 'di'. If
6875     // the FP type doesn't need to be softened just let generic type
6876     // legalization promote the result type.
6877     RTLIB::Libcall LC;
6878     if (IsSigned)
6879       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6880     else
6881       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6882     MakeLibCallOptions CallOptions;
6883     EVT OpVT = Op0.getValueType();
6884     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6885     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6886     SDValue Result;
6887     std::tie(Result, Chain) =
6888         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6889     Results.push_back(Result);
6890     if (IsStrict)
6891       Results.push_back(Chain);
6892     break;
6893   }
6894   case ISD::READCYCLECOUNTER: {
6895     assert(!Subtarget.is64Bit() &&
6896            "READCYCLECOUNTER only has custom type legalization on riscv32");
6897 
6898     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6899     SDValue RCW =
6900         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6901 
6902     Results.push_back(
6903         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6904     Results.push_back(RCW.getValue(2));
6905     break;
6906   }
6907   case ISD::MUL: {
6908     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6909     unsigned XLen = Subtarget.getXLen();
6910     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6911     if (Size > XLen) {
6912       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6913       SDValue LHS = N->getOperand(0);
6914       SDValue RHS = N->getOperand(1);
6915       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6916 
6917       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6918       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6919       // We need exactly one side to be unsigned.
6920       if (LHSIsU == RHSIsU)
6921         return;
6922 
6923       auto MakeMULPair = [&](SDValue S, SDValue U) {
6924         MVT XLenVT = Subtarget.getXLenVT();
6925         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6926         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6927         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6928         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6929         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6930       };
6931 
6932       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6933       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6934 
6935       // The other operand should be signed, but still prefer MULH when
6936       // possible.
6937       if (RHSIsU && LHSIsS && !RHSIsS)
6938         Results.push_back(MakeMULPair(LHS, RHS));
6939       else if (LHSIsU && RHSIsS && !LHSIsS)
6940         Results.push_back(MakeMULPair(RHS, LHS));
6941 
6942       return;
6943     }
6944     LLVM_FALLTHROUGH;
6945   }
6946   case ISD::ADD:
6947   case ISD::SUB:
6948     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6949            "Unexpected custom legalisation");
6950     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6951     break;
6952   case ISD::SHL:
6953   case ISD::SRA:
6954   case ISD::SRL:
6955     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6956            "Unexpected custom legalisation");
6957     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6958       // If we can use a BSET instruction, allow default promotion to apply.
6959       if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() &&
6960           isOneConstant(N->getOperand(0)))
6961         break;
6962       Results.push_back(customLegalizeToWOp(N, DAG));
6963       break;
6964     }
6965 
6966     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6967     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6968     // shift amount.
6969     if (N->getOpcode() == ISD::SHL) {
6970       SDLoc DL(N);
6971       SDValue NewOp0 =
6972           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6973       SDValue NewOp1 =
6974           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6975       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6976       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6977                                    DAG.getValueType(MVT::i32));
6978       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6979     }
6980 
6981     break;
6982   case ISD::ROTL:
6983   case ISD::ROTR:
6984     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6985            "Unexpected custom legalisation");
6986     Results.push_back(customLegalizeToWOp(N, DAG));
6987     break;
6988   case ISD::CTTZ:
6989   case ISD::CTTZ_ZERO_UNDEF:
6990   case ISD::CTLZ:
6991   case ISD::CTLZ_ZERO_UNDEF: {
6992     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6993            "Unexpected custom legalisation");
6994 
6995     SDValue NewOp0 =
6996         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6997     bool IsCTZ =
6998         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6999     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
7000     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
7001     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7002     return;
7003   }
7004   case ISD::SDIV:
7005   case ISD::UDIV:
7006   case ISD::UREM: {
7007     MVT VT = N->getSimpleValueType(0);
7008     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
7009            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
7010            "Unexpected custom legalisation");
7011     // Don't promote division/remainder by constant since we should expand those
7012     // to multiply by magic constant.
7013     // FIXME: What if the expansion is disabled for minsize.
7014     if (N->getOperand(1).getOpcode() == ISD::Constant)
7015       return;
7016 
7017     // If the input is i32, use ANY_EXTEND since the W instructions don't read
7018     // the upper 32 bits. For other types we need to sign or zero extend
7019     // based on the opcode.
7020     unsigned ExtOpc = ISD::ANY_EXTEND;
7021     if (VT != MVT::i32)
7022       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
7023                                            : ISD::ZERO_EXTEND;
7024 
7025     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
7026     break;
7027   }
7028   case ISD::UADDO:
7029   case ISD::USUBO: {
7030     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7031            "Unexpected custom legalisation");
7032     bool IsAdd = N->getOpcode() == ISD::UADDO;
7033     // Create an ADDW or SUBW.
7034     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7035     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7036     SDValue Res =
7037         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
7038     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
7039                       DAG.getValueType(MVT::i32));
7040 
7041     SDValue Overflow;
7042     if (IsAdd && isOneConstant(RHS)) {
7043       // Special case uaddo X, 1 overflowed if the addition result is 0.
7044       // The general case (X + C) < C is not necessarily beneficial. Although we
7045       // reduce the live range of X, we may introduce the materialization of
7046       // constant C, especially when the setcc result is used by branch. We have
7047       // no compare with constant and branch instructions.
7048       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res,
7049                               DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ);
7050     } else {
7051       // Sign extend the LHS and perform an unsigned compare with the ADDW
7052       // result. Since the inputs are sign extended from i32, this is equivalent
7053       // to comparing the lower 32 bits.
7054       LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
7055       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
7056                               IsAdd ? ISD::SETULT : ISD::SETUGT);
7057     }
7058 
7059     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7060     Results.push_back(Overflow);
7061     return;
7062   }
7063   case ISD::UADDSAT:
7064   case ISD::USUBSAT: {
7065     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7066            "Unexpected custom legalisation");
7067     if (Subtarget.hasStdExtZbb()) {
7068       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
7069       // sign extend allows overflow of the lower 32 bits to be detected on
7070       // the promoted size.
7071       SDValue LHS =
7072           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
7073       SDValue RHS =
7074           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
7075       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
7076       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7077       return;
7078     }
7079 
7080     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
7081     // promotion for UADDO/USUBO.
7082     Results.push_back(expandAddSubSat(N, DAG));
7083     return;
7084   }
7085   case ISD::ABS: {
7086     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7087            "Unexpected custom legalisation");
7088 
7089     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
7090 
7091     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7092 
7093     // Freeze the source so we can increase it's use count.
7094     Src = DAG.getFreeze(Src);
7095 
7096     // Copy sign bit to all bits using the sraiw pattern.
7097     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
7098                                    DAG.getValueType(MVT::i32));
7099     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
7100                            DAG.getConstant(31, DL, MVT::i64));
7101 
7102     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
7103     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
7104 
7105     // NOTE: The result is only required to be anyextended, but sext is
7106     // consistent with type legalization of sub.
7107     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
7108                          DAG.getValueType(MVT::i32));
7109     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
7110     return;
7111   }
7112   case ISD::BITCAST: {
7113     EVT VT = N->getValueType(0);
7114     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
7115     SDValue Op0 = N->getOperand(0);
7116     EVT Op0VT = Op0.getValueType();
7117     MVT XLenVT = Subtarget.getXLenVT();
7118     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
7119       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
7120       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
7121     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
7122                Subtarget.hasStdExtF()) {
7123       SDValue FPConv =
7124           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
7125       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
7126     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
7127                isTypeLegal(Op0VT)) {
7128       // Custom-legalize bitcasts from fixed-length vector types to illegal
7129       // scalar types in order to improve codegen. Bitcast the vector to a
7130       // one-element vector type whose element type is the same as the result
7131       // type, and extract the first element.
7132       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
7133       if (isTypeLegal(BVT)) {
7134         SDValue BVec = DAG.getBitcast(BVT, Op0);
7135         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
7136                                       DAG.getConstant(0, DL, XLenVT)));
7137       }
7138     }
7139     break;
7140   }
7141   case RISCVISD::GREV:
7142   case RISCVISD::GORC:
7143   case RISCVISD::SHFL: {
7144     MVT VT = N->getSimpleValueType(0);
7145     MVT XLenVT = Subtarget.getXLenVT();
7146     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
7147            "Unexpected custom legalisation");
7148     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
7149     assert((Subtarget.hasStdExtZbp() ||
7150             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
7151              N->getConstantOperandVal(1) == 7)) &&
7152            "Unexpected extension");
7153     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7154     SDValue NewOp1 =
7155         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
7156     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
7157     // ReplaceNodeResults requires we maintain the same type for the return
7158     // value.
7159     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
7160     break;
7161   }
7162   case ISD::BSWAP:
7163   case ISD::BITREVERSE: {
7164     MVT VT = N->getSimpleValueType(0);
7165     MVT XLenVT = Subtarget.getXLenVT();
7166     assert((VT == MVT::i8 || VT == MVT::i16 ||
7167             (VT == MVT::i32 && Subtarget.is64Bit())) &&
7168            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
7169     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7170     unsigned Imm = VT.getSizeInBits() - 1;
7171     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
7172     if (N->getOpcode() == ISD::BSWAP)
7173       Imm &= ~0x7U;
7174     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
7175                                 DAG.getConstant(Imm, DL, XLenVT));
7176     // ReplaceNodeResults requires we maintain the same type for the return
7177     // value.
7178     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
7179     break;
7180   }
7181   case ISD::FSHL:
7182   case ISD::FSHR: {
7183     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7184            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
7185     SDValue NewOp0 =
7186         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7187     SDValue NewOp1 =
7188         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7189     SDValue NewShAmt =
7190         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7191     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
7192     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
7193     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
7194                            DAG.getConstant(0x1f, DL, MVT::i64));
7195     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
7196     // instruction use different orders. fshl will return its first operand for
7197     // shift of zero, fshr will return its second operand. fsl and fsr both
7198     // return rs1 so the ISD nodes need to have different operand orders.
7199     // Shift amount is in rs2.
7200     unsigned Opc = RISCVISD::FSLW;
7201     if (N->getOpcode() == ISD::FSHR) {
7202       std::swap(NewOp0, NewOp1);
7203       Opc = RISCVISD::FSRW;
7204     }
7205     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
7206     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
7207     break;
7208   }
7209   case ISD::EXTRACT_VECTOR_ELT: {
7210     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
7211     // type is illegal (currently only vXi64 RV32).
7212     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
7213     // transferred to the destination register. We issue two of these from the
7214     // upper- and lower- halves of the SEW-bit vector element, slid down to the
7215     // first element.
7216     SDValue Vec = N->getOperand(0);
7217     SDValue Idx = N->getOperand(1);
7218 
7219     // The vector type hasn't been legalized yet so we can't issue target
7220     // specific nodes if it needs legalization.
7221     // FIXME: We would manually legalize if it's important.
7222     if (!isTypeLegal(Vec.getValueType()))
7223       return;
7224 
7225     MVT VecVT = Vec.getSimpleValueType();
7226 
7227     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7228            VecVT.getVectorElementType() == MVT::i64 &&
7229            "Unexpected EXTRACT_VECTOR_ELT legalization");
7230 
7231     // If this is a fixed vector, we need to convert it to a scalable vector.
7232     MVT ContainerVT = VecVT;
7233     if (VecVT.isFixedLengthVector()) {
7234       ContainerVT = getContainerForFixedLengthVector(VecVT);
7235       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7236     }
7237 
7238     MVT XLenVT = Subtarget.getXLenVT();
7239 
7240     // Use a VL of 1 to avoid processing more elements than we need.
7241     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7242     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
7243 
7244     // Unless the index is known to be 0, we must slide the vector down to get
7245     // the desired element into index 0.
7246     if (!isNullConstant(Idx)) {
7247       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7248                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7249     }
7250 
7251     // Extract the lower XLEN bits of the correct vector element.
7252     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7253 
7254     // To extract the upper XLEN bits of the vector element, shift the first
7255     // element right by 32 bits and re-extract the lower XLEN bits.
7256     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7257                                      DAG.getUNDEF(ContainerVT),
7258                                      DAG.getConstant(32, DL, XLenVT), VL);
7259     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7260                                  ThirtyTwoV, Mask, VL);
7261 
7262     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7263 
7264     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7265     break;
7266   }
7267   case ISD::INTRINSIC_WO_CHAIN: {
7268     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7269     switch (IntNo) {
7270     default:
7271       llvm_unreachable(
7272           "Don't know how to custom type legalize this intrinsic!");
7273     case Intrinsic::riscv_grev:
7274     case Intrinsic::riscv_gorc: {
7275       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7276              "Unexpected custom legalisation");
7277       SDValue NewOp1 =
7278           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7279       SDValue NewOp2 =
7280           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7281       unsigned Opc =
7282           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7283       // If the control is a constant, promote the node by clearing any extra
7284       // bits bits in the control. isel will form greviw/gorciw if the result is
7285       // sign extended.
7286       if (isa<ConstantSDNode>(NewOp2)) {
7287         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7288                              DAG.getConstant(0x1f, DL, MVT::i64));
7289         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7290       }
7291       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7292       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7293       break;
7294     }
7295     case Intrinsic::riscv_bcompress:
7296     case Intrinsic::riscv_bdecompress:
7297     case Intrinsic::riscv_bfp:
7298     case Intrinsic::riscv_fsl:
7299     case Intrinsic::riscv_fsr: {
7300       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7301              "Unexpected custom legalisation");
7302       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7303       break;
7304     }
7305     case Intrinsic::riscv_orc_b: {
7306       // Lower to the GORCI encoding for orc.b with the operand extended.
7307       SDValue NewOp =
7308           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7309       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7310                                 DAG.getConstant(7, DL, MVT::i64));
7311       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7312       return;
7313     }
7314     case Intrinsic::riscv_shfl:
7315     case Intrinsic::riscv_unshfl: {
7316       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7317              "Unexpected custom legalisation");
7318       SDValue NewOp1 =
7319           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7320       SDValue NewOp2 =
7321           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7322       unsigned Opc =
7323           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7324       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7325       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7326       // will be shuffled the same way as the lower 32 bit half, but the two
7327       // halves won't cross.
7328       if (isa<ConstantSDNode>(NewOp2)) {
7329         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7330                              DAG.getConstant(0xf, DL, MVT::i64));
7331         Opc =
7332             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7333       }
7334       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7335       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7336       break;
7337     }
7338     case Intrinsic::riscv_vmv_x_s: {
7339       EVT VT = N->getValueType(0);
7340       MVT XLenVT = Subtarget.getXLenVT();
7341       if (VT.bitsLT(XLenVT)) {
7342         // Simple case just extract using vmv.x.s and truncate.
7343         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7344                                       Subtarget.getXLenVT(), N->getOperand(1));
7345         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7346         return;
7347       }
7348 
7349       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7350              "Unexpected custom legalization");
7351 
7352       // We need to do the move in two steps.
7353       SDValue Vec = N->getOperand(1);
7354       MVT VecVT = Vec.getSimpleValueType();
7355 
7356       // First extract the lower XLEN bits of the element.
7357       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7358 
7359       // To extract the upper XLEN bits of the vector element, shift the first
7360       // element right by 32 bits and re-extract the lower XLEN bits.
7361       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7362       SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG);
7363 
7364       SDValue ThirtyTwoV =
7365           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7366                       DAG.getConstant(32, DL, XLenVT), VL);
7367       SDValue LShr32 =
7368           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7369       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7370 
7371       Results.push_back(
7372           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7373       break;
7374     }
7375     }
7376     break;
7377   }
7378   case ISD::VECREDUCE_ADD:
7379   case ISD::VECREDUCE_AND:
7380   case ISD::VECREDUCE_OR:
7381   case ISD::VECREDUCE_XOR:
7382   case ISD::VECREDUCE_SMAX:
7383   case ISD::VECREDUCE_UMAX:
7384   case ISD::VECREDUCE_SMIN:
7385   case ISD::VECREDUCE_UMIN:
7386     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7387       Results.push_back(V);
7388     break;
7389   case ISD::VP_REDUCE_ADD:
7390   case ISD::VP_REDUCE_AND:
7391   case ISD::VP_REDUCE_OR:
7392   case ISD::VP_REDUCE_XOR:
7393   case ISD::VP_REDUCE_SMAX:
7394   case ISD::VP_REDUCE_UMAX:
7395   case ISD::VP_REDUCE_SMIN:
7396   case ISD::VP_REDUCE_UMIN:
7397     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7398       Results.push_back(V);
7399     break;
7400   case ISD::FLT_ROUNDS_: {
7401     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7402     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7403     Results.push_back(Res.getValue(0));
7404     Results.push_back(Res.getValue(1));
7405     break;
7406   }
7407   }
7408 }
7409 
7410 // A structure to hold one of the bit-manipulation patterns below. Together, a
7411 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7412 //   (or (and (shl x, 1), 0xAAAAAAAA),
7413 //       (and (srl x, 1), 0x55555555))
7414 struct RISCVBitmanipPat {
7415   SDValue Op;
7416   unsigned ShAmt;
7417   bool IsSHL;
7418 
7419   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7420     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7421   }
7422 };
7423 
7424 // Matches patterns of the form
7425 //   (and (shl x, C2), (C1 << C2))
7426 //   (and (srl x, C2), C1)
7427 //   (shl (and x, C1), C2)
7428 //   (srl (and x, (C1 << C2)), C2)
7429 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7430 // The expected masks for each shift amount are specified in BitmanipMasks where
7431 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7432 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7433 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7434 // XLen is 64.
7435 static Optional<RISCVBitmanipPat>
7436 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7437   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7438          "Unexpected number of masks");
7439   Optional<uint64_t> Mask;
7440   // Optionally consume a mask around the shift operation.
7441   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7442     Mask = Op.getConstantOperandVal(1);
7443     Op = Op.getOperand(0);
7444   }
7445   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7446     return None;
7447   bool IsSHL = Op.getOpcode() == ISD::SHL;
7448 
7449   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7450     return None;
7451   uint64_t ShAmt = Op.getConstantOperandVal(1);
7452 
7453   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7454   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7455     return None;
7456   // If we don't have enough masks for 64 bit, then we must be trying to
7457   // match SHFL so we're only allowed to shift 1/4 of the width.
7458   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7459     return None;
7460 
7461   SDValue Src = Op.getOperand(0);
7462 
7463   // The expected mask is shifted left when the AND is found around SHL
7464   // patterns.
7465   //   ((x >> 1) & 0x55555555)
7466   //   ((x << 1) & 0xAAAAAAAA)
7467   bool SHLExpMask = IsSHL;
7468 
7469   if (!Mask) {
7470     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7471     // the mask is all ones: consume that now.
7472     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7473       Mask = Src.getConstantOperandVal(1);
7474       Src = Src.getOperand(0);
7475       // The expected mask is now in fact shifted left for SRL, so reverse the
7476       // decision.
7477       //   ((x & 0xAAAAAAAA) >> 1)
7478       //   ((x & 0x55555555) << 1)
7479       SHLExpMask = !SHLExpMask;
7480     } else {
7481       // Use a default shifted mask of all-ones if there's no AND, truncated
7482       // down to the expected width. This simplifies the logic later on.
7483       Mask = maskTrailingOnes<uint64_t>(Width);
7484       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7485     }
7486   }
7487 
7488   unsigned MaskIdx = Log2_32(ShAmt);
7489   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7490 
7491   if (SHLExpMask)
7492     ExpMask <<= ShAmt;
7493 
7494   if (Mask != ExpMask)
7495     return None;
7496 
7497   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7498 }
7499 
7500 // Matches any of the following bit-manipulation patterns:
7501 //   (and (shl x, 1), (0x55555555 << 1))
7502 //   (and (srl x, 1), 0x55555555)
7503 //   (shl (and x, 0x55555555), 1)
7504 //   (srl (and x, (0x55555555 << 1)), 1)
7505 // where the shift amount and mask may vary thus:
7506 //   [1]  = 0x55555555 / 0xAAAAAAAA
7507 //   [2]  = 0x33333333 / 0xCCCCCCCC
7508 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7509 //   [8]  = 0x00FF00FF / 0xFF00FF00
7510 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7511 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7512 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7513   // These are the unshifted masks which we use to match bit-manipulation
7514   // patterns. They may be shifted left in certain circumstances.
7515   static const uint64_t BitmanipMasks[] = {
7516       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7517       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7518 
7519   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7520 }
7521 
7522 // Try to fold (<bop> x, (reduction.<bop> vec, start))
7523 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) {
7524   auto BinOpToRVVReduce = [](unsigned Opc) {
7525     switch (Opc) {
7526     default:
7527       llvm_unreachable("Unhandled binary to transfrom reduction");
7528     case ISD::ADD:
7529       return RISCVISD::VECREDUCE_ADD_VL;
7530     case ISD::UMAX:
7531       return RISCVISD::VECREDUCE_UMAX_VL;
7532     case ISD::SMAX:
7533       return RISCVISD::VECREDUCE_SMAX_VL;
7534     case ISD::UMIN:
7535       return RISCVISD::VECREDUCE_UMIN_VL;
7536     case ISD::SMIN:
7537       return RISCVISD::VECREDUCE_SMIN_VL;
7538     case ISD::AND:
7539       return RISCVISD::VECREDUCE_AND_VL;
7540     case ISD::OR:
7541       return RISCVISD::VECREDUCE_OR_VL;
7542     case ISD::XOR:
7543       return RISCVISD::VECREDUCE_XOR_VL;
7544     case ISD::FADD:
7545       return RISCVISD::VECREDUCE_FADD_VL;
7546     case ISD::FMAXNUM:
7547       return RISCVISD::VECREDUCE_FMAX_VL;
7548     case ISD::FMINNUM:
7549       return RISCVISD::VECREDUCE_FMIN_VL;
7550     }
7551   };
7552 
7553   auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) {
7554     return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7555            isNullConstant(V.getOperand(1)) &&
7556            V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc);
7557   };
7558 
7559   unsigned Opc = N->getOpcode();
7560   unsigned ReduceIdx;
7561   if (IsReduction(N->getOperand(0), Opc))
7562     ReduceIdx = 0;
7563   else if (IsReduction(N->getOperand(1), Opc))
7564     ReduceIdx = 1;
7565   else
7566     return SDValue();
7567 
7568   // Skip if FADD disallows reassociation but the combiner needs.
7569   if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation())
7570     return SDValue();
7571 
7572   SDValue Extract = N->getOperand(ReduceIdx);
7573   SDValue Reduce = Extract.getOperand(0);
7574   if (!Reduce.hasOneUse())
7575     return SDValue();
7576 
7577   SDValue ScalarV = Reduce.getOperand(2);
7578 
7579   // Make sure that ScalarV is a splat with VL=1.
7580   if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL &&
7581       ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL &&
7582       ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL)
7583     return SDValue();
7584 
7585   if (!isOneConstant(ScalarV.getOperand(2)))
7586     return SDValue();
7587 
7588   // TODO: Deal with value other than neutral element.
7589   auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) {
7590     if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() &&
7591         isNullFPConstant(V))
7592       return true;
7593     return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(),
7594                                  N->getFlags()) == V;
7595   };
7596 
7597   // Check the scalar of ScalarV is neutral element
7598   if (!IsRVVNeutralElement(N, ScalarV.getOperand(1)))
7599     return SDValue();
7600 
7601   if (!ScalarV.hasOneUse())
7602     return SDValue();
7603 
7604   EVT SplatVT = ScalarV.getValueType();
7605   SDValue NewStart = N->getOperand(1 - ReduceIdx);
7606   unsigned SplatOpc = RISCVISD::VFMV_S_F_VL;
7607   if (SplatVT.isInteger()) {
7608     auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode());
7609     if (!C || C->isZero() || !isInt<5>(C->getSExtValue()))
7610       SplatOpc = RISCVISD::VMV_S_X_VL;
7611     else
7612       SplatOpc = RISCVISD::VMV_V_X_VL;
7613   }
7614 
7615   SDValue NewScalarV =
7616       DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart,
7617                   ScalarV.getOperand(2));
7618   SDValue NewReduce =
7619       DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(),
7620                   Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV,
7621                   Reduce.getOperand(3), Reduce.getOperand(4));
7622   return DAG.getNode(Extract.getOpcode(), SDLoc(Extract),
7623                      Extract.getValueType(), NewReduce, Extract.getOperand(1));
7624 }
7625 
7626 // Match the following pattern as a GREVI(W) operation
7627 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7628 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7629                                const RISCVSubtarget &Subtarget) {
7630   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7631   EVT VT = Op.getValueType();
7632 
7633   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7634     auto LHS = matchGREVIPat(Op.getOperand(0));
7635     auto RHS = matchGREVIPat(Op.getOperand(1));
7636     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7637       SDLoc DL(Op);
7638       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7639                          DAG.getConstant(LHS->ShAmt, DL, VT));
7640     }
7641   }
7642   return SDValue();
7643 }
7644 
7645 // Matches any the following pattern as a GORCI(W) operation
7646 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7647 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7648 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7649 // Note that with the variant of 3.,
7650 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7651 // the inner pattern will first be matched as GREVI and then the outer
7652 // pattern will be matched to GORC via the first rule above.
7653 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7654 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7655                                const RISCVSubtarget &Subtarget) {
7656   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7657   EVT VT = Op.getValueType();
7658 
7659   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7660     SDLoc DL(Op);
7661     SDValue Op0 = Op.getOperand(0);
7662     SDValue Op1 = Op.getOperand(1);
7663 
7664     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7665       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7666           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7667           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7668         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7669       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7670       if ((Reverse.getOpcode() == ISD::ROTL ||
7671            Reverse.getOpcode() == ISD::ROTR) &&
7672           Reverse.getOperand(0) == X &&
7673           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7674         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7675         if (RotAmt == (VT.getSizeInBits() / 2))
7676           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7677                              DAG.getConstant(RotAmt, DL, VT));
7678       }
7679       return SDValue();
7680     };
7681 
7682     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7683     if (SDValue V = MatchOROfReverse(Op0, Op1))
7684       return V;
7685     if (SDValue V = MatchOROfReverse(Op1, Op0))
7686       return V;
7687 
7688     // OR is commutable so canonicalize its OR operand to the left
7689     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7690       std::swap(Op0, Op1);
7691     if (Op0.getOpcode() != ISD::OR)
7692       return SDValue();
7693     SDValue OrOp0 = Op0.getOperand(0);
7694     SDValue OrOp1 = Op0.getOperand(1);
7695     auto LHS = matchGREVIPat(OrOp0);
7696     // OR is commutable so swap the operands and try again: x might have been
7697     // on the left
7698     if (!LHS) {
7699       std::swap(OrOp0, OrOp1);
7700       LHS = matchGREVIPat(OrOp0);
7701     }
7702     auto RHS = matchGREVIPat(Op1);
7703     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7704       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7705                          DAG.getConstant(LHS->ShAmt, DL, VT));
7706     }
7707   }
7708   return SDValue();
7709 }
7710 
7711 // Matches any of the following bit-manipulation patterns:
7712 //   (and (shl x, 1), (0x22222222 << 1))
7713 //   (and (srl x, 1), 0x22222222)
7714 //   (shl (and x, 0x22222222), 1)
7715 //   (srl (and x, (0x22222222 << 1)), 1)
7716 // where the shift amount and mask may vary thus:
7717 //   [1]  = 0x22222222 / 0x44444444
7718 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7719 //   [4]  = 0x00F000F0 / 0x0F000F00
7720 //   [8]  = 0x0000FF00 / 0x00FF0000
7721 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7722 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7723   // These are the unshifted masks which we use to match bit-manipulation
7724   // patterns. They may be shifted left in certain circumstances.
7725   static const uint64_t BitmanipMasks[] = {
7726       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7727       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7728 
7729   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7730 }
7731 
7732 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7733 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7734                                const RISCVSubtarget &Subtarget) {
7735   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7736   EVT VT = Op.getValueType();
7737 
7738   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7739     return SDValue();
7740 
7741   SDValue Op0 = Op.getOperand(0);
7742   SDValue Op1 = Op.getOperand(1);
7743 
7744   // Or is commutable so canonicalize the second OR to the LHS.
7745   if (Op0.getOpcode() != ISD::OR)
7746     std::swap(Op0, Op1);
7747   if (Op0.getOpcode() != ISD::OR)
7748     return SDValue();
7749 
7750   // We found an inner OR, so our operands are the operands of the inner OR
7751   // and the other operand of the outer OR.
7752   SDValue A = Op0.getOperand(0);
7753   SDValue B = Op0.getOperand(1);
7754   SDValue C = Op1;
7755 
7756   auto Match1 = matchSHFLPat(A);
7757   auto Match2 = matchSHFLPat(B);
7758 
7759   // If neither matched, we failed.
7760   if (!Match1 && !Match2)
7761     return SDValue();
7762 
7763   // We had at least one match. if one failed, try the remaining C operand.
7764   if (!Match1) {
7765     std::swap(A, C);
7766     Match1 = matchSHFLPat(A);
7767     if (!Match1)
7768       return SDValue();
7769   } else if (!Match2) {
7770     std::swap(B, C);
7771     Match2 = matchSHFLPat(B);
7772     if (!Match2)
7773       return SDValue();
7774   }
7775   assert(Match1 && Match2);
7776 
7777   // Make sure our matches pair up.
7778   if (!Match1->formsPairWith(*Match2))
7779     return SDValue();
7780 
7781   // All the remains is to make sure C is an AND with the same input, that masks
7782   // out the bits that are being shuffled.
7783   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7784       C.getOperand(0) != Match1->Op)
7785     return SDValue();
7786 
7787   uint64_t Mask = C.getConstantOperandVal(1);
7788 
7789   static const uint64_t BitmanipMasks[] = {
7790       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7791       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7792   };
7793 
7794   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7795   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7796   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7797 
7798   if (Mask != ExpMask)
7799     return SDValue();
7800 
7801   SDLoc DL(Op);
7802   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7803                      DAG.getConstant(Match1->ShAmt, DL, VT));
7804 }
7805 
7806 // Optimize (add (shl x, c0), (shl y, c1)) ->
7807 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7808 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7809                                   const RISCVSubtarget &Subtarget) {
7810   // Perform this optimization only in the zba extension.
7811   if (!Subtarget.hasStdExtZba())
7812     return SDValue();
7813 
7814   // Skip for vector types and larger types.
7815   EVT VT = N->getValueType(0);
7816   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7817     return SDValue();
7818 
7819   // The two operand nodes must be SHL and have no other use.
7820   SDValue N0 = N->getOperand(0);
7821   SDValue N1 = N->getOperand(1);
7822   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7823       !N0->hasOneUse() || !N1->hasOneUse())
7824     return SDValue();
7825 
7826   // Check c0 and c1.
7827   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7828   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7829   if (!N0C || !N1C)
7830     return SDValue();
7831   int64_t C0 = N0C->getSExtValue();
7832   int64_t C1 = N1C->getSExtValue();
7833   if (C0 <= 0 || C1 <= 0)
7834     return SDValue();
7835 
7836   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7837   int64_t Bits = std::min(C0, C1);
7838   int64_t Diff = std::abs(C0 - C1);
7839   if (Diff != 1 && Diff != 2 && Diff != 3)
7840     return SDValue();
7841 
7842   // Build nodes.
7843   SDLoc DL(N);
7844   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7845   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7846   SDValue NA0 =
7847       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7848   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7849   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7850 }
7851 
7852 // Combine
7853 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7854 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7855 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7856 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7857 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7858 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7859 // The grev patterns represents BSWAP.
7860 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7861 // off the grev.
7862 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7863                                           const RISCVSubtarget &Subtarget) {
7864   bool IsWInstruction =
7865       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7866   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7867           IsWInstruction) &&
7868          "Unexpected opcode!");
7869   SDValue Src = N->getOperand(0);
7870   EVT VT = N->getValueType(0);
7871   SDLoc DL(N);
7872 
7873   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7874     return SDValue();
7875 
7876   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7877       !isa<ConstantSDNode>(Src.getOperand(1)))
7878     return SDValue();
7879 
7880   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7881   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7882 
7883   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7884   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7885   unsigned ShAmt1 = N->getConstantOperandVal(1);
7886   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7887   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7888     return SDValue();
7889 
7890   Src = Src.getOperand(0);
7891 
7892   // Toggle bit the MSB of the shift.
7893   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7894   if (CombinedShAmt == 0)
7895     return Src;
7896 
7897   SDValue Res = DAG.getNode(
7898       RISCVISD::GREV, DL, VT, Src,
7899       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7900   if (!IsWInstruction)
7901     return Res;
7902 
7903   // Sign extend the result to match the behavior of the rotate. This will be
7904   // selected to GREVIW in isel.
7905   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7906                      DAG.getValueType(MVT::i32));
7907 }
7908 
7909 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7910 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7911 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7912 // not undo itself, but they are redundant.
7913 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7914   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7915   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7916   SDValue Src = N->getOperand(0);
7917 
7918   if (Src.getOpcode() != N->getOpcode())
7919     return SDValue();
7920 
7921   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7922       !isa<ConstantSDNode>(Src.getOperand(1)))
7923     return SDValue();
7924 
7925   unsigned ShAmt1 = N->getConstantOperandVal(1);
7926   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7927   Src = Src.getOperand(0);
7928 
7929   unsigned CombinedShAmt;
7930   if (IsGORC)
7931     CombinedShAmt = ShAmt1 | ShAmt2;
7932   else
7933     CombinedShAmt = ShAmt1 ^ ShAmt2;
7934 
7935   if (CombinedShAmt == 0)
7936     return Src;
7937 
7938   SDLoc DL(N);
7939   return DAG.getNode(
7940       N->getOpcode(), DL, N->getValueType(0), Src,
7941       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7942 }
7943 
7944 // Combine a constant select operand into its use:
7945 //
7946 // (and (select cond, -1, c), x)
7947 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7948 // (or  (select cond, 0, c), x)
7949 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7950 // (xor (select cond, 0, c), x)
7951 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7952 // (add (select cond, 0, c), x)
7953 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7954 // (sub x, (select cond, 0, c))
7955 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7956 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7957                                    SelectionDAG &DAG, bool AllOnes) {
7958   EVT VT = N->getValueType(0);
7959 
7960   // Skip vectors.
7961   if (VT.isVector())
7962     return SDValue();
7963 
7964   if ((Slct.getOpcode() != ISD::SELECT &&
7965        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7966       !Slct.hasOneUse())
7967     return SDValue();
7968 
7969   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7970     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7971   };
7972 
7973   bool SwapSelectOps;
7974   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7975   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7976   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7977   SDValue NonConstantVal;
7978   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7979     SwapSelectOps = false;
7980     NonConstantVal = FalseVal;
7981   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7982     SwapSelectOps = true;
7983     NonConstantVal = TrueVal;
7984   } else
7985     return SDValue();
7986 
7987   // Slct is now know to be the desired identity constant when CC is true.
7988   TrueVal = OtherOp;
7989   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7990   // Unless SwapSelectOps says the condition should be false.
7991   if (SwapSelectOps)
7992     std::swap(TrueVal, FalseVal);
7993 
7994   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7995     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7996                        {Slct.getOperand(0), Slct.getOperand(1),
7997                         Slct.getOperand(2), TrueVal, FalseVal});
7998 
7999   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8000                      {Slct.getOperand(0), TrueVal, FalseVal});
8001 }
8002 
8003 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8004 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
8005                                               bool AllOnes) {
8006   SDValue N0 = N->getOperand(0);
8007   SDValue N1 = N->getOperand(1);
8008   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
8009     return Result;
8010   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
8011     return Result;
8012   return SDValue();
8013 }
8014 
8015 // Transform (add (mul x, c0), c1) ->
8016 //           (add (mul (add x, c1/c0), c0), c1%c0).
8017 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
8018 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
8019 // to an infinite loop in DAGCombine if transformed.
8020 // Or transform (add (mul x, c0), c1) ->
8021 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
8022 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
8023 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
8024 // lead to an infinite loop in DAGCombine if transformed.
8025 // Or transform (add (mul x, c0), c1) ->
8026 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
8027 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
8028 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
8029 // lead to an infinite loop in DAGCombine if transformed.
8030 // Or transform (add (mul x, c0), c1) ->
8031 //              (mul (add x, c1/c0), c0).
8032 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
8033 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
8034                                      const RISCVSubtarget &Subtarget) {
8035   // Skip for vector types and larger types.
8036   EVT VT = N->getValueType(0);
8037   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
8038     return SDValue();
8039   // The first operand node must be a MUL and has no other use.
8040   SDValue N0 = N->getOperand(0);
8041   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
8042     return SDValue();
8043   // Check if c0 and c1 match above conditions.
8044   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8045   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8046   if (!N0C || !N1C)
8047     return SDValue();
8048   // If N0C has multiple uses it's possible one of the cases in
8049   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
8050   // in an infinite loop.
8051   if (!N0C->hasOneUse())
8052     return SDValue();
8053   int64_t C0 = N0C->getSExtValue();
8054   int64_t C1 = N1C->getSExtValue();
8055   int64_t CA, CB;
8056   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
8057     return SDValue();
8058   // Search for proper CA (non-zero) and CB that both are simm12.
8059   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
8060       !isInt<12>(C0 * (C1 / C0))) {
8061     CA = C1 / C0;
8062     CB = C1 % C0;
8063   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
8064              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
8065     CA = C1 / C0 + 1;
8066     CB = C1 % C0 - C0;
8067   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
8068              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
8069     CA = C1 / C0 - 1;
8070     CB = C1 % C0 + C0;
8071   } else
8072     return SDValue();
8073   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
8074   SDLoc DL(N);
8075   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
8076                              DAG.getConstant(CA, DL, VT));
8077   SDValue New1 =
8078       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
8079   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
8080 }
8081 
8082 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
8083                                  const RISCVSubtarget &Subtarget) {
8084   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
8085     return V;
8086   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
8087     return V;
8088   if (SDValue V = combineBinOpToReduce(N, DAG))
8089     return V;
8090   // fold (add (select lhs, rhs, cc, 0, y), x) ->
8091   //      (select lhs, rhs, cc, x, (add x, y))
8092   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8093 }
8094 
8095 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
8096   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
8097   //      (select lhs, rhs, cc, x, (sub x, y))
8098   SDValue N0 = N->getOperand(0);
8099   SDValue N1 = N->getOperand(1);
8100   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
8101 }
8102 
8103 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
8104                                  const RISCVSubtarget &Subtarget) {
8105   SDValue N0 = N->getOperand(0);
8106   // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero
8107   // extending X. This is safe since we only need the LSB after the shift and
8108   // shift amounts larger than 31 would produce poison. If we wait until
8109   // type legalization, we'll create RISCVISD::SRLW and we can't recover it
8110   // to use a BEXT instruction.
8111   if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() &&
8112       N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) &&
8113       N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) &&
8114       N0.hasOneUse()) {
8115     SDLoc DL(N);
8116     SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0));
8117     SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1));
8118     SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1);
8119     SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl,
8120                               DAG.getConstant(1, DL, MVT::i64));
8121     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And);
8122   }
8123 
8124   if (SDValue V = combineBinOpToReduce(N, DAG))
8125     return V;
8126 
8127   // fold (and (select lhs, rhs, cc, -1, y), x) ->
8128   //      (select lhs, rhs, cc, x, (and x, y))
8129   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
8130 }
8131 
8132 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
8133                                 const RISCVSubtarget &Subtarget) {
8134   if (Subtarget.hasStdExtZbp()) {
8135     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
8136       return GREV;
8137     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
8138       return GORC;
8139     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
8140       return SHFL;
8141   }
8142 
8143   if (SDValue V = combineBinOpToReduce(N, DAG))
8144     return V;
8145   // fold (or (select cond, 0, y), x) ->
8146   //      (select cond, x, (or x, y))
8147   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8148 }
8149 
8150 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
8151   SDValue N0 = N->getOperand(0);
8152   SDValue N1 = N->getOperand(1);
8153 
8154   // fold (xor (sllw 1, x), -1) -> (rolw ~1, x)
8155   // NOTE: Assumes ROL being legal means ROLW is legal.
8156   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8157   if (N0.getOpcode() == RISCVISD::SLLW &&
8158       isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) &&
8159       TLI.isOperationLegal(ISD::ROTL, MVT::i64)) {
8160     SDLoc DL(N);
8161     return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64,
8162                        DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1));
8163   }
8164 
8165   if (SDValue V = combineBinOpToReduce(N, DAG))
8166     return V;
8167   // fold (xor (select cond, 0, y), x) ->
8168   //      (select cond, x, (xor x, y))
8169   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8170 }
8171 
8172 // Replace (seteq (i64 (and X, 0xffffffff)), C1) with
8173 // (seteq (i64 (sext_inreg (X, i32)), C1')) where C1' is C1 sign extended from
8174 // bit 31. Same for setne. C1' may be cheaper to materialize and the sext_inreg
8175 // can become a sext.w instead of a shift pair.
8176 static SDValue performSETCCCombine(SDNode *N, SelectionDAG &DAG,
8177                                    const RISCVSubtarget &Subtarget) {
8178   SDValue N0 = N->getOperand(0);
8179   SDValue N1 = N->getOperand(1);
8180   EVT VT = N->getValueType(0);
8181   EVT OpVT = N0.getValueType();
8182 
8183   if (OpVT != MVT::i64 || !Subtarget.is64Bit())
8184     return SDValue();
8185 
8186   // RHS needs to be a constant.
8187   auto *N1C = dyn_cast<ConstantSDNode>(N1);
8188   if (!N1C)
8189     return SDValue();
8190 
8191   // LHS needs to be (and X, 0xffffffff).
8192   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse() ||
8193       !isa<ConstantSDNode>(N0.getOperand(1)) ||
8194       N0.getConstantOperandVal(1) != UINT64_C(0xffffffff))
8195     return SDValue();
8196 
8197   // Looking for an equality compare.
8198   ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get();
8199   if (!isIntEqualitySetCC(Cond))
8200     return SDValue();
8201 
8202   const APInt &C1 = cast<ConstantSDNode>(N1)->getAPIntValue();
8203 
8204   SDLoc dl(N);
8205   // If the constant is larger than 2^32 - 1 it is impossible for both sides
8206   // to be equal.
8207   if (C1.getActiveBits() > 32)
8208     return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
8209 
8210   SDValue SExtOp = DAG.getNode(ISD::SIGN_EXTEND_INREG, N, OpVT,
8211                                N0.getOperand(0), DAG.getValueType(MVT::i32));
8212   return DAG.getSetCC(dl, VT, SExtOp, DAG.getConstant(C1.trunc(32).sext(64),
8213                                                       dl, OpVT), Cond);
8214 }
8215 
8216 static SDValue
8217 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
8218                                 const RISCVSubtarget &Subtarget) {
8219   SDValue Src = N->getOperand(0);
8220   EVT VT = N->getValueType(0);
8221 
8222   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
8223   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8224       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
8225     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
8226                        Src.getOperand(0));
8227 
8228   // Fold (i64 (sext_inreg (abs X), i32)) ->
8229   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
8230   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
8231   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
8232   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
8233   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
8234   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
8235   // may get combined into an earlier operation so we need to use
8236   // ComputeNumSignBits.
8237   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
8238   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
8239   // we can't assume that X has 33 sign bits. We must check.
8240   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
8241       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
8242       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
8243       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
8244     SDLoc DL(N);
8245     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
8246     SDValue Neg =
8247         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
8248     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
8249                       DAG.getValueType(MVT::i32));
8250     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
8251   }
8252 
8253   return SDValue();
8254 }
8255 
8256 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
8257 // vwadd(u).vv/vx or vwsub(u).vv/vx.
8258 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
8259                                              bool Commute = false) {
8260   assert((N->getOpcode() == RISCVISD::ADD_VL ||
8261           N->getOpcode() == RISCVISD::SUB_VL) &&
8262          "Unexpected opcode");
8263   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
8264   SDValue Op0 = N->getOperand(0);
8265   SDValue Op1 = N->getOperand(1);
8266   if (Commute)
8267     std::swap(Op0, Op1);
8268 
8269   MVT VT = N->getSimpleValueType(0);
8270 
8271   // Determine the narrow size for a widening add/sub.
8272   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8273   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8274                                   VT.getVectorElementCount());
8275 
8276   SDValue Mask = N->getOperand(2);
8277   SDValue VL = N->getOperand(3);
8278 
8279   SDLoc DL(N);
8280 
8281   // If the RHS is a sext or zext, we can form a widening op.
8282   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
8283        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
8284       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
8285     unsigned ExtOpc = Op1.getOpcode();
8286     Op1 = Op1.getOperand(0);
8287     // Re-introduce narrower extends if needed.
8288     if (Op1.getValueType() != NarrowVT)
8289       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8290 
8291     unsigned WOpc;
8292     if (ExtOpc == RISCVISD::VSEXT_VL)
8293       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
8294     else
8295       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
8296 
8297     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
8298   }
8299 
8300   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
8301   // sext/zext?
8302 
8303   return SDValue();
8304 }
8305 
8306 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
8307 // vwsub(u).vv/vx.
8308 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
8309   SDValue Op0 = N->getOperand(0);
8310   SDValue Op1 = N->getOperand(1);
8311   SDValue Mask = N->getOperand(2);
8312   SDValue VL = N->getOperand(3);
8313 
8314   MVT VT = N->getSimpleValueType(0);
8315   MVT NarrowVT = Op1.getSimpleValueType();
8316   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
8317 
8318   unsigned VOpc;
8319   switch (N->getOpcode()) {
8320   default: llvm_unreachable("Unexpected opcode");
8321   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
8322   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
8323   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
8324   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
8325   }
8326 
8327   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8328                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
8329 
8330   SDLoc DL(N);
8331 
8332   // If the LHS is a sext or zext, we can narrow this op to the same size as
8333   // the RHS.
8334   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
8335        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
8336       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
8337     unsigned ExtOpc = Op0.getOpcode();
8338     Op0 = Op0.getOperand(0);
8339     // Re-introduce narrower extends if needed.
8340     if (Op0.getValueType() != NarrowVT)
8341       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8342     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
8343   }
8344 
8345   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8346                N->getOpcode() == RISCVISD::VWADDU_W_VL;
8347 
8348   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
8349   // to commute and use a vwadd(u).vx instead.
8350   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
8351       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
8352     Op0 = Op0.getOperand(1);
8353 
8354     // See if have enough sign bits or zero bits in the scalar to use a
8355     // widening add/sub by splatting to smaller element size.
8356     unsigned EltBits = VT.getScalarSizeInBits();
8357     unsigned ScalarBits = Op0.getValueSizeInBits();
8358     // Make sure we're getting all element bits from the scalar register.
8359     // FIXME: Support implicit sign extension of vmv.v.x?
8360     if (ScalarBits < EltBits)
8361       return SDValue();
8362 
8363     if (IsSigned) {
8364       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
8365         return SDValue();
8366     } else {
8367       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8368       if (!DAG.MaskedValueIsZero(Op0, Mask))
8369         return SDValue();
8370     }
8371 
8372     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8373                       DAG.getUNDEF(NarrowVT), Op0, VL);
8374     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
8375   }
8376 
8377   return SDValue();
8378 }
8379 
8380 // Try to form VWMUL, VWMULU or VWMULSU.
8381 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
8382 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
8383                                        bool Commute) {
8384   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
8385   SDValue Op0 = N->getOperand(0);
8386   SDValue Op1 = N->getOperand(1);
8387   if (Commute)
8388     std::swap(Op0, Op1);
8389 
8390   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
8391   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
8392   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
8393   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
8394     return SDValue();
8395 
8396   SDValue Mask = N->getOperand(2);
8397   SDValue VL = N->getOperand(3);
8398 
8399   // Make sure the mask and VL match.
8400   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8401     return SDValue();
8402 
8403   MVT VT = N->getSimpleValueType(0);
8404 
8405   // Determine the narrow size for a widening multiply.
8406   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8407   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8408                                   VT.getVectorElementCount());
8409 
8410   SDLoc DL(N);
8411 
8412   // See if the other operand is the same opcode.
8413   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8414     if (!Op1.hasOneUse())
8415       return SDValue();
8416 
8417     // Make sure the mask and VL match.
8418     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8419       return SDValue();
8420 
8421     Op1 = Op1.getOperand(0);
8422   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8423     // The operand is a splat of a scalar.
8424 
8425     // The pasthru must be undef for tail agnostic
8426     if (!Op1.getOperand(0).isUndef())
8427       return SDValue();
8428     // The VL must be the same.
8429     if (Op1.getOperand(2) != VL)
8430       return SDValue();
8431 
8432     // Get the scalar value.
8433     Op1 = Op1.getOperand(1);
8434 
8435     // See if have enough sign bits or zero bits in the scalar to use a
8436     // widening multiply by splatting to smaller element size.
8437     unsigned EltBits = VT.getScalarSizeInBits();
8438     unsigned ScalarBits = Op1.getValueSizeInBits();
8439     // Make sure we're getting all element bits from the scalar register.
8440     // FIXME: Support implicit sign extension of vmv.v.x?
8441     if (ScalarBits < EltBits)
8442       return SDValue();
8443 
8444     // If the LHS is a sign extend, try to use vwmul.
8445     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8446       // Can use vwmul.
8447     } else {
8448       // Otherwise try to use vwmulu or vwmulsu.
8449       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8450       if (DAG.MaskedValueIsZero(Op1, Mask))
8451         IsVWMULSU = IsSignExt;
8452       else
8453         return SDValue();
8454     }
8455 
8456     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8457                       DAG.getUNDEF(NarrowVT), Op1, VL);
8458   } else
8459     return SDValue();
8460 
8461   Op0 = Op0.getOperand(0);
8462 
8463   // Re-introduce narrower extends if needed.
8464   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8465   if (Op0.getValueType() != NarrowVT)
8466     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8467   // vwmulsu requires second operand to be zero extended.
8468   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8469   if (Op1.getValueType() != NarrowVT)
8470     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8471 
8472   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8473   if (!IsVWMULSU)
8474     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8475   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8476 }
8477 
8478 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8479   switch (Op.getOpcode()) {
8480   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8481   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8482   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8483   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8484   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8485   }
8486 
8487   return RISCVFPRndMode::Invalid;
8488 }
8489 
8490 // Fold
8491 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8492 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8493 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8494 //   (fp_to_int (fceil X))      -> fcvt X, rup
8495 //   (fp_to_int (fround X))     -> fcvt X, rmm
8496 static SDValue performFP_TO_INTCombine(SDNode *N,
8497                                        TargetLowering::DAGCombinerInfo &DCI,
8498                                        const RISCVSubtarget &Subtarget) {
8499   SelectionDAG &DAG = DCI.DAG;
8500   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8501   MVT XLenVT = Subtarget.getXLenVT();
8502 
8503   // Only handle XLen or i32 types. Other types narrower than XLen will
8504   // eventually be legalized to XLenVT.
8505   EVT VT = N->getValueType(0);
8506   if (VT != MVT::i32 && VT != XLenVT)
8507     return SDValue();
8508 
8509   SDValue Src = N->getOperand(0);
8510 
8511   // Ensure the FP type is also legal.
8512   if (!TLI.isTypeLegal(Src.getValueType()))
8513     return SDValue();
8514 
8515   // Don't do this for f16 with Zfhmin and not Zfh.
8516   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8517     return SDValue();
8518 
8519   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8520   if (FRM == RISCVFPRndMode::Invalid)
8521     return SDValue();
8522 
8523   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8524 
8525   unsigned Opc;
8526   if (VT == XLenVT)
8527     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8528   else
8529     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8530 
8531   SDLoc DL(N);
8532   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8533                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8534   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8535 }
8536 
8537 // Fold
8538 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8539 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8540 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8541 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8542 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8543 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8544                                        TargetLowering::DAGCombinerInfo &DCI,
8545                                        const RISCVSubtarget &Subtarget) {
8546   SelectionDAG &DAG = DCI.DAG;
8547   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8548   MVT XLenVT = Subtarget.getXLenVT();
8549 
8550   // Only handle XLen types. Other types narrower than XLen will eventually be
8551   // legalized to XLenVT.
8552   EVT DstVT = N->getValueType(0);
8553   if (DstVT != XLenVT)
8554     return SDValue();
8555 
8556   SDValue Src = N->getOperand(0);
8557 
8558   // Ensure the FP type is also legal.
8559   if (!TLI.isTypeLegal(Src.getValueType()))
8560     return SDValue();
8561 
8562   // Don't do this for f16 with Zfhmin and not Zfh.
8563   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8564     return SDValue();
8565 
8566   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8567 
8568   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8569   if (FRM == RISCVFPRndMode::Invalid)
8570     return SDValue();
8571 
8572   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8573 
8574   unsigned Opc;
8575   if (SatVT == DstVT)
8576     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8577   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8578     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8579   else
8580     return SDValue();
8581   // FIXME: Support other SatVTs by clamping before or after the conversion.
8582 
8583   Src = Src.getOperand(0);
8584 
8585   SDLoc DL(N);
8586   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8587                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8588 
8589   // RISCV FP-to-int conversions saturate to the destination register size, but
8590   // don't produce 0 for nan.
8591   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8592   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8593 }
8594 
8595 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8596 // smaller than XLenVT.
8597 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8598                                         const RISCVSubtarget &Subtarget) {
8599   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8600 
8601   SDValue Src = N->getOperand(0);
8602   if (Src.getOpcode() != ISD::BSWAP)
8603     return SDValue();
8604 
8605   EVT VT = N->getValueType(0);
8606   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8607       !isPowerOf2_32(VT.getSizeInBits()))
8608     return SDValue();
8609 
8610   SDLoc DL(N);
8611   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8612                      DAG.getConstant(7, DL, VT));
8613 }
8614 
8615 // Convert from one FMA opcode to another based on whether we are negating the
8616 // multiply result and/or the accumulator.
8617 // NOTE: Only supports RVV operations with VL.
8618 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) {
8619   assert((NegMul || NegAcc) && "Not negating anything?");
8620 
8621   // Negating the multiply result changes ADD<->SUB and toggles 'N'.
8622   if (NegMul) {
8623     // clang-format off
8624     switch (Opcode) {
8625     default: llvm_unreachable("Unexpected opcode");
8626     case RISCVISD::VFMADD_VL:  Opcode = RISCVISD::VFNMSUB_VL; break;
8627     case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFMADD_VL;  break;
8628     case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFMSUB_VL;  break;
8629     case RISCVISD::VFMSUB_VL:  Opcode = RISCVISD::VFNMADD_VL; break;
8630     }
8631     // clang-format on
8632   }
8633 
8634   // Negating the accumulator changes ADD<->SUB.
8635   if (NegAcc) {
8636     // clang-format off
8637     switch (Opcode) {
8638     default: llvm_unreachable("Unexpected opcode");
8639     case RISCVISD::VFMADD_VL:  Opcode = RISCVISD::VFMSUB_VL;  break;
8640     case RISCVISD::VFMSUB_VL:  Opcode = RISCVISD::VFMADD_VL;  break;
8641     case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break;
8642     case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break;
8643     }
8644     // clang-format on
8645   }
8646 
8647   return Opcode;
8648 }
8649 
8650 static SDValue performSRACombine(SDNode *N, SelectionDAG &DAG,
8651                                  const RISCVSubtarget &Subtarget) {
8652   assert(N->getOpcode() == ISD::SRA && "Unexpected opcode");
8653 
8654   if (N->getValueType(0) != MVT::i64 || !Subtarget.is64Bit())
8655     return SDValue();
8656 
8657   if (!isa<ConstantSDNode>(N->getOperand(1)))
8658     return SDValue();
8659   uint64_t ShAmt = N->getConstantOperandVal(1);
8660   if (ShAmt > 32)
8661     return SDValue();
8662 
8663   SDValue N0 = N->getOperand(0);
8664 
8665   // Combine (sra (sext_inreg (shl X, C1), i32), C2) ->
8666   // (sra (shl X, C1+32), C2+32) so it gets selected as SLLI+SRAI instead of
8667   // SLLIW+SRAIW. SLLI+SRAI have compressed forms.
8668   if (ShAmt < 32 &&
8669       N0.getOpcode() == ISD::SIGN_EXTEND_INREG && N0.hasOneUse() &&
8670       cast<VTSDNode>(N0.getOperand(1))->getVT() == MVT::i32 &&
8671       N0.getOperand(0).getOpcode() == ISD::SHL && N0.getOperand(0).hasOneUse() &&
8672       isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
8673     uint64_t LShAmt = N0.getOperand(0).getConstantOperandVal(1);
8674     if (LShAmt < 32) {
8675       SDLoc ShlDL(N0.getOperand(0));
8676       SDValue Shl = DAG.getNode(ISD::SHL, ShlDL, MVT::i64,
8677                                 N0.getOperand(0).getOperand(0),
8678                                 DAG.getConstant(LShAmt + 32, ShlDL, MVT::i64));
8679       SDLoc DL(N);
8680       return DAG.getNode(ISD::SRA, DL, MVT::i64, Shl,
8681                          DAG.getConstant(ShAmt + 32, DL, MVT::i64));
8682     }
8683   }
8684 
8685   // Combine (sra (shl X, 32), 32 - C) -> (shl (sext_inreg X, i32), C)
8686   // FIXME: Should this be a generic combine? There's a similar combine on X86.
8687   //
8688   // Also try these folds where an add or sub is in the middle.
8689   // (sra (add (shl X, 32), C1), 32 - C) -> (shl (sext_inreg (add X, C1), C)
8690   // (sra (sub C1, (shl X, 32)), 32 - C) -> (shl (sext_inreg (sub C1, X), C)
8691   SDValue Shl;
8692   ConstantSDNode *AddC = nullptr;
8693 
8694   // We might have an ADD or SUB between the SRA and SHL.
8695   bool IsAdd = N0.getOpcode() == ISD::ADD;
8696   if ((IsAdd || N0.getOpcode() == ISD::SUB)) {
8697     if (!N0.hasOneUse())
8698       return SDValue();
8699     // Other operand needs to be a constant we can modify.
8700     AddC = dyn_cast<ConstantSDNode>(N0.getOperand(IsAdd ? 1 : 0));
8701     if (!AddC)
8702       return SDValue();
8703 
8704     // AddC needs to have at least 32 trailing zeros.
8705     if (AddC->getAPIntValue().countTrailingZeros() < 32)
8706       return SDValue();
8707 
8708     Shl = N0.getOperand(IsAdd ? 0 : 1);
8709   } else {
8710     // Not an ADD or SUB.
8711     Shl = N0;
8712   }
8713 
8714   // Look for a shift left by 32.
8715   if (Shl.getOpcode() != ISD::SHL || !Shl.hasOneUse() ||
8716       !isa<ConstantSDNode>(Shl.getOperand(1)) ||
8717       Shl.getConstantOperandVal(1) != 32)
8718     return SDValue();
8719 
8720   SDLoc DL(N);
8721   SDValue In = Shl.getOperand(0);
8722 
8723   // If we looked through an ADD or SUB, we need to rebuild it with the shifted
8724   // constant.
8725   if (AddC) {
8726     SDValue ShiftedAddC =
8727         DAG.getConstant(AddC->getAPIntValue().lshr(32), DL, MVT::i64);
8728     if (IsAdd)
8729       In = DAG.getNode(ISD::ADD, DL, MVT::i64, In, ShiftedAddC);
8730     else
8731       In = DAG.getNode(ISD::SUB, DL, MVT::i64, ShiftedAddC, In);
8732   }
8733 
8734   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, In,
8735                              DAG.getValueType(MVT::i32));
8736   if (ShAmt == 32)
8737     return SExt;
8738 
8739   return DAG.getNode(
8740       ISD::SHL, DL, MVT::i64, SExt,
8741       DAG.getConstant(32 - ShAmt, DL, MVT::i64));
8742 }
8743 
8744 // Perform common combines for BR_CC and SELECT_CC condtions.
8745 static bool combine_CC(SDValue &LHS, SDValue &RHS, SDValue &CC, const SDLoc &DL,
8746                        SelectionDAG &DAG, const RISCVSubtarget &Subtarget) {
8747   ISD::CondCode CCVal = cast<CondCodeSDNode>(CC)->get();
8748   if (!ISD::isIntEqualitySetCC(CCVal))
8749     return false;
8750 
8751   // Fold ((setlt X, Y), 0, ne) -> (X, Y, lt)
8752   // Sometimes the setcc is introduced after br_cc/select_cc has been formed.
8753   if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8754       LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8755     // If we're looking for eq 0 instead of ne 0, we need to invert the
8756     // condition.
8757     bool Invert = CCVal == ISD::SETEQ;
8758     CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8759     if (Invert)
8760       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8761 
8762     RHS = LHS.getOperand(1);
8763     LHS = LHS.getOperand(0);
8764     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8765 
8766     CC = DAG.getCondCode(CCVal);
8767     return true;
8768   }
8769 
8770   // Fold ((xor X, Y), 0, eq/ne) -> (X, Y, eq/ne)
8771   if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) {
8772     RHS = LHS.getOperand(1);
8773     LHS = LHS.getOperand(0);
8774     return true;
8775   }
8776 
8777   // Fold ((srl (and X, 1<<C), C), 0, eq/ne) -> ((shl X, XLen-1-C), 0, ge/lt)
8778   if (isNullConstant(RHS) && LHS.getOpcode() == ISD::SRL && LHS.hasOneUse() &&
8779       LHS.getOperand(1).getOpcode() == ISD::Constant) {
8780     SDValue LHS0 = LHS.getOperand(0);
8781     if (LHS0.getOpcode() == ISD::AND &&
8782         LHS0.getOperand(1).getOpcode() == ISD::Constant) {
8783       uint64_t Mask = LHS0.getConstantOperandVal(1);
8784       uint64_t ShAmt = LHS.getConstantOperandVal(1);
8785       if (isPowerOf2_64(Mask) && Log2_64(Mask) == ShAmt) {
8786         CCVal = CCVal == ISD::SETEQ ? ISD::SETGE : ISD::SETLT;
8787         CC = DAG.getCondCode(CCVal);
8788 
8789         ShAmt = LHS.getValueSizeInBits() - 1 - ShAmt;
8790         LHS = LHS0.getOperand(0);
8791         if (ShAmt != 0)
8792           LHS =
8793               DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS0.getOperand(0),
8794                           DAG.getConstant(ShAmt, DL, LHS.getValueType()));
8795         return true;
8796       }
8797     }
8798   }
8799 
8800   // (X, 1, setne) -> // (X, 0, seteq) if we can prove X is 0/1.
8801   // This can occur when legalizing some floating point comparisons.
8802   APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8803   if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8804     CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8805     CC = DAG.getCondCode(CCVal);
8806     RHS = DAG.getConstant(0, DL, LHS.getValueType());
8807     return true;
8808   }
8809 
8810   return false;
8811 }
8812 
8813 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8814                                                DAGCombinerInfo &DCI) const {
8815   SelectionDAG &DAG = DCI.DAG;
8816 
8817   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8818   // bits are demanded. N will be added to the Worklist if it was not deleted.
8819   // Caller should return SDValue(N, 0) if this returns true.
8820   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8821     SDValue Op = N->getOperand(OpNo);
8822     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8823     if (!SimplifyDemandedBits(Op, Mask, DCI))
8824       return false;
8825 
8826     if (N->getOpcode() != ISD::DELETED_NODE)
8827       DCI.AddToWorklist(N);
8828     return true;
8829   };
8830 
8831   switch (N->getOpcode()) {
8832   default:
8833     break;
8834   case RISCVISD::SplitF64: {
8835     SDValue Op0 = N->getOperand(0);
8836     // If the input to SplitF64 is just BuildPairF64 then the operation is
8837     // redundant. Instead, use BuildPairF64's operands directly.
8838     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8839       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8840 
8841     if (Op0->isUndef()) {
8842       SDValue Lo = DAG.getUNDEF(MVT::i32);
8843       SDValue Hi = DAG.getUNDEF(MVT::i32);
8844       return DCI.CombineTo(N, Lo, Hi);
8845     }
8846 
8847     SDLoc DL(N);
8848 
8849     // It's cheaper to materialise two 32-bit integers than to load a double
8850     // from the constant pool and transfer it to integer registers through the
8851     // stack.
8852     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8853       APInt V = C->getValueAPF().bitcastToAPInt();
8854       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8855       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8856       return DCI.CombineTo(N, Lo, Hi);
8857     }
8858 
8859     // This is a target-specific version of a DAGCombine performed in
8860     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8861     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8862     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8863     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8864         !Op0.getNode()->hasOneUse())
8865       break;
8866     SDValue NewSplitF64 =
8867         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8868                     Op0.getOperand(0));
8869     SDValue Lo = NewSplitF64.getValue(0);
8870     SDValue Hi = NewSplitF64.getValue(1);
8871     APInt SignBit = APInt::getSignMask(32);
8872     if (Op0.getOpcode() == ISD::FNEG) {
8873       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8874                                   DAG.getConstant(SignBit, DL, MVT::i32));
8875       return DCI.CombineTo(N, Lo, NewHi);
8876     }
8877     assert(Op0.getOpcode() == ISD::FABS);
8878     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8879                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8880     return DCI.CombineTo(N, Lo, NewHi);
8881   }
8882   case RISCVISD::SLLW:
8883   case RISCVISD::SRAW:
8884   case RISCVISD::SRLW: {
8885     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8886     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8887         SimplifyDemandedLowBitsHelper(1, 5))
8888       return SDValue(N, 0);
8889 
8890     break;
8891   }
8892   case ISD::ROTR:
8893   case ISD::ROTL:
8894   case RISCVISD::RORW:
8895   case RISCVISD::ROLW: {
8896     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8897       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8898       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8899           SimplifyDemandedLowBitsHelper(1, 5))
8900         return SDValue(N, 0);
8901     }
8902 
8903     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8904   }
8905   case RISCVISD::CLZW:
8906   case RISCVISD::CTZW: {
8907     // Only the lower 32 bits of the first operand are read
8908     if (SimplifyDemandedLowBitsHelper(0, 32))
8909       return SDValue(N, 0);
8910     break;
8911   }
8912   case RISCVISD::GREV:
8913   case RISCVISD::GORC: {
8914     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8915     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8916     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8917     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8918       return SDValue(N, 0);
8919 
8920     return combineGREVI_GORCI(N, DAG);
8921   }
8922   case RISCVISD::GREVW:
8923   case RISCVISD::GORCW: {
8924     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8925     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8926         SimplifyDemandedLowBitsHelper(1, 5))
8927       return SDValue(N, 0);
8928 
8929     break;
8930   }
8931   case RISCVISD::SHFL:
8932   case RISCVISD::UNSHFL: {
8933     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8934     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8935     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8936     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8937       return SDValue(N, 0);
8938 
8939     break;
8940   }
8941   case RISCVISD::SHFLW:
8942   case RISCVISD::UNSHFLW: {
8943     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8944     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8945         SimplifyDemandedLowBitsHelper(1, 4))
8946       return SDValue(N, 0);
8947 
8948     break;
8949   }
8950   case RISCVISD::BCOMPRESSW:
8951   case RISCVISD::BDECOMPRESSW: {
8952     // Only the lower 32 bits of LHS and RHS are read.
8953     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8954         SimplifyDemandedLowBitsHelper(1, 32))
8955       return SDValue(N, 0);
8956 
8957     break;
8958   }
8959   case RISCVISD::FSR:
8960   case RISCVISD::FSL:
8961   case RISCVISD::FSRW:
8962   case RISCVISD::FSLW: {
8963     bool IsWInstruction =
8964         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8965     unsigned BitWidth =
8966         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8967     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8968     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8969     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8970       return SDValue(N, 0);
8971 
8972     break;
8973   }
8974   case RISCVISD::FMV_X_ANYEXTH:
8975   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8976     SDLoc DL(N);
8977     SDValue Op0 = N->getOperand(0);
8978     MVT VT = N->getSimpleValueType(0);
8979     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8980     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8981     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8982     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8983          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8984         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8985          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8986       assert(Op0.getOperand(0).getValueType() == VT &&
8987              "Unexpected value type!");
8988       return Op0.getOperand(0);
8989     }
8990 
8991     // This is a target-specific version of a DAGCombine performed in
8992     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8993     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8994     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8995     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8996         !Op0.getNode()->hasOneUse())
8997       break;
8998     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8999     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
9000     APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits());
9001     if (Op0.getOpcode() == ISD::FNEG)
9002       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
9003                          DAG.getConstant(SignBit, DL, VT));
9004 
9005     assert(Op0.getOpcode() == ISD::FABS);
9006     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
9007                        DAG.getConstant(~SignBit, DL, VT));
9008   }
9009   case ISD::ADD:
9010     return performADDCombine(N, DAG, Subtarget);
9011   case ISD::SUB:
9012     return performSUBCombine(N, DAG);
9013   case ISD::AND:
9014     return performANDCombine(N, DAG, Subtarget);
9015   case ISD::OR:
9016     return performORCombine(N, DAG, Subtarget);
9017   case ISD::XOR:
9018     return performXORCombine(N, DAG);
9019   case ISD::FADD:
9020   case ISD::UMAX:
9021   case ISD::UMIN:
9022   case ISD::SMAX:
9023   case ISD::SMIN:
9024   case ISD::FMAXNUM:
9025   case ISD::FMINNUM:
9026     return combineBinOpToReduce(N, DAG);
9027   case ISD::SETCC:
9028     return performSETCCCombine(N, DAG, Subtarget);
9029   case ISD::SIGN_EXTEND_INREG:
9030     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
9031   case ISD::ZERO_EXTEND:
9032     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
9033     // type legalization. This is safe because fp_to_uint produces poison if
9034     // it overflows.
9035     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
9036       SDValue Src = N->getOperand(0);
9037       if (Src.getOpcode() == ISD::FP_TO_UINT &&
9038           isTypeLegal(Src.getOperand(0).getValueType()))
9039         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
9040                            Src.getOperand(0));
9041       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
9042           isTypeLegal(Src.getOperand(1).getValueType())) {
9043         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
9044         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
9045                                   Src.getOperand(0), Src.getOperand(1));
9046         DCI.CombineTo(N, Res);
9047         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
9048         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
9049         return SDValue(N, 0); // Return N so it doesn't get rechecked.
9050       }
9051     }
9052     return SDValue();
9053   case RISCVISD::SELECT_CC: {
9054     // Transform
9055     SDValue LHS = N->getOperand(0);
9056     SDValue RHS = N->getOperand(1);
9057     SDValue CC = N->getOperand(2);
9058     SDValue TrueV = N->getOperand(3);
9059     SDValue FalseV = N->getOperand(4);
9060     SDLoc DL(N);
9061 
9062     // If the True and False values are the same, we don't need a select_cc.
9063     if (TrueV == FalseV)
9064       return TrueV;
9065 
9066     if (combine_CC(LHS, RHS, CC, DL, DAG, Subtarget))
9067       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
9068                          {LHS, RHS, CC, TrueV, FalseV});
9069 
9070     return SDValue();
9071   }
9072   case RISCVISD::BR_CC: {
9073     SDValue LHS = N->getOperand(1);
9074     SDValue RHS = N->getOperand(2);
9075     SDValue CC = N->getOperand(3);
9076     SDLoc DL(N);
9077 
9078     if (combine_CC(LHS, RHS, CC, DL, DAG, Subtarget))
9079       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
9080                          N->getOperand(0), LHS, RHS, CC, N->getOperand(4));
9081 
9082     return SDValue();
9083   }
9084   case ISD::BITREVERSE:
9085     return performBITREVERSECombine(N, DAG, Subtarget);
9086   case ISD::FP_TO_SINT:
9087   case ISD::FP_TO_UINT:
9088     return performFP_TO_INTCombine(N, DCI, Subtarget);
9089   case ISD::FP_TO_SINT_SAT:
9090   case ISD::FP_TO_UINT_SAT:
9091     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
9092   case ISD::FCOPYSIGN: {
9093     EVT VT = N->getValueType(0);
9094     if (!VT.isVector())
9095       break;
9096     // There is a form of VFSGNJ which injects the negated sign of its second
9097     // operand. Try and bubble any FNEG up after the extend/round to produce
9098     // this optimized pattern. Avoid modifying cases where FP_ROUND and
9099     // TRUNC=1.
9100     SDValue In2 = N->getOperand(1);
9101     // Avoid cases where the extend/round has multiple uses, as duplicating
9102     // those is typically more expensive than removing a fneg.
9103     if (!In2.hasOneUse())
9104       break;
9105     if (In2.getOpcode() != ISD::FP_EXTEND &&
9106         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
9107       break;
9108     In2 = In2.getOperand(0);
9109     if (In2.getOpcode() != ISD::FNEG)
9110       break;
9111     SDLoc DL(N);
9112     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
9113     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
9114                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
9115   }
9116   case ISD::MGATHER:
9117   case ISD::MSCATTER:
9118   case ISD::VP_GATHER:
9119   case ISD::VP_SCATTER: {
9120     if (!DCI.isBeforeLegalize())
9121       break;
9122     SDValue Index, ScaleOp;
9123     bool IsIndexScaled = false;
9124     bool IsIndexSigned = false;
9125     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
9126       Index = VPGSN->getIndex();
9127       ScaleOp = VPGSN->getScale();
9128       IsIndexScaled = VPGSN->isIndexScaled();
9129       IsIndexSigned = VPGSN->isIndexSigned();
9130     } else {
9131       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
9132       Index = MGSN->getIndex();
9133       ScaleOp = MGSN->getScale();
9134       IsIndexScaled = MGSN->isIndexScaled();
9135       IsIndexSigned = MGSN->isIndexSigned();
9136     }
9137     EVT IndexVT = Index.getValueType();
9138     MVT XLenVT = Subtarget.getXLenVT();
9139     // RISCV indexed loads only support the "unsigned unscaled" addressing
9140     // mode, so anything else must be manually legalized.
9141     bool NeedsIdxLegalization =
9142         IsIndexScaled ||
9143         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
9144     if (!NeedsIdxLegalization)
9145       break;
9146 
9147     SDLoc DL(N);
9148 
9149     // Any index legalization should first promote to XLenVT, so we don't lose
9150     // bits when scaling. This may create an illegal index type so we let
9151     // LLVM's legalization take care of the splitting.
9152     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
9153     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
9154       IndexVT = IndexVT.changeVectorElementType(XLenVT);
9155       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9156                           DL, IndexVT, Index);
9157     }
9158 
9159     if (IsIndexScaled) {
9160       // Manually scale the indices.
9161       // TODO: Sanitize the scale operand here?
9162       // TODO: For VP nodes, should we use VP_SHL here?
9163       unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
9164       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
9165       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
9166       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
9167       ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType());
9168     }
9169 
9170     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED;
9171     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
9172       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
9173                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
9174                               ScaleOp, VPGN->getMask(),
9175                               VPGN->getVectorLength()},
9176                              VPGN->getMemOperand(), NewIndexTy);
9177     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
9178       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
9179                               {VPSN->getChain(), VPSN->getValue(),
9180                                VPSN->getBasePtr(), Index, ScaleOp,
9181                                VPSN->getMask(), VPSN->getVectorLength()},
9182                               VPSN->getMemOperand(), NewIndexTy);
9183     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
9184       return DAG.getMaskedGather(
9185           N->getVTList(), MGN->getMemoryVT(), DL,
9186           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
9187            MGN->getBasePtr(), Index, ScaleOp},
9188           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
9189     const auto *MSN = cast<MaskedScatterSDNode>(N);
9190     return DAG.getMaskedScatter(
9191         N->getVTList(), MSN->getMemoryVT(), DL,
9192         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
9193          Index, ScaleOp},
9194         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
9195   }
9196   case RISCVISD::SRA_VL:
9197   case RISCVISD::SRL_VL:
9198   case RISCVISD::SHL_VL: {
9199     SDValue ShAmt = N->getOperand(1);
9200     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
9201       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
9202       SDLoc DL(N);
9203       SDValue VL = N->getOperand(3);
9204       EVT VT = N->getValueType(0);
9205       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
9206                           ShAmt.getOperand(1), VL);
9207       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
9208                          N->getOperand(2), N->getOperand(3));
9209     }
9210     break;
9211   }
9212   case ISD::SRA:
9213     if (SDValue V = performSRACombine(N, DAG, Subtarget))
9214       return V;
9215     LLVM_FALLTHROUGH;
9216   case ISD::SRL:
9217   case ISD::SHL: {
9218     SDValue ShAmt = N->getOperand(1);
9219     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
9220       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
9221       SDLoc DL(N);
9222       EVT VT = N->getValueType(0);
9223       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
9224                           ShAmt.getOperand(1),
9225                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
9226       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
9227     }
9228     break;
9229   }
9230   case RISCVISD::ADD_VL:
9231     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
9232       return V;
9233     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
9234   case RISCVISD::SUB_VL:
9235     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
9236   case RISCVISD::VWADD_W_VL:
9237   case RISCVISD::VWADDU_W_VL:
9238   case RISCVISD::VWSUB_W_VL:
9239   case RISCVISD::VWSUBU_W_VL:
9240     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
9241   case RISCVISD::MUL_VL:
9242     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
9243       return V;
9244     // Mul is commutative.
9245     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
9246   case RISCVISD::VFMADD_VL:
9247   case RISCVISD::VFNMADD_VL:
9248   case RISCVISD::VFMSUB_VL:
9249   case RISCVISD::VFNMSUB_VL: {
9250     // Fold FNEG_VL into FMA opcodes.
9251     SDValue A = N->getOperand(0);
9252     SDValue B = N->getOperand(1);
9253     SDValue C = N->getOperand(2);
9254     SDValue Mask = N->getOperand(3);
9255     SDValue VL = N->getOperand(4);
9256 
9257     auto invertIfNegative = [&Mask, &VL](SDValue &V) {
9258       if (V.getOpcode() == RISCVISD::FNEG_VL && V.getOperand(1) == Mask &&
9259           V.getOperand(2) == VL) {
9260         // Return the negated input.
9261         V = V.getOperand(0);
9262         return true;
9263       }
9264 
9265       return false;
9266     };
9267 
9268     bool NegA = invertIfNegative(A);
9269     bool NegB = invertIfNegative(B);
9270     bool NegC = invertIfNegative(C);
9271 
9272     // If no operands are negated, we're done.
9273     if (!NegA && !NegB && !NegC)
9274       return SDValue();
9275 
9276     unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC);
9277     return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), A, B, C, Mask,
9278                        VL);
9279   }
9280   case ISD::STORE: {
9281     auto *Store = cast<StoreSDNode>(N);
9282     SDValue Val = Store->getValue();
9283     // Combine store of vmv.x.s to vse with VL of 1.
9284     // FIXME: Support FP.
9285     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
9286       SDValue Src = Val.getOperand(0);
9287       MVT VecVT = Src.getSimpleValueType();
9288       EVT MemVT = Store->getMemoryVT();
9289       // The memory VT and the element type must match.
9290       if (MemVT == VecVT.getVectorElementType()) {
9291         SDLoc DL(N);
9292         MVT MaskVT = getMaskTypeFor(VecVT);
9293         return DAG.getStoreVP(
9294             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
9295             DAG.getConstant(1, DL, MaskVT),
9296             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
9297             Store->getMemOperand(), Store->getAddressingMode(),
9298             Store->isTruncatingStore(), /*IsCompress*/ false);
9299       }
9300     }
9301 
9302     break;
9303   }
9304   case ISD::SPLAT_VECTOR: {
9305     EVT VT = N->getValueType(0);
9306     // Only perform this combine on legal MVT types.
9307     if (!isTypeLegal(VT))
9308       break;
9309     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
9310                                          DAG, Subtarget))
9311       return Gather;
9312     break;
9313   }
9314   case RISCVISD::VMV_V_X_VL: {
9315     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
9316     // scalar input.
9317     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
9318     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
9319     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
9320       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
9321         return SDValue(N, 0);
9322 
9323     break;
9324   }
9325   case ISD::INTRINSIC_WO_CHAIN: {
9326     unsigned IntNo = N->getConstantOperandVal(0);
9327     switch (IntNo) {
9328       // By default we do not combine any intrinsic.
9329     default:
9330       return SDValue();
9331     case Intrinsic::riscv_vcpop:
9332     case Intrinsic::riscv_vcpop_mask:
9333     case Intrinsic::riscv_vfirst:
9334     case Intrinsic::riscv_vfirst_mask: {
9335       SDValue VL = N->getOperand(2);
9336       if (IntNo == Intrinsic::riscv_vcpop_mask ||
9337           IntNo == Intrinsic::riscv_vfirst_mask)
9338         VL = N->getOperand(3);
9339       if (!isNullConstant(VL))
9340         return SDValue();
9341       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
9342       SDLoc DL(N);
9343       EVT VT = N->getValueType(0);
9344       if (IntNo == Intrinsic::riscv_vfirst ||
9345           IntNo == Intrinsic::riscv_vfirst_mask)
9346         return DAG.getConstant(-1, DL, VT);
9347       return DAG.getConstant(0, DL, VT);
9348     }
9349     }
9350   }
9351   case ISD::BITCAST: {
9352     assert(Subtarget.useRVVForFixedLengthVectors());
9353     SDValue N0 = N->getOperand(0);
9354     EVT VT = N->getValueType(0);
9355     EVT SrcVT = N0.getValueType();
9356     // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer
9357     // type, widen both sides to avoid a trip through memory.
9358     if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) &&
9359         VT.isScalarInteger()) {
9360       unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
9361       SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
9362       Ops[0] = N0;
9363       SDLoc DL(N);
9364       N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops);
9365       N0 = DAG.getBitcast(MVT::i8, N0);
9366       return DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
9367     }
9368 
9369     return SDValue();
9370   }
9371   }
9372 
9373   return SDValue();
9374 }
9375 
9376 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
9377     const SDNode *N, CombineLevel Level) const {
9378   assert((N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA ||
9379           N->getOpcode() == ISD::SRL) &&
9380          "Expected shift op");
9381 
9382   // The following folds are only desirable if `(OP _, c1 << c2)` can be
9383   // materialised in fewer instructions than `(OP _, c1)`:
9384   //
9385   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
9386   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
9387   SDValue N0 = N->getOperand(0);
9388   EVT Ty = N0.getValueType();
9389   if (Ty.isScalarInteger() &&
9390       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
9391     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9392     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
9393     if (C1 && C2) {
9394       const APInt &C1Int = C1->getAPIntValue();
9395       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
9396 
9397       // We can materialise `c1 << c2` into an add immediate, so it's "free",
9398       // and the combine should happen, to potentially allow further combines
9399       // later.
9400       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
9401           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
9402         return true;
9403 
9404       // We can materialise `c1` in an add immediate, so it's "free", and the
9405       // combine should be prevented.
9406       if (C1Int.getMinSignedBits() <= 64 &&
9407           isLegalAddImmediate(C1Int.getSExtValue()))
9408         return false;
9409 
9410       // Neither constant will fit into an immediate, so find materialisation
9411       // costs.
9412       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
9413                                               Subtarget.getFeatureBits(),
9414                                               /*CompressionCost*/true);
9415       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
9416           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
9417           /*CompressionCost*/true);
9418 
9419       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
9420       // combine should be prevented.
9421       if (C1Cost < ShiftedC1Cost)
9422         return false;
9423     }
9424   }
9425   return true;
9426 }
9427 
9428 bool RISCVTargetLowering::targetShrinkDemandedConstant(
9429     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
9430     TargetLoweringOpt &TLO) const {
9431   // Delay this optimization as late as possible.
9432   if (!TLO.LegalOps)
9433     return false;
9434 
9435   EVT VT = Op.getValueType();
9436   if (VT.isVector())
9437     return false;
9438 
9439   // Only handle AND for now.
9440   unsigned Opcode = Op.getOpcode();
9441   if (Opcode != ISD::AND && Opcode != ISD::OR && Opcode != ISD::XOR)
9442     return false;
9443 
9444   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9445   if (!C)
9446     return false;
9447 
9448   const APInt &Mask = C->getAPIntValue();
9449 
9450   // Clear all non-demanded bits initially.
9451   APInt ShrunkMask = Mask & DemandedBits;
9452 
9453   // Try to make a smaller immediate by setting undemanded bits.
9454 
9455   APInt ExpandedMask = Mask | ~DemandedBits;
9456 
9457   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
9458     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
9459   };
9460   auto UseMask = [Mask, Op, &TLO](const APInt &NewMask) -> bool {
9461     if (NewMask == Mask)
9462       return true;
9463     SDLoc DL(Op);
9464     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, Op.getValueType());
9465     SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), DL, Op.getValueType(),
9466                                     Op.getOperand(0), NewC);
9467     return TLO.CombineTo(Op, NewOp);
9468   };
9469 
9470   // If the shrunk mask fits in sign extended 12 bits, let the target
9471   // independent code apply it.
9472   if (ShrunkMask.isSignedIntN(12))
9473     return false;
9474 
9475   // And has a few special cases for zext.
9476   if (Opcode == ISD::AND) {
9477     // Preserve (and X, 0xffff) when zext.h is supported.
9478     if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
9479       APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
9480       if (IsLegalMask(NewMask))
9481         return UseMask(NewMask);
9482     }
9483 
9484     // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
9485     if (VT == MVT::i64) {
9486       APInt NewMask = APInt(64, 0xffffffff);
9487       if (IsLegalMask(NewMask))
9488         return UseMask(NewMask);
9489     }
9490   }
9491 
9492   // For the remaining optimizations, we need to be able to make a negative
9493   // number through a combination of mask and undemanded bits.
9494   if (!ExpandedMask.isNegative())
9495     return false;
9496 
9497   // What is the fewest number of bits we need to represent the negative number.
9498   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
9499 
9500   // Try to make a 12 bit negative immediate. If that fails try to make a 32
9501   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
9502   // If we can't create a simm12, we shouldn't change opaque constants.
9503   APInt NewMask = ShrunkMask;
9504   if (MinSignedBits <= 12)
9505     NewMask.setBitsFrom(11);
9506   else if (!C->isOpaque() && MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
9507     NewMask.setBitsFrom(31);
9508   else
9509     return false;
9510 
9511   // Check that our new mask is a subset of the demanded mask.
9512   assert(IsLegalMask(NewMask));
9513   return UseMask(NewMask);
9514 }
9515 
9516 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
9517   static const uint64_t GREVMasks[] = {
9518       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
9519       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
9520 
9521   for (unsigned Stage = 0; Stage != 6; ++Stage) {
9522     unsigned Shift = 1 << Stage;
9523     if (ShAmt & Shift) {
9524       uint64_t Mask = GREVMasks[Stage];
9525       uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
9526       if (IsGORC)
9527         Res |= x;
9528       x = Res;
9529     }
9530   }
9531 
9532   return x;
9533 }
9534 
9535 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9536                                                         KnownBits &Known,
9537                                                         const APInt &DemandedElts,
9538                                                         const SelectionDAG &DAG,
9539                                                         unsigned Depth) const {
9540   unsigned BitWidth = Known.getBitWidth();
9541   unsigned Opc = Op.getOpcode();
9542   assert((Opc >= ISD::BUILTIN_OP_END ||
9543           Opc == ISD::INTRINSIC_WO_CHAIN ||
9544           Opc == ISD::INTRINSIC_W_CHAIN ||
9545           Opc == ISD::INTRINSIC_VOID) &&
9546          "Should use MaskedValueIsZero if you don't know whether Op"
9547          " is a target node!");
9548 
9549   Known.resetAll();
9550   switch (Opc) {
9551   default: break;
9552   case RISCVISD::SELECT_CC: {
9553     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
9554     // If we don't know any bits, early out.
9555     if (Known.isUnknown())
9556       break;
9557     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
9558 
9559     // Only known if known in both the LHS and RHS.
9560     Known = KnownBits::commonBits(Known, Known2);
9561     break;
9562   }
9563   case RISCVISD::REMUW: {
9564     KnownBits Known2;
9565     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9566     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9567     // We only care about the lower 32 bits.
9568     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
9569     // Restore the original width by sign extending.
9570     Known = Known.sext(BitWidth);
9571     break;
9572   }
9573   case RISCVISD::DIVUW: {
9574     KnownBits Known2;
9575     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9576     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9577     // We only care about the lower 32 bits.
9578     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
9579     // Restore the original width by sign extending.
9580     Known = Known.sext(BitWidth);
9581     break;
9582   }
9583   case RISCVISD::CTZW: {
9584     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9585     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
9586     unsigned LowBits = Log2_32(PossibleTZ) + 1;
9587     Known.Zero.setBitsFrom(LowBits);
9588     break;
9589   }
9590   case RISCVISD::CLZW: {
9591     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9592     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
9593     unsigned LowBits = Log2_32(PossibleLZ) + 1;
9594     Known.Zero.setBitsFrom(LowBits);
9595     break;
9596   }
9597   case RISCVISD::GREV:
9598   case RISCVISD::GORC: {
9599     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9600       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9601       unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1);
9602       bool IsGORC = Op.getOpcode() == RISCVISD::GORC;
9603       // To compute zeros, we need to invert the value and invert it back after.
9604       Known.Zero =
9605           ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC);
9606       Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC);
9607     }
9608     break;
9609   }
9610   case RISCVISD::READ_VLENB: {
9611     // We can use the minimum and maximum VLEN values to bound VLENB.  We
9612     // know VLEN must be a power of two.
9613     const unsigned MinVLenB = Subtarget.getRealMinVLen() / 8;
9614     const unsigned MaxVLenB = Subtarget.getRealMaxVLen() / 8;
9615     assert(MinVLenB > 0 && "READ_VLENB without vector extension enabled?");
9616     Known.Zero.setLowBits(Log2_32(MinVLenB));
9617     Known.Zero.setBitsFrom(Log2_32(MaxVLenB)+1);
9618     if (MaxVLenB == MinVLenB)
9619       Known.One.setBit(Log2_32(MinVLenB));
9620     break;
9621   }
9622   case ISD::INTRINSIC_W_CHAIN:
9623   case ISD::INTRINSIC_WO_CHAIN: {
9624     unsigned IntNo =
9625         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9626     switch (IntNo) {
9627     default:
9628       // We can't do anything for most intrinsics.
9629       break;
9630     case Intrinsic::riscv_vsetvli:
9631     case Intrinsic::riscv_vsetvlimax:
9632     case Intrinsic::riscv_vsetvli_opt:
9633     case Intrinsic::riscv_vsetvlimax_opt:
9634       // Assume that VL output is positive and would fit in an int32_t.
9635       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9636       if (BitWidth >= 32)
9637         Known.Zero.setBitsFrom(31);
9638       break;
9639     }
9640     break;
9641   }
9642   }
9643 }
9644 
9645 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9646     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9647     unsigned Depth) const {
9648   switch (Op.getOpcode()) {
9649   default:
9650     break;
9651   case RISCVISD::SELECT_CC: {
9652     unsigned Tmp =
9653         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9654     if (Tmp == 1) return 1;  // Early out.
9655     unsigned Tmp2 =
9656         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9657     return std::min(Tmp, Tmp2);
9658   }
9659   case RISCVISD::SLLW:
9660   case RISCVISD::SRAW:
9661   case RISCVISD::SRLW:
9662   case RISCVISD::DIVW:
9663   case RISCVISD::DIVUW:
9664   case RISCVISD::REMUW:
9665   case RISCVISD::ROLW:
9666   case RISCVISD::RORW:
9667   case RISCVISD::GREVW:
9668   case RISCVISD::GORCW:
9669   case RISCVISD::FSLW:
9670   case RISCVISD::FSRW:
9671   case RISCVISD::SHFLW:
9672   case RISCVISD::UNSHFLW:
9673   case RISCVISD::BCOMPRESSW:
9674   case RISCVISD::BDECOMPRESSW:
9675   case RISCVISD::BFPW:
9676   case RISCVISD::FCVT_W_RV64:
9677   case RISCVISD::FCVT_WU_RV64:
9678   case RISCVISD::STRICT_FCVT_W_RV64:
9679   case RISCVISD::STRICT_FCVT_WU_RV64:
9680     // TODO: As the result is sign-extended, this is conservatively correct. A
9681     // more precise answer could be calculated for SRAW depending on known
9682     // bits in the shift amount.
9683     return 33;
9684   case RISCVISD::SHFL:
9685   case RISCVISD::UNSHFL: {
9686     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9687     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9688     // will stay within the upper 32 bits. If there were more than 32 sign bits
9689     // before there will be at least 33 sign bits after.
9690     if (Op.getValueType() == MVT::i64 &&
9691         isa<ConstantSDNode>(Op.getOperand(1)) &&
9692         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9693       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9694       if (Tmp > 32)
9695         return 33;
9696     }
9697     break;
9698   }
9699   case RISCVISD::VMV_X_S: {
9700     // The number of sign bits of the scalar result is computed by obtaining the
9701     // element type of the input vector operand, subtracting its width from the
9702     // XLEN, and then adding one (sign bit within the element type). If the
9703     // element type is wider than XLen, the least-significant XLEN bits are
9704     // taken.
9705     unsigned XLen = Subtarget.getXLen();
9706     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9707     if (EltBits <= XLen)
9708       return XLen - EltBits + 1;
9709     break;
9710   }
9711   }
9712 
9713   return 1;
9714 }
9715 
9716 const Constant *
9717 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const {
9718   assert(Ld && "Unexpected null LoadSDNode");
9719   if (!ISD::isNormalLoad(Ld))
9720     return nullptr;
9721 
9722   SDValue Ptr = Ld->getBasePtr();
9723 
9724   // Only constant pools with no offset are supported.
9725   auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * {
9726     auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
9727     if (!CNode || CNode->isMachineConstantPoolEntry() ||
9728         CNode->getOffset() != 0)
9729       return nullptr;
9730 
9731     return CNode;
9732   };
9733 
9734   // Simple case, LLA.
9735   if (Ptr.getOpcode() == RISCVISD::LLA) {
9736     auto *CNode = GetSupportedConstantPool(Ptr);
9737     if (!CNode || CNode->getTargetFlags() != 0)
9738       return nullptr;
9739 
9740     return CNode->getConstVal();
9741   }
9742 
9743   // Look for a HI and ADD_LO pair.
9744   if (Ptr.getOpcode() != RISCVISD::ADD_LO ||
9745       Ptr.getOperand(0).getOpcode() != RISCVISD::HI)
9746     return nullptr;
9747 
9748   auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1));
9749   auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0));
9750 
9751   if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO ||
9752       !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI)
9753     return nullptr;
9754 
9755   if (CNodeLo->getConstVal() != CNodeHi->getConstVal())
9756     return nullptr;
9757 
9758   return CNodeLo->getConstVal();
9759 }
9760 
9761 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9762                                                   MachineBasicBlock *BB) {
9763   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9764 
9765   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9766   // Should the count have wrapped while it was being read, we need to try
9767   // again.
9768   // ...
9769   // read:
9770   // rdcycleh x3 # load high word of cycle
9771   // rdcycle  x2 # load low word of cycle
9772   // rdcycleh x4 # load high word of cycle
9773   // bne x3, x4, read # check if high word reads match, otherwise try again
9774   // ...
9775 
9776   MachineFunction &MF = *BB->getParent();
9777   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9778   MachineFunction::iterator It = ++BB->getIterator();
9779 
9780   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9781   MF.insert(It, LoopMBB);
9782 
9783   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9784   MF.insert(It, DoneMBB);
9785 
9786   // Transfer the remainder of BB and its successor edges to DoneMBB.
9787   DoneMBB->splice(DoneMBB->begin(), BB,
9788                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9789   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9790 
9791   BB->addSuccessor(LoopMBB);
9792 
9793   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9794   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9795   Register LoReg = MI.getOperand(0).getReg();
9796   Register HiReg = MI.getOperand(1).getReg();
9797   DebugLoc DL = MI.getDebugLoc();
9798 
9799   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9800   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9801       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9802       .addReg(RISCV::X0);
9803   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9804       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9805       .addReg(RISCV::X0);
9806   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9807       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9808       .addReg(RISCV::X0);
9809 
9810   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9811       .addReg(HiReg)
9812       .addReg(ReadAgainReg)
9813       .addMBB(LoopMBB);
9814 
9815   LoopMBB->addSuccessor(LoopMBB);
9816   LoopMBB->addSuccessor(DoneMBB);
9817 
9818   MI.eraseFromParent();
9819 
9820   return DoneMBB;
9821 }
9822 
9823 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9824                                              MachineBasicBlock *BB) {
9825   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9826 
9827   MachineFunction &MF = *BB->getParent();
9828   DebugLoc DL = MI.getDebugLoc();
9829   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9830   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9831   Register LoReg = MI.getOperand(0).getReg();
9832   Register HiReg = MI.getOperand(1).getReg();
9833   Register SrcReg = MI.getOperand(2).getReg();
9834   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9835   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9836 
9837   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9838                           RI);
9839   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9840   MachineMemOperand *MMOLo =
9841       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9842   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9843       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9844   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9845       .addFrameIndex(FI)
9846       .addImm(0)
9847       .addMemOperand(MMOLo);
9848   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9849       .addFrameIndex(FI)
9850       .addImm(4)
9851       .addMemOperand(MMOHi);
9852   MI.eraseFromParent(); // The pseudo instruction is gone now.
9853   return BB;
9854 }
9855 
9856 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9857                                                  MachineBasicBlock *BB) {
9858   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9859          "Unexpected instruction");
9860 
9861   MachineFunction &MF = *BB->getParent();
9862   DebugLoc DL = MI.getDebugLoc();
9863   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9864   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9865   Register DstReg = MI.getOperand(0).getReg();
9866   Register LoReg = MI.getOperand(1).getReg();
9867   Register HiReg = MI.getOperand(2).getReg();
9868   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9869   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9870 
9871   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9872   MachineMemOperand *MMOLo =
9873       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9874   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9875       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9876   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9877       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9878       .addFrameIndex(FI)
9879       .addImm(0)
9880       .addMemOperand(MMOLo);
9881   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9882       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9883       .addFrameIndex(FI)
9884       .addImm(4)
9885       .addMemOperand(MMOHi);
9886   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9887   MI.eraseFromParent(); // The pseudo instruction is gone now.
9888   return BB;
9889 }
9890 
9891 static bool isSelectPseudo(MachineInstr &MI) {
9892   switch (MI.getOpcode()) {
9893   default:
9894     return false;
9895   case RISCV::Select_GPR_Using_CC_GPR:
9896   case RISCV::Select_FPR16_Using_CC_GPR:
9897   case RISCV::Select_FPR32_Using_CC_GPR:
9898   case RISCV::Select_FPR64_Using_CC_GPR:
9899     return true;
9900   }
9901 }
9902 
9903 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9904                                         unsigned RelOpcode, unsigned EqOpcode,
9905                                         const RISCVSubtarget &Subtarget) {
9906   DebugLoc DL = MI.getDebugLoc();
9907   Register DstReg = MI.getOperand(0).getReg();
9908   Register Src1Reg = MI.getOperand(1).getReg();
9909   Register Src2Reg = MI.getOperand(2).getReg();
9910   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9911   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9912   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9913 
9914   // Save the current FFLAGS.
9915   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9916 
9917   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9918                  .addReg(Src1Reg)
9919                  .addReg(Src2Reg);
9920   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9921     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9922 
9923   // Restore the FFLAGS.
9924   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9925       .addReg(SavedFFlags, RegState::Kill);
9926 
9927   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9928   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9929                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9930                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9931   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9932     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9933 
9934   // Erase the pseudoinstruction.
9935   MI.eraseFromParent();
9936   return BB;
9937 }
9938 
9939 static MachineBasicBlock *
9940 EmitLoweredCascadedSelect(MachineInstr &First, MachineInstr &Second,
9941                           MachineBasicBlock *ThisMBB,
9942                           const RISCVSubtarget &Subtarget) {
9943   // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5)
9944   // Without this, custom-inserter would have generated:
9945   //
9946   //   A
9947   //   | \
9948   //   |  B
9949   //   | /
9950   //   C
9951   //   | \
9952   //   |  D
9953   //   | /
9954   //   E
9955   //
9956   // A: X = ...; Y = ...
9957   // B: empty
9958   // C: Z = PHI [X, A], [Y, B]
9959   // D: empty
9960   // E: PHI [X, C], [Z, D]
9961   //
9962   // If we lower both Select_FPRX_ in a single step, we can instead generate:
9963   //
9964   //   A
9965   //   | \
9966   //   |  C
9967   //   | /|
9968   //   |/ |
9969   //   |  |
9970   //   |  D
9971   //   | /
9972   //   E
9973   //
9974   // A: X = ...; Y = ...
9975   // D: empty
9976   // E: PHI [X, A], [X, C], [Y, D]
9977 
9978   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9979   const DebugLoc &DL = First.getDebugLoc();
9980   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
9981   MachineFunction *F = ThisMBB->getParent();
9982   MachineBasicBlock *FirstMBB = F->CreateMachineBasicBlock(LLVM_BB);
9983   MachineBasicBlock *SecondMBB = F->CreateMachineBasicBlock(LLVM_BB);
9984   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9985   MachineFunction::iterator It = ++ThisMBB->getIterator();
9986   F->insert(It, FirstMBB);
9987   F->insert(It, SecondMBB);
9988   F->insert(It, SinkMBB);
9989 
9990   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
9991   SinkMBB->splice(SinkMBB->begin(), ThisMBB,
9992                   std::next(MachineBasicBlock::iterator(First)),
9993                   ThisMBB->end());
9994   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
9995 
9996   // Fallthrough block for ThisMBB.
9997   ThisMBB->addSuccessor(FirstMBB);
9998   // Fallthrough block for FirstMBB.
9999   FirstMBB->addSuccessor(SecondMBB);
10000   ThisMBB->addSuccessor(SinkMBB);
10001   FirstMBB->addSuccessor(SinkMBB);
10002   // This is fallthrough.
10003   SecondMBB->addSuccessor(SinkMBB);
10004 
10005   auto FirstCC = static_cast<RISCVCC::CondCode>(First.getOperand(3).getImm());
10006   Register FLHS = First.getOperand(1).getReg();
10007   Register FRHS = First.getOperand(2).getReg();
10008   // Insert appropriate branch.
10009   BuildMI(FirstMBB, DL, TII.getBrCond(FirstCC))
10010       .addReg(FLHS)
10011       .addReg(FRHS)
10012       .addMBB(SinkMBB);
10013 
10014   Register SLHS = Second.getOperand(1).getReg();
10015   Register SRHS = Second.getOperand(2).getReg();
10016   Register Op1Reg4 = First.getOperand(4).getReg();
10017   Register Op1Reg5 = First.getOperand(5).getReg();
10018 
10019   auto SecondCC = static_cast<RISCVCC::CondCode>(Second.getOperand(3).getImm());
10020   // Insert appropriate branch.
10021   BuildMI(ThisMBB, DL, TII.getBrCond(SecondCC))
10022       .addReg(SLHS)
10023       .addReg(SRHS)
10024       .addMBB(SinkMBB);
10025 
10026   Register DestReg = Second.getOperand(0).getReg();
10027   Register Op2Reg4 = Second.getOperand(4).getReg();
10028   BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII.get(RISCV::PHI), DestReg)
10029       .addReg(Op2Reg4)
10030       .addMBB(ThisMBB)
10031       .addReg(Op1Reg4)
10032       .addMBB(FirstMBB)
10033       .addReg(Op1Reg5)
10034       .addMBB(SecondMBB);
10035 
10036   // Now remove the Select_FPRX_s.
10037   First.eraseFromParent();
10038   Second.eraseFromParent();
10039   return SinkMBB;
10040 }
10041 
10042 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
10043                                            MachineBasicBlock *BB,
10044                                            const RISCVSubtarget &Subtarget) {
10045   // To "insert" Select_* instructions, we actually have to insert the triangle
10046   // control-flow pattern.  The incoming instructions know the destination vreg
10047   // to set, the condition code register to branch on, the true/false values to
10048   // select between, and the condcode to use to select the appropriate branch.
10049   //
10050   // We produce the following control flow:
10051   //     HeadMBB
10052   //     |  \
10053   //     |  IfFalseMBB
10054   //     | /
10055   //    TailMBB
10056   //
10057   // When we find a sequence of selects we attempt to optimize their emission
10058   // by sharing the control flow. Currently we only handle cases where we have
10059   // multiple selects with the exact same condition (same LHS, RHS and CC).
10060   // The selects may be interleaved with other instructions if the other
10061   // instructions meet some requirements we deem safe:
10062   // - They are debug instructions. Otherwise,
10063   // - They do not have side-effects, do not access memory and their inputs do
10064   //   not depend on the results of the select pseudo-instructions.
10065   // The TrueV/FalseV operands of the selects cannot depend on the result of
10066   // previous selects in the sequence.
10067   // These conditions could be further relaxed. See the X86 target for a
10068   // related approach and more information.
10069   //
10070   // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5))
10071   // is checked here and handled by a separate function -
10072   // EmitLoweredCascadedSelect.
10073   Register LHS = MI.getOperand(1).getReg();
10074   Register RHS = MI.getOperand(2).getReg();
10075   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
10076 
10077   SmallVector<MachineInstr *, 4> SelectDebugValues;
10078   SmallSet<Register, 4> SelectDests;
10079   SelectDests.insert(MI.getOperand(0).getReg());
10080 
10081   MachineInstr *LastSelectPseudo = &MI;
10082   auto Next = next_nodbg(MI.getIterator(), BB->instr_end());
10083   if (MI.getOpcode() != RISCV::Select_GPR_Using_CC_GPR && Next != BB->end() &&
10084       Next->getOpcode() == MI.getOpcode() &&
10085       Next->getOperand(5).getReg() == MI.getOperand(0).getReg() &&
10086       Next->getOperand(5).isKill()) {
10087     return EmitLoweredCascadedSelect(MI, *Next, BB, Subtarget);
10088   }
10089 
10090   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
10091        SequenceMBBI != E; ++SequenceMBBI) {
10092     if (SequenceMBBI->isDebugInstr())
10093       continue;
10094     if (isSelectPseudo(*SequenceMBBI)) {
10095       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
10096           SequenceMBBI->getOperand(2).getReg() != RHS ||
10097           SequenceMBBI->getOperand(3).getImm() != CC ||
10098           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
10099           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
10100         break;
10101       LastSelectPseudo = &*SequenceMBBI;
10102       SequenceMBBI->collectDebugValues(SelectDebugValues);
10103       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
10104       continue;
10105     }
10106     if (SequenceMBBI->hasUnmodeledSideEffects() ||
10107         SequenceMBBI->mayLoadOrStore())
10108       break;
10109     if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
10110           return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
10111         }))
10112       break;
10113   }
10114 
10115   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
10116   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10117   DebugLoc DL = MI.getDebugLoc();
10118   MachineFunction::iterator I = ++BB->getIterator();
10119 
10120   MachineBasicBlock *HeadMBB = BB;
10121   MachineFunction *F = BB->getParent();
10122   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
10123   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
10124 
10125   F->insert(I, IfFalseMBB);
10126   F->insert(I, TailMBB);
10127 
10128   // Transfer debug instructions associated with the selects to TailMBB.
10129   for (MachineInstr *DebugInstr : SelectDebugValues) {
10130     TailMBB->push_back(DebugInstr->removeFromParent());
10131   }
10132 
10133   // Move all instructions after the sequence to TailMBB.
10134   TailMBB->splice(TailMBB->end(), HeadMBB,
10135                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
10136   // Update machine-CFG edges by transferring all successors of the current
10137   // block to the new block which will contain the Phi nodes for the selects.
10138   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
10139   // Set the successors for HeadMBB.
10140   HeadMBB->addSuccessor(IfFalseMBB);
10141   HeadMBB->addSuccessor(TailMBB);
10142 
10143   // Insert appropriate branch.
10144   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
10145     .addReg(LHS)
10146     .addReg(RHS)
10147     .addMBB(TailMBB);
10148 
10149   // IfFalseMBB just falls through to TailMBB.
10150   IfFalseMBB->addSuccessor(TailMBB);
10151 
10152   // Create PHIs for all of the select pseudo-instructions.
10153   auto SelectMBBI = MI.getIterator();
10154   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
10155   auto InsertionPoint = TailMBB->begin();
10156   while (SelectMBBI != SelectEnd) {
10157     auto Next = std::next(SelectMBBI);
10158     if (isSelectPseudo(*SelectMBBI)) {
10159       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
10160       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
10161               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
10162           .addReg(SelectMBBI->getOperand(4).getReg())
10163           .addMBB(HeadMBB)
10164           .addReg(SelectMBBI->getOperand(5).getReg())
10165           .addMBB(IfFalseMBB);
10166       SelectMBBI->eraseFromParent();
10167     }
10168     SelectMBBI = Next;
10169   }
10170 
10171   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
10172   return TailMBB;
10173 }
10174 
10175 MachineBasicBlock *
10176 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10177                                                  MachineBasicBlock *BB) const {
10178   switch (MI.getOpcode()) {
10179   default:
10180     llvm_unreachable("Unexpected instr type to insert");
10181   case RISCV::ReadCycleWide:
10182     assert(!Subtarget.is64Bit() &&
10183            "ReadCycleWrite is only to be used on riscv32");
10184     return emitReadCycleWidePseudo(MI, BB);
10185   case RISCV::Select_GPR_Using_CC_GPR:
10186   case RISCV::Select_FPR16_Using_CC_GPR:
10187   case RISCV::Select_FPR32_Using_CC_GPR:
10188   case RISCV::Select_FPR64_Using_CC_GPR:
10189     return emitSelectPseudo(MI, BB, Subtarget);
10190   case RISCV::BuildPairF64Pseudo:
10191     return emitBuildPairF64Pseudo(MI, BB);
10192   case RISCV::SplitF64Pseudo:
10193     return emitSplitF64Pseudo(MI, BB);
10194   case RISCV::PseudoQuietFLE_H:
10195     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
10196   case RISCV::PseudoQuietFLT_H:
10197     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
10198   case RISCV::PseudoQuietFLE_S:
10199     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
10200   case RISCV::PseudoQuietFLT_S:
10201     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
10202   case RISCV::PseudoQuietFLE_D:
10203     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
10204   case RISCV::PseudoQuietFLT_D:
10205     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
10206   }
10207 }
10208 
10209 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10210                                                         SDNode *Node) const {
10211   // Add FRM dependency to any instructions with dynamic rounding mode.
10212   unsigned Opc = MI.getOpcode();
10213   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
10214   if (Idx < 0)
10215     return;
10216   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
10217     return;
10218   // If the instruction already reads FRM, don't add another read.
10219   if (MI.readsRegister(RISCV::FRM))
10220     return;
10221   MI.addOperand(
10222       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
10223 }
10224 
10225 // Calling Convention Implementation.
10226 // The expectations for frontend ABI lowering vary from target to target.
10227 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
10228 // details, but this is a longer term goal. For now, we simply try to keep the
10229 // role of the frontend as simple and well-defined as possible. The rules can
10230 // be summarised as:
10231 // * Never split up large scalar arguments. We handle them here.
10232 // * If a hardfloat calling convention is being used, and the struct may be
10233 // passed in a pair of registers (fp+fp, int+fp), and both registers are
10234 // available, then pass as two separate arguments. If either the GPRs or FPRs
10235 // are exhausted, then pass according to the rule below.
10236 // * If a struct could never be passed in registers or directly in a stack
10237 // slot (as it is larger than 2*XLEN and the floating point rules don't
10238 // apply), then pass it using a pointer with the byval attribute.
10239 // * If a struct is less than 2*XLEN, then coerce to either a two-element
10240 // word-sized array or a 2*XLEN scalar (depending on alignment).
10241 // * The frontend can determine whether a struct is returned by reference or
10242 // not based on its size and fields. If it will be returned by reference, the
10243 // frontend must modify the prototype so a pointer with the sret annotation is
10244 // passed as the first argument. This is not necessary for large scalar
10245 // returns.
10246 // * Struct return values and varargs should be coerced to structs containing
10247 // register-size fields in the same situations they would be for fixed
10248 // arguments.
10249 
10250 static const MCPhysReg ArgGPRs[] = {
10251   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
10252   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
10253 };
10254 static const MCPhysReg ArgFPR16s[] = {
10255   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
10256   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
10257 };
10258 static const MCPhysReg ArgFPR32s[] = {
10259   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
10260   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
10261 };
10262 static const MCPhysReg ArgFPR64s[] = {
10263   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
10264   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
10265 };
10266 // This is an interim calling convention and it may be changed in the future.
10267 static const MCPhysReg ArgVRs[] = {
10268     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
10269     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
10270     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
10271 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
10272                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
10273                                      RISCV::V20M2, RISCV::V22M2};
10274 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
10275                                      RISCV::V20M4};
10276 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
10277 
10278 // Pass a 2*XLEN argument that has been split into two XLEN values through
10279 // registers or the stack as necessary.
10280 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
10281                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
10282                                 MVT ValVT2, MVT LocVT2,
10283                                 ISD::ArgFlagsTy ArgFlags2) {
10284   unsigned XLenInBytes = XLen / 8;
10285   if (Register Reg = State.AllocateReg(ArgGPRs)) {
10286     // At least one half can be passed via register.
10287     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
10288                                      VA1.getLocVT(), CCValAssign::Full));
10289   } else {
10290     // Both halves must be passed on the stack, with proper alignment.
10291     Align StackAlign =
10292         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
10293     State.addLoc(
10294         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
10295                             State.AllocateStack(XLenInBytes, StackAlign),
10296                             VA1.getLocVT(), CCValAssign::Full));
10297     State.addLoc(CCValAssign::getMem(
10298         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
10299         LocVT2, CCValAssign::Full));
10300     return false;
10301   }
10302 
10303   if (Register Reg = State.AllocateReg(ArgGPRs)) {
10304     // The second half can also be passed via register.
10305     State.addLoc(
10306         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
10307   } else {
10308     // The second half is passed via the stack, without additional alignment.
10309     State.addLoc(CCValAssign::getMem(
10310         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
10311         LocVT2, CCValAssign::Full));
10312   }
10313 
10314   return false;
10315 }
10316 
10317 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
10318                                Optional<unsigned> FirstMaskArgument,
10319                                CCState &State, const RISCVTargetLowering &TLI) {
10320   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
10321   if (RC == &RISCV::VRRegClass) {
10322     // Assign the first mask argument to V0.
10323     // This is an interim calling convention and it may be changed in the
10324     // future.
10325     if (FirstMaskArgument && ValNo == *FirstMaskArgument)
10326       return State.AllocateReg(RISCV::V0);
10327     return State.AllocateReg(ArgVRs);
10328   }
10329   if (RC == &RISCV::VRM2RegClass)
10330     return State.AllocateReg(ArgVRM2s);
10331   if (RC == &RISCV::VRM4RegClass)
10332     return State.AllocateReg(ArgVRM4s);
10333   if (RC == &RISCV::VRM8RegClass)
10334     return State.AllocateReg(ArgVRM8s);
10335   llvm_unreachable("Unhandled register class for ValueType");
10336 }
10337 
10338 // Implements the RISC-V calling convention. Returns true upon failure.
10339 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
10340                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
10341                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
10342                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
10343                      Optional<unsigned> FirstMaskArgument) {
10344   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
10345   assert(XLen == 32 || XLen == 64);
10346   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
10347 
10348   // Any return value split in to more than two values can't be returned
10349   // directly. Vectors are returned via the available vector registers.
10350   if (!LocVT.isVector() && IsRet && ValNo > 1)
10351     return true;
10352 
10353   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
10354   // variadic argument, or if no F16/F32 argument registers are available.
10355   bool UseGPRForF16_F32 = true;
10356   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
10357   // variadic argument, or if no F64 argument registers are available.
10358   bool UseGPRForF64 = true;
10359 
10360   switch (ABI) {
10361   default:
10362     llvm_unreachable("Unexpected ABI");
10363   case RISCVABI::ABI_ILP32:
10364   case RISCVABI::ABI_LP64:
10365     break;
10366   case RISCVABI::ABI_ILP32F:
10367   case RISCVABI::ABI_LP64F:
10368     UseGPRForF16_F32 = !IsFixed;
10369     break;
10370   case RISCVABI::ABI_ILP32D:
10371   case RISCVABI::ABI_LP64D:
10372     UseGPRForF16_F32 = !IsFixed;
10373     UseGPRForF64 = !IsFixed;
10374     break;
10375   }
10376 
10377   // FPR16, FPR32, and FPR64 alias each other.
10378   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
10379     UseGPRForF16_F32 = true;
10380     UseGPRForF64 = true;
10381   }
10382 
10383   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
10384   // similar local variables rather than directly checking against the target
10385   // ABI.
10386 
10387   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
10388     LocVT = XLenVT;
10389     LocInfo = CCValAssign::BCvt;
10390   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
10391     LocVT = MVT::i64;
10392     LocInfo = CCValAssign::BCvt;
10393   }
10394 
10395   // If this is a variadic argument, the RISC-V calling convention requires
10396   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
10397   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
10398   // be used regardless of whether the original argument was split during
10399   // legalisation or not. The argument will not be passed by registers if the
10400   // original type is larger than 2*XLEN, so the register alignment rule does
10401   // not apply.
10402   unsigned TwoXLenInBytes = (2 * XLen) / 8;
10403   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
10404       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
10405     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
10406     // Skip 'odd' register if necessary.
10407     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
10408       State.AllocateReg(ArgGPRs);
10409   }
10410 
10411   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
10412   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
10413       State.getPendingArgFlags();
10414 
10415   assert(PendingLocs.size() == PendingArgFlags.size() &&
10416          "PendingLocs and PendingArgFlags out of sync");
10417 
10418   // Handle passing f64 on RV32D with a soft float ABI or when floating point
10419   // registers are exhausted.
10420   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
10421     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
10422            "Can't lower f64 if it is split");
10423     // Depending on available argument GPRS, f64 may be passed in a pair of
10424     // GPRs, split between a GPR and the stack, or passed completely on the
10425     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
10426     // cases.
10427     Register Reg = State.AllocateReg(ArgGPRs);
10428     LocVT = MVT::i32;
10429     if (!Reg) {
10430       unsigned StackOffset = State.AllocateStack(8, Align(8));
10431       State.addLoc(
10432           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10433       return false;
10434     }
10435     if (!State.AllocateReg(ArgGPRs))
10436       State.AllocateStack(4, Align(4));
10437     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10438     return false;
10439   }
10440 
10441   // Fixed-length vectors are located in the corresponding scalable-vector
10442   // container types.
10443   if (ValVT.isFixedLengthVector())
10444     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10445 
10446   // Split arguments might be passed indirectly, so keep track of the pending
10447   // values. Split vectors are passed via a mix of registers and indirectly, so
10448   // treat them as we would any other argument.
10449   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
10450     LocVT = XLenVT;
10451     LocInfo = CCValAssign::Indirect;
10452     PendingLocs.push_back(
10453         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
10454     PendingArgFlags.push_back(ArgFlags);
10455     if (!ArgFlags.isSplitEnd()) {
10456       return false;
10457     }
10458   }
10459 
10460   // If the split argument only had two elements, it should be passed directly
10461   // in registers or on the stack.
10462   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
10463       PendingLocs.size() <= 2) {
10464     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
10465     // Apply the normal calling convention rules to the first half of the
10466     // split argument.
10467     CCValAssign VA = PendingLocs[0];
10468     ISD::ArgFlagsTy AF = PendingArgFlags[0];
10469     PendingLocs.clear();
10470     PendingArgFlags.clear();
10471     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
10472                                ArgFlags);
10473   }
10474 
10475   // Allocate to a register if possible, or else a stack slot.
10476   Register Reg;
10477   unsigned StoreSizeBytes = XLen / 8;
10478   Align StackAlign = Align(XLen / 8);
10479 
10480   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
10481     Reg = State.AllocateReg(ArgFPR16s);
10482   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
10483     Reg = State.AllocateReg(ArgFPR32s);
10484   else if (ValVT == MVT::f64 && !UseGPRForF64)
10485     Reg = State.AllocateReg(ArgFPR64s);
10486   else if (ValVT.isVector()) {
10487     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
10488     if (!Reg) {
10489       // For return values, the vector must be passed fully via registers or
10490       // via the stack.
10491       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
10492       // but we're using all of them.
10493       if (IsRet)
10494         return true;
10495       // Try using a GPR to pass the address
10496       if ((Reg = State.AllocateReg(ArgGPRs))) {
10497         LocVT = XLenVT;
10498         LocInfo = CCValAssign::Indirect;
10499       } else if (ValVT.isScalableVector()) {
10500         LocVT = XLenVT;
10501         LocInfo = CCValAssign::Indirect;
10502       } else {
10503         // Pass fixed-length vectors on the stack.
10504         LocVT = ValVT;
10505         StoreSizeBytes = ValVT.getStoreSize();
10506         // Align vectors to their element sizes, being careful for vXi1
10507         // vectors.
10508         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10509       }
10510     }
10511   } else {
10512     Reg = State.AllocateReg(ArgGPRs);
10513   }
10514 
10515   unsigned StackOffset =
10516       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
10517 
10518   // If we reach this point and PendingLocs is non-empty, we must be at the
10519   // end of a split argument that must be passed indirectly.
10520   if (!PendingLocs.empty()) {
10521     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
10522     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
10523 
10524     for (auto &It : PendingLocs) {
10525       if (Reg)
10526         It.convertToReg(Reg);
10527       else
10528         It.convertToMem(StackOffset);
10529       State.addLoc(It);
10530     }
10531     PendingLocs.clear();
10532     PendingArgFlags.clear();
10533     return false;
10534   }
10535 
10536   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
10537           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
10538          "Expected an XLenVT or vector types at this stage");
10539 
10540   if (Reg) {
10541     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10542     return false;
10543   }
10544 
10545   // When a floating-point value is passed on the stack, no bit-conversion is
10546   // needed.
10547   if (ValVT.isFloatingPoint()) {
10548     LocVT = ValVT;
10549     LocInfo = CCValAssign::Full;
10550   }
10551   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10552   return false;
10553 }
10554 
10555 template <typename ArgTy>
10556 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
10557   for (const auto &ArgIdx : enumerate(Args)) {
10558     MVT ArgVT = ArgIdx.value().VT;
10559     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
10560       return ArgIdx.index();
10561   }
10562   return None;
10563 }
10564 
10565 void RISCVTargetLowering::analyzeInputArgs(
10566     MachineFunction &MF, CCState &CCInfo,
10567     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
10568     RISCVCCAssignFn Fn) const {
10569   unsigned NumArgs = Ins.size();
10570   FunctionType *FType = MF.getFunction().getFunctionType();
10571 
10572   Optional<unsigned> FirstMaskArgument;
10573   if (Subtarget.hasVInstructions())
10574     FirstMaskArgument = preAssignMask(Ins);
10575 
10576   for (unsigned i = 0; i != NumArgs; ++i) {
10577     MVT ArgVT = Ins[i].VT;
10578     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
10579 
10580     Type *ArgTy = nullptr;
10581     if (IsRet)
10582       ArgTy = FType->getReturnType();
10583     else if (Ins[i].isOrigArg())
10584       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
10585 
10586     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10587     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10588            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
10589            FirstMaskArgument)) {
10590       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
10591                         << EVT(ArgVT).getEVTString() << '\n');
10592       llvm_unreachable(nullptr);
10593     }
10594   }
10595 }
10596 
10597 void RISCVTargetLowering::analyzeOutputArgs(
10598     MachineFunction &MF, CCState &CCInfo,
10599     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
10600     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
10601   unsigned NumArgs = Outs.size();
10602 
10603   Optional<unsigned> FirstMaskArgument;
10604   if (Subtarget.hasVInstructions())
10605     FirstMaskArgument = preAssignMask(Outs);
10606 
10607   for (unsigned i = 0; i != NumArgs; i++) {
10608     MVT ArgVT = Outs[i].VT;
10609     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10610     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
10611 
10612     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10613     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10614            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
10615            FirstMaskArgument)) {
10616       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
10617                         << EVT(ArgVT).getEVTString() << "\n");
10618       llvm_unreachable(nullptr);
10619     }
10620   }
10621 }
10622 
10623 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
10624 // values.
10625 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
10626                                    const CCValAssign &VA, const SDLoc &DL,
10627                                    const RISCVSubtarget &Subtarget) {
10628   switch (VA.getLocInfo()) {
10629   default:
10630     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10631   case CCValAssign::Full:
10632     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
10633       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
10634     break;
10635   case CCValAssign::BCvt:
10636     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10637       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
10638     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10639       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
10640     else
10641       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
10642     break;
10643   }
10644   return Val;
10645 }
10646 
10647 // The caller is responsible for loading the full value if the argument is
10648 // passed with CCValAssign::Indirect.
10649 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
10650                                 const CCValAssign &VA, const SDLoc &DL,
10651                                 const RISCVTargetLowering &TLI) {
10652   MachineFunction &MF = DAG.getMachineFunction();
10653   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10654   EVT LocVT = VA.getLocVT();
10655   SDValue Val;
10656   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
10657   Register VReg = RegInfo.createVirtualRegister(RC);
10658   RegInfo.addLiveIn(VA.getLocReg(), VReg);
10659   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
10660 
10661   if (VA.getLocInfo() == CCValAssign::Indirect)
10662     return Val;
10663 
10664   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
10665 }
10666 
10667 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
10668                                    const CCValAssign &VA, const SDLoc &DL,
10669                                    const RISCVSubtarget &Subtarget) {
10670   EVT LocVT = VA.getLocVT();
10671 
10672   switch (VA.getLocInfo()) {
10673   default:
10674     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10675   case CCValAssign::Full:
10676     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
10677       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
10678     break;
10679   case CCValAssign::BCvt:
10680     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10681       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
10682     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10683       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
10684     else
10685       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
10686     break;
10687   }
10688   return Val;
10689 }
10690 
10691 // The caller is responsible for loading the full value if the argument is
10692 // passed with CCValAssign::Indirect.
10693 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
10694                                 const CCValAssign &VA, const SDLoc &DL) {
10695   MachineFunction &MF = DAG.getMachineFunction();
10696   MachineFrameInfo &MFI = MF.getFrameInfo();
10697   EVT LocVT = VA.getLocVT();
10698   EVT ValVT = VA.getValVT();
10699   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
10700   if (ValVT.isScalableVector()) {
10701     // When the value is a scalable vector, we save the pointer which points to
10702     // the scalable vector value in the stack. The ValVT will be the pointer
10703     // type, instead of the scalable vector type.
10704     ValVT = LocVT;
10705   }
10706   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
10707                                  /*IsImmutable=*/true);
10708   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
10709   SDValue Val;
10710 
10711   ISD::LoadExtType ExtType;
10712   switch (VA.getLocInfo()) {
10713   default:
10714     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10715   case CCValAssign::Full:
10716   case CCValAssign::Indirect:
10717   case CCValAssign::BCvt:
10718     ExtType = ISD::NON_EXTLOAD;
10719     break;
10720   }
10721   Val = DAG.getExtLoad(
10722       ExtType, DL, LocVT, Chain, FIN,
10723       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
10724   return Val;
10725 }
10726 
10727 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
10728                                        const CCValAssign &VA, const SDLoc &DL) {
10729   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
10730          "Unexpected VA");
10731   MachineFunction &MF = DAG.getMachineFunction();
10732   MachineFrameInfo &MFI = MF.getFrameInfo();
10733   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10734 
10735   if (VA.isMemLoc()) {
10736     // f64 is passed on the stack.
10737     int FI =
10738         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
10739     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10740     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
10741                        MachinePointerInfo::getFixedStack(MF, FI));
10742   }
10743 
10744   assert(VA.isRegLoc() && "Expected register VA assignment");
10745 
10746   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10747   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
10748   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
10749   SDValue Hi;
10750   if (VA.getLocReg() == RISCV::X17) {
10751     // Second half of f64 is passed on the stack.
10752     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
10753     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10754     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10755                      MachinePointerInfo::getFixedStack(MF, FI));
10756   } else {
10757     // Second half of f64 is passed in another GPR.
10758     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10759     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10760     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10761   }
10762   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10763 }
10764 
10765 // FastCC has less than 1% performance improvement for some particular
10766 // benchmark. But theoretically, it may has benenfit for some cases.
10767 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10768                             unsigned ValNo, MVT ValVT, MVT LocVT,
10769                             CCValAssign::LocInfo LocInfo,
10770                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10771                             bool IsFixed, bool IsRet, Type *OrigTy,
10772                             const RISCVTargetLowering &TLI,
10773                             Optional<unsigned> FirstMaskArgument) {
10774 
10775   // X5 and X6 might be used for save-restore libcall.
10776   static const MCPhysReg GPRList[] = {
10777       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10778       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10779       RISCV::X29, RISCV::X30, RISCV::X31};
10780 
10781   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10782     if (unsigned Reg = State.AllocateReg(GPRList)) {
10783       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10784       return false;
10785     }
10786   }
10787 
10788   if (LocVT == MVT::f16) {
10789     static const MCPhysReg FPR16List[] = {
10790         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10791         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10792         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10793         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10794     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10795       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10796       return false;
10797     }
10798   }
10799 
10800   if (LocVT == MVT::f32) {
10801     static const MCPhysReg FPR32List[] = {
10802         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10803         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10804         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10805         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10806     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10807       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10808       return false;
10809     }
10810   }
10811 
10812   if (LocVT == MVT::f64) {
10813     static const MCPhysReg FPR64List[] = {
10814         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10815         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10816         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10817         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10818     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10819       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10820       return false;
10821     }
10822   }
10823 
10824   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10825     unsigned Offset4 = State.AllocateStack(4, Align(4));
10826     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10827     return false;
10828   }
10829 
10830   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10831     unsigned Offset5 = State.AllocateStack(8, Align(8));
10832     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10833     return false;
10834   }
10835 
10836   if (LocVT.isVector()) {
10837     if (unsigned Reg =
10838             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10839       // Fixed-length vectors are located in the corresponding scalable-vector
10840       // container types.
10841       if (ValVT.isFixedLengthVector())
10842         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10843       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10844     } else {
10845       // Try and pass the address via a "fast" GPR.
10846       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10847         LocInfo = CCValAssign::Indirect;
10848         LocVT = TLI.getSubtarget().getXLenVT();
10849         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10850       } else if (ValVT.isFixedLengthVector()) {
10851         auto StackAlign =
10852             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10853         unsigned StackOffset =
10854             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10855         State.addLoc(
10856             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10857       } else {
10858         // Can't pass scalable vectors on the stack.
10859         return true;
10860       }
10861     }
10862 
10863     return false;
10864   }
10865 
10866   return true; // CC didn't match.
10867 }
10868 
10869 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10870                          CCValAssign::LocInfo LocInfo,
10871                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10872 
10873   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10874     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10875     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10876     static const MCPhysReg GPRList[] = {
10877         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10878         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10879     if (unsigned Reg = State.AllocateReg(GPRList)) {
10880       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10881       return false;
10882     }
10883   }
10884 
10885   if (LocVT == MVT::f32) {
10886     // Pass in STG registers: F1, ..., F6
10887     //                        fs0 ... fs5
10888     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10889                                           RISCV::F18_F, RISCV::F19_F,
10890                                           RISCV::F20_F, RISCV::F21_F};
10891     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10892       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10893       return false;
10894     }
10895   }
10896 
10897   if (LocVT == MVT::f64) {
10898     // Pass in STG registers: D1, ..., D6
10899     //                        fs6 ... fs11
10900     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10901                                           RISCV::F24_D, RISCV::F25_D,
10902                                           RISCV::F26_D, RISCV::F27_D};
10903     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10904       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10905       return false;
10906     }
10907   }
10908 
10909   report_fatal_error("No registers left in GHC calling convention");
10910   return true;
10911 }
10912 
10913 // Transform physical registers into virtual registers.
10914 SDValue RISCVTargetLowering::LowerFormalArguments(
10915     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10916     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10917     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10918 
10919   MachineFunction &MF = DAG.getMachineFunction();
10920 
10921   switch (CallConv) {
10922   default:
10923     report_fatal_error("Unsupported calling convention");
10924   case CallingConv::C:
10925   case CallingConv::Fast:
10926     break;
10927   case CallingConv::GHC:
10928     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10929         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10930       report_fatal_error(
10931         "GHC calling convention requires the F and D instruction set extensions");
10932   }
10933 
10934   const Function &Func = MF.getFunction();
10935   if (Func.hasFnAttribute("interrupt")) {
10936     if (!Func.arg_empty())
10937       report_fatal_error(
10938         "Functions with the interrupt attribute cannot have arguments!");
10939 
10940     StringRef Kind =
10941       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10942 
10943     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10944       report_fatal_error(
10945         "Function interrupt attribute argument not supported!");
10946   }
10947 
10948   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10949   MVT XLenVT = Subtarget.getXLenVT();
10950   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10951   // Used with vargs to acumulate store chains.
10952   std::vector<SDValue> OutChains;
10953 
10954   // Assign locations to all of the incoming arguments.
10955   SmallVector<CCValAssign, 16> ArgLocs;
10956   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10957 
10958   if (CallConv == CallingConv::GHC)
10959     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10960   else
10961     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10962                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10963                                                    : CC_RISCV);
10964 
10965   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10966     CCValAssign &VA = ArgLocs[i];
10967     SDValue ArgValue;
10968     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10969     // case.
10970     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10971       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10972     else if (VA.isRegLoc())
10973       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10974     else
10975       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10976 
10977     if (VA.getLocInfo() == CCValAssign::Indirect) {
10978       // If the original argument was split and passed by reference (e.g. i128
10979       // on RV32), we need to load all parts of it here (using the same
10980       // address). Vectors may be partly split to registers and partly to the
10981       // stack, in which case the base address is partly offset and subsequent
10982       // stores are relative to that.
10983       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10984                                    MachinePointerInfo()));
10985       unsigned ArgIndex = Ins[i].OrigArgIndex;
10986       unsigned ArgPartOffset = Ins[i].PartOffset;
10987       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10988       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10989         CCValAssign &PartVA = ArgLocs[i + 1];
10990         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10991         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10992         if (PartVA.getValVT().isScalableVector())
10993           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10994         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10995         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10996                                      MachinePointerInfo()));
10997         ++i;
10998       }
10999       continue;
11000     }
11001     InVals.push_back(ArgValue);
11002   }
11003 
11004   if (IsVarArg) {
11005     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
11006     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
11007     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
11008     MachineFrameInfo &MFI = MF.getFrameInfo();
11009     MachineRegisterInfo &RegInfo = MF.getRegInfo();
11010     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
11011 
11012     // Offset of the first variable argument from stack pointer, and size of
11013     // the vararg save area. For now, the varargs save area is either zero or
11014     // large enough to hold a0-a7.
11015     int VaArgOffset, VarArgsSaveSize;
11016 
11017     // If all registers are allocated, then all varargs must be passed on the
11018     // stack and we don't need to save any argregs.
11019     if (ArgRegs.size() == Idx) {
11020       VaArgOffset = CCInfo.getNextStackOffset();
11021       VarArgsSaveSize = 0;
11022     } else {
11023       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
11024       VaArgOffset = -VarArgsSaveSize;
11025     }
11026 
11027     // Record the frame index of the first variable argument
11028     // which is a value necessary to VASTART.
11029     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
11030     RVFI->setVarArgsFrameIndex(FI);
11031 
11032     // If saving an odd number of registers then create an extra stack slot to
11033     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
11034     // offsets to even-numbered registered remain 2*XLEN-aligned.
11035     if (Idx % 2) {
11036       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
11037       VarArgsSaveSize += XLenInBytes;
11038     }
11039 
11040     // Copy the integer registers that may have been used for passing varargs
11041     // to the vararg save area.
11042     for (unsigned I = Idx; I < ArgRegs.size();
11043          ++I, VaArgOffset += XLenInBytes) {
11044       const Register Reg = RegInfo.createVirtualRegister(RC);
11045       RegInfo.addLiveIn(ArgRegs[I], Reg);
11046       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
11047       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
11048       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
11049       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
11050                                    MachinePointerInfo::getFixedStack(MF, FI));
11051       cast<StoreSDNode>(Store.getNode())
11052           ->getMemOperand()
11053           ->setValue((Value *)nullptr);
11054       OutChains.push_back(Store);
11055     }
11056     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
11057   }
11058 
11059   // All stores are grouped in one node to allow the matching between
11060   // the size of Ins and InVals. This only happens for vararg functions.
11061   if (!OutChains.empty()) {
11062     OutChains.push_back(Chain);
11063     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
11064   }
11065 
11066   return Chain;
11067 }
11068 
11069 /// isEligibleForTailCallOptimization - Check whether the call is eligible
11070 /// for tail call optimization.
11071 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
11072 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
11073     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
11074     const SmallVector<CCValAssign, 16> &ArgLocs) const {
11075 
11076   auto &Callee = CLI.Callee;
11077   auto CalleeCC = CLI.CallConv;
11078   auto &Outs = CLI.Outs;
11079   auto &Caller = MF.getFunction();
11080   auto CallerCC = Caller.getCallingConv();
11081 
11082   // Exception-handling functions need a special set of instructions to
11083   // indicate a return to the hardware. Tail-calling another function would
11084   // probably break this.
11085   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
11086   // should be expanded as new function attributes are introduced.
11087   if (Caller.hasFnAttribute("interrupt"))
11088     return false;
11089 
11090   // Do not tail call opt if the stack is used to pass parameters.
11091   if (CCInfo.getNextStackOffset() != 0)
11092     return false;
11093 
11094   // Do not tail call opt if any parameters need to be passed indirectly.
11095   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
11096   // passed indirectly. So the address of the value will be passed in a
11097   // register, or if not available, then the address is put on the stack. In
11098   // order to pass indirectly, space on the stack often needs to be allocated
11099   // in order to store the value. In this case the CCInfo.getNextStackOffset()
11100   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
11101   // are passed CCValAssign::Indirect.
11102   for (auto &VA : ArgLocs)
11103     if (VA.getLocInfo() == CCValAssign::Indirect)
11104       return false;
11105 
11106   // Do not tail call opt if either caller or callee uses struct return
11107   // semantics.
11108   auto IsCallerStructRet = Caller.hasStructRetAttr();
11109   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
11110   if (IsCallerStructRet || IsCalleeStructRet)
11111     return false;
11112 
11113   // Externally-defined functions with weak linkage should not be
11114   // tail-called. The behaviour of branch instructions in this situation (as
11115   // used for tail calls) is implementation-defined, so we cannot rely on the
11116   // linker replacing the tail call with a return.
11117   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
11118     const GlobalValue *GV = G->getGlobal();
11119     if (GV->hasExternalWeakLinkage())
11120       return false;
11121   }
11122 
11123   // The callee has to preserve all registers the caller needs to preserve.
11124   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
11125   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
11126   if (CalleeCC != CallerCC) {
11127     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
11128     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
11129       return false;
11130   }
11131 
11132   // Byval parameters hand the function a pointer directly into the stack area
11133   // we want to reuse during a tail call. Working around this *is* possible
11134   // but less efficient and uglier in LowerCall.
11135   for (auto &Arg : Outs)
11136     if (Arg.Flags.isByVal())
11137       return false;
11138 
11139   return true;
11140 }
11141 
11142 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
11143   return DAG.getDataLayout().getPrefTypeAlign(
11144       VT.getTypeForEVT(*DAG.getContext()));
11145 }
11146 
11147 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
11148 // and output parameter nodes.
11149 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
11150                                        SmallVectorImpl<SDValue> &InVals) const {
11151   SelectionDAG &DAG = CLI.DAG;
11152   SDLoc &DL = CLI.DL;
11153   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
11154   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
11155   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
11156   SDValue Chain = CLI.Chain;
11157   SDValue Callee = CLI.Callee;
11158   bool &IsTailCall = CLI.IsTailCall;
11159   CallingConv::ID CallConv = CLI.CallConv;
11160   bool IsVarArg = CLI.IsVarArg;
11161   EVT PtrVT = getPointerTy(DAG.getDataLayout());
11162   MVT XLenVT = Subtarget.getXLenVT();
11163 
11164   MachineFunction &MF = DAG.getMachineFunction();
11165 
11166   // Analyze the operands of the call, assigning locations to each operand.
11167   SmallVector<CCValAssign, 16> ArgLocs;
11168   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
11169 
11170   if (CallConv == CallingConv::GHC)
11171     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
11172   else
11173     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
11174                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
11175                                                     : CC_RISCV);
11176 
11177   // Check if it's really possible to do a tail call.
11178   if (IsTailCall)
11179     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
11180 
11181   if (IsTailCall)
11182     ++NumTailCalls;
11183   else if (CLI.CB && CLI.CB->isMustTailCall())
11184     report_fatal_error("failed to perform tail call elimination on a call "
11185                        "site marked musttail");
11186 
11187   // Get a count of how many bytes are to be pushed on the stack.
11188   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
11189 
11190   // Create local copies for byval args
11191   SmallVector<SDValue, 8> ByValArgs;
11192   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
11193     ISD::ArgFlagsTy Flags = Outs[i].Flags;
11194     if (!Flags.isByVal())
11195       continue;
11196 
11197     SDValue Arg = OutVals[i];
11198     unsigned Size = Flags.getByValSize();
11199     Align Alignment = Flags.getNonZeroByValAlign();
11200 
11201     int FI =
11202         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
11203     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
11204     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
11205 
11206     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
11207                           /*IsVolatile=*/false,
11208                           /*AlwaysInline=*/false, IsTailCall,
11209                           MachinePointerInfo(), MachinePointerInfo());
11210     ByValArgs.push_back(FIPtr);
11211   }
11212 
11213   if (!IsTailCall)
11214     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
11215 
11216   // Copy argument values to their designated locations.
11217   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
11218   SmallVector<SDValue, 8> MemOpChains;
11219   SDValue StackPtr;
11220   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
11221     CCValAssign &VA = ArgLocs[i];
11222     SDValue ArgValue = OutVals[i];
11223     ISD::ArgFlagsTy Flags = Outs[i].Flags;
11224 
11225     // Handle passing f64 on RV32D with a soft float ABI as a special case.
11226     bool IsF64OnRV32DSoftABI =
11227         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
11228     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
11229       SDValue SplitF64 = DAG.getNode(
11230           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
11231       SDValue Lo = SplitF64.getValue(0);
11232       SDValue Hi = SplitF64.getValue(1);
11233 
11234       Register RegLo = VA.getLocReg();
11235       RegsToPass.push_back(std::make_pair(RegLo, Lo));
11236 
11237       if (RegLo == RISCV::X17) {
11238         // Second half of f64 is passed on the stack.
11239         // Work out the address of the stack slot.
11240         if (!StackPtr.getNode())
11241           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
11242         // Emit the store.
11243         MemOpChains.push_back(
11244             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
11245       } else {
11246         // Second half of f64 is passed in another GPR.
11247         assert(RegLo < RISCV::X31 && "Invalid register pair");
11248         Register RegHigh = RegLo + 1;
11249         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
11250       }
11251       continue;
11252     }
11253 
11254     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
11255     // as any other MemLoc.
11256 
11257     // Promote the value if needed.
11258     // For now, only handle fully promoted and indirect arguments.
11259     if (VA.getLocInfo() == CCValAssign::Indirect) {
11260       // Store the argument in a stack slot and pass its address.
11261       Align StackAlign =
11262           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
11263                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
11264       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
11265       // If the original argument was split (e.g. i128), we need
11266       // to store the required parts of it here (and pass just one address).
11267       // Vectors may be partly split to registers and partly to the stack, in
11268       // which case the base address is partly offset and subsequent stores are
11269       // relative to that.
11270       unsigned ArgIndex = Outs[i].OrigArgIndex;
11271       unsigned ArgPartOffset = Outs[i].PartOffset;
11272       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
11273       // Calculate the total size to store. We don't have access to what we're
11274       // actually storing other than performing the loop and collecting the
11275       // info.
11276       SmallVector<std::pair<SDValue, SDValue>> Parts;
11277       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
11278         SDValue PartValue = OutVals[i + 1];
11279         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
11280         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
11281         EVT PartVT = PartValue.getValueType();
11282         if (PartVT.isScalableVector())
11283           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
11284         StoredSize += PartVT.getStoreSize();
11285         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
11286         Parts.push_back(std::make_pair(PartValue, Offset));
11287         ++i;
11288       }
11289       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
11290       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
11291       MemOpChains.push_back(
11292           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
11293                        MachinePointerInfo::getFixedStack(MF, FI)));
11294       for (const auto &Part : Parts) {
11295         SDValue PartValue = Part.first;
11296         SDValue PartOffset = Part.second;
11297         SDValue Address =
11298             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
11299         MemOpChains.push_back(
11300             DAG.getStore(Chain, DL, PartValue, Address,
11301                          MachinePointerInfo::getFixedStack(MF, FI)));
11302       }
11303       ArgValue = SpillSlot;
11304     } else {
11305       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
11306     }
11307 
11308     // Use local copy if it is a byval arg.
11309     if (Flags.isByVal())
11310       ArgValue = ByValArgs[j++];
11311 
11312     if (VA.isRegLoc()) {
11313       // Queue up the argument copies and emit them at the end.
11314       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
11315     } else {
11316       assert(VA.isMemLoc() && "Argument not register or memory");
11317       assert(!IsTailCall && "Tail call not allowed if stack is used "
11318                             "for passing parameters");
11319 
11320       // Work out the address of the stack slot.
11321       if (!StackPtr.getNode())
11322         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
11323       SDValue Address =
11324           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
11325                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
11326 
11327       // Emit the store.
11328       MemOpChains.push_back(
11329           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
11330     }
11331   }
11332 
11333   // Join the stores, which are independent of one another.
11334   if (!MemOpChains.empty())
11335     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
11336 
11337   SDValue Glue;
11338 
11339   // Build a sequence of copy-to-reg nodes, chained and glued together.
11340   for (auto &Reg : RegsToPass) {
11341     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
11342     Glue = Chain.getValue(1);
11343   }
11344 
11345   // Validate that none of the argument registers have been marked as
11346   // reserved, if so report an error. Do the same for the return address if this
11347   // is not a tailcall.
11348   validateCCReservedRegs(RegsToPass, MF);
11349   if (!IsTailCall &&
11350       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
11351     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11352         MF.getFunction(),
11353         "Return address register required, but has been reserved."});
11354 
11355   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
11356   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
11357   // split it and then direct call can be matched by PseudoCALL.
11358   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
11359     const GlobalValue *GV = S->getGlobal();
11360 
11361     unsigned OpFlags = RISCVII::MO_CALL;
11362     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
11363       OpFlags = RISCVII::MO_PLT;
11364 
11365     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
11366   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
11367     unsigned OpFlags = RISCVII::MO_CALL;
11368 
11369     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
11370                                                  nullptr))
11371       OpFlags = RISCVII::MO_PLT;
11372 
11373     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
11374   }
11375 
11376   // The first call operand is the chain and the second is the target address.
11377   SmallVector<SDValue, 8> Ops;
11378   Ops.push_back(Chain);
11379   Ops.push_back(Callee);
11380 
11381   // Add argument registers to the end of the list so that they are
11382   // known live into the call.
11383   for (auto &Reg : RegsToPass)
11384     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
11385 
11386   if (!IsTailCall) {
11387     // Add a register mask operand representing the call-preserved registers.
11388     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
11389     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
11390     assert(Mask && "Missing call preserved mask for calling convention");
11391     Ops.push_back(DAG.getRegisterMask(Mask));
11392   }
11393 
11394   // Glue the call to the argument copies, if any.
11395   if (Glue.getNode())
11396     Ops.push_back(Glue);
11397 
11398   // Emit the call.
11399   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11400 
11401   if (IsTailCall) {
11402     MF.getFrameInfo().setHasTailCall();
11403     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
11404   }
11405 
11406   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
11407   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
11408   Glue = Chain.getValue(1);
11409 
11410   // Mark the end of the call, which is glued to the call itself.
11411   Chain = DAG.getCALLSEQ_END(Chain,
11412                              DAG.getConstant(NumBytes, DL, PtrVT, true),
11413                              DAG.getConstant(0, DL, PtrVT, true),
11414                              Glue, DL);
11415   Glue = Chain.getValue(1);
11416 
11417   // Assign locations to each value returned by this call.
11418   SmallVector<CCValAssign, 16> RVLocs;
11419   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
11420   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
11421 
11422   // Copy all of the result registers out of their specified physreg.
11423   for (auto &VA : RVLocs) {
11424     // Copy the value out
11425     SDValue RetValue =
11426         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
11427     // Glue the RetValue to the end of the call sequence
11428     Chain = RetValue.getValue(1);
11429     Glue = RetValue.getValue(2);
11430 
11431     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11432       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
11433       SDValue RetValue2 =
11434           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
11435       Chain = RetValue2.getValue(1);
11436       Glue = RetValue2.getValue(2);
11437       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
11438                              RetValue2);
11439     }
11440 
11441     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
11442 
11443     InVals.push_back(RetValue);
11444   }
11445 
11446   return Chain;
11447 }
11448 
11449 bool RISCVTargetLowering::CanLowerReturn(
11450     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
11451     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
11452   SmallVector<CCValAssign, 16> RVLocs;
11453   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
11454 
11455   Optional<unsigned> FirstMaskArgument;
11456   if (Subtarget.hasVInstructions())
11457     FirstMaskArgument = preAssignMask(Outs);
11458 
11459   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
11460     MVT VT = Outs[i].VT;
11461     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
11462     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
11463     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
11464                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
11465                  *this, FirstMaskArgument))
11466       return false;
11467   }
11468   return true;
11469 }
11470 
11471 SDValue
11472 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
11473                                  bool IsVarArg,
11474                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
11475                                  const SmallVectorImpl<SDValue> &OutVals,
11476                                  const SDLoc &DL, SelectionDAG &DAG) const {
11477   const MachineFunction &MF = DAG.getMachineFunction();
11478   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11479 
11480   // Stores the assignment of the return value to a location.
11481   SmallVector<CCValAssign, 16> RVLocs;
11482 
11483   // Info about the registers and stack slot.
11484   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
11485                  *DAG.getContext());
11486 
11487   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
11488                     nullptr, CC_RISCV);
11489 
11490   if (CallConv == CallingConv::GHC && !RVLocs.empty())
11491     report_fatal_error("GHC functions return void only");
11492 
11493   SDValue Glue;
11494   SmallVector<SDValue, 4> RetOps(1, Chain);
11495 
11496   // Copy the result values into the output registers.
11497   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
11498     SDValue Val = OutVals[i];
11499     CCValAssign &VA = RVLocs[i];
11500     assert(VA.isRegLoc() && "Can only return in registers!");
11501 
11502     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11503       // Handle returning f64 on RV32D with a soft float ABI.
11504       assert(VA.isRegLoc() && "Expected return via registers");
11505       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
11506                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
11507       SDValue Lo = SplitF64.getValue(0);
11508       SDValue Hi = SplitF64.getValue(1);
11509       Register RegLo = VA.getLocReg();
11510       assert(RegLo < RISCV::X31 && "Invalid register pair");
11511       Register RegHi = RegLo + 1;
11512 
11513       if (STI.isRegisterReservedByUser(RegLo) ||
11514           STI.isRegisterReservedByUser(RegHi))
11515         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11516             MF.getFunction(),
11517             "Return value register required, but has been reserved."});
11518 
11519       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
11520       Glue = Chain.getValue(1);
11521       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
11522       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
11523       Glue = Chain.getValue(1);
11524       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
11525     } else {
11526       // Handle a 'normal' return.
11527       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
11528       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
11529 
11530       if (STI.isRegisterReservedByUser(VA.getLocReg()))
11531         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11532             MF.getFunction(),
11533             "Return value register required, but has been reserved."});
11534 
11535       // Guarantee that all emitted copies are stuck together.
11536       Glue = Chain.getValue(1);
11537       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
11538     }
11539   }
11540 
11541   RetOps[0] = Chain; // Update chain.
11542 
11543   // Add the glue node if we have it.
11544   if (Glue.getNode()) {
11545     RetOps.push_back(Glue);
11546   }
11547 
11548   unsigned RetOpc = RISCVISD::RET_FLAG;
11549   // Interrupt service routines use different return instructions.
11550   const Function &Func = DAG.getMachineFunction().getFunction();
11551   if (Func.hasFnAttribute("interrupt")) {
11552     if (!Func.getReturnType()->isVoidTy())
11553       report_fatal_error(
11554           "Functions with the interrupt attribute must have void return type!");
11555 
11556     MachineFunction &MF = DAG.getMachineFunction();
11557     StringRef Kind =
11558       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
11559 
11560     if (Kind == "user")
11561       RetOpc = RISCVISD::URET_FLAG;
11562     else if (Kind == "supervisor")
11563       RetOpc = RISCVISD::SRET_FLAG;
11564     else
11565       RetOpc = RISCVISD::MRET_FLAG;
11566   }
11567 
11568   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
11569 }
11570 
11571 void RISCVTargetLowering::validateCCReservedRegs(
11572     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
11573     MachineFunction &MF) const {
11574   const Function &F = MF.getFunction();
11575   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11576 
11577   if (llvm::any_of(Regs, [&STI](auto Reg) {
11578         return STI.isRegisterReservedByUser(Reg.first);
11579       }))
11580     F.getContext().diagnose(DiagnosticInfoUnsupported{
11581         F, "Argument register required, but has been reserved."});
11582 }
11583 
11584 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11585   return CI->isTailCall();
11586 }
11587 
11588 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
11589 #define NODE_NAME_CASE(NODE)                                                   \
11590   case RISCVISD::NODE:                                                         \
11591     return "RISCVISD::" #NODE;
11592   // clang-format off
11593   switch ((RISCVISD::NodeType)Opcode) {
11594   case RISCVISD::FIRST_NUMBER:
11595     break;
11596   NODE_NAME_CASE(RET_FLAG)
11597   NODE_NAME_CASE(URET_FLAG)
11598   NODE_NAME_CASE(SRET_FLAG)
11599   NODE_NAME_CASE(MRET_FLAG)
11600   NODE_NAME_CASE(CALL)
11601   NODE_NAME_CASE(SELECT_CC)
11602   NODE_NAME_CASE(BR_CC)
11603   NODE_NAME_CASE(BuildPairF64)
11604   NODE_NAME_CASE(SplitF64)
11605   NODE_NAME_CASE(TAIL)
11606   NODE_NAME_CASE(ADD_LO)
11607   NODE_NAME_CASE(HI)
11608   NODE_NAME_CASE(LLA)
11609   NODE_NAME_CASE(ADD_TPREL)
11610   NODE_NAME_CASE(LA)
11611   NODE_NAME_CASE(LA_TLS_IE)
11612   NODE_NAME_CASE(LA_TLS_GD)
11613   NODE_NAME_CASE(MULHSU)
11614   NODE_NAME_CASE(SLLW)
11615   NODE_NAME_CASE(SRAW)
11616   NODE_NAME_CASE(SRLW)
11617   NODE_NAME_CASE(DIVW)
11618   NODE_NAME_CASE(DIVUW)
11619   NODE_NAME_CASE(REMUW)
11620   NODE_NAME_CASE(ROLW)
11621   NODE_NAME_CASE(RORW)
11622   NODE_NAME_CASE(CLZW)
11623   NODE_NAME_CASE(CTZW)
11624   NODE_NAME_CASE(FSLW)
11625   NODE_NAME_CASE(FSRW)
11626   NODE_NAME_CASE(FSL)
11627   NODE_NAME_CASE(FSR)
11628   NODE_NAME_CASE(FMV_H_X)
11629   NODE_NAME_CASE(FMV_X_ANYEXTH)
11630   NODE_NAME_CASE(FMV_X_SIGNEXTH)
11631   NODE_NAME_CASE(FMV_W_X_RV64)
11632   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
11633   NODE_NAME_CASE(FCVT_X)
11634   NODE_NAME_CASE(FCVT_XU)
11635   NODE_NAME_CASE(FCVT_W_RV64)
11636   NODE_NAME_CASE(FCVT_WU_RV64)
11637   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
11638   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
11639   NODE_NAME_CASE(READ_CYCLE_WIDE)
11640   NODE_NAME_CASE(GREV)
11641   NODE_NAME_CASE(GREVW)
11642   NODE_NAME_CASE(GORC)
11643   NODE_NAME_CASE(GORCW)
11644   NODE_NAME_CASE(SHFL)
11645   NODE_NAME_CASE(SHFLW)
11646   NODE_NAME_CASE(UNSHFL)
11647   NODE_NAME_CASE(UNSHFLW)
11648   NODE_NAME_CASE(BFP)
11649   NODE_NAME_CASE(BFPW)
11650   NODE_NAME_CASE(BCOMPRESS)
11651   NODE_NAME_CASE(BCOMPRESSW)
11652   NODE_NAME_CASE(BDECOMPRESS)
11653   NODE_NAME_CASE(BDECOMPRESSW)
11654   NODE_NAME_CASE(VMV_V_X_VL)
11655   NODE_NAME_CASE(VFMV_V_F_VL)
11656   NODE_NAME_CASE(VMV_X_S)
11657   NODE_NAME_CASE(VMV_S_X_VL)
11658   NODE_NAME_CASE(VFMV_S_F_VL)
11659   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
11660   NODE_NAME_CASE(READ_VLENB)
11661   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
11662   NODE_NAME_CASE(VSLIDEUP_VL)
11663   NODE_NAME_CASE(VSLIDE1UP_VL)
11664   NODE_NAME_CASE(VSLIDEDOWN_VL)
11665   NODE_NAME_CASE(VSLIDE1DOWN_VL)
11666   NODE_NAME_CASE(VID_VL)
11667   NODE_NAME_CASE(VFNCVT_ROD_VL)
11668   NODE_NAME_CASE(VECREDUCE_ADD_VL)
11669   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
11670   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
11671   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
11672   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
11673   NODE_NAME_CASE(VECREDUCE_AND_VL)
11674   NODE_NAME_CASE(VECREDUCE_OR_VL)
11675   NODE_NAME_CASE(VECREDUCE_XOR_VL)
11676   NODE_NAME_CASE(VECREDUCE_FADD_VL)
11677   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
11678   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
11679   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
11680   NODE_NAME_CASE(ADD_VL)
11681   NODE_NAME_CASE(AND_VL)
11682   NODE_NAME_CASE(MUL_VL)
11683   NODE_NAME_CASE(OR_VL)
11684   NODE_NAME_CASE(SDIV_VL)
11685   NODE_NAME_CASE(SHL_VL)
11686   NODE_NAME_CASE(SREM_VL)
11687   NODE_NAME_CASE(SRA_VL)
11688   NODE_NAME_CASE(SRL_VL)
11689   NODE_NAME_CASE(SUB_VL)
11690   NODE_NAME_CASE(UDIV_VL)
11691   NODE_NAME_CASE(UREM_VL)
11692   NODE_NAME_CASE(XOR_VL)
11693   NODE_NAME_CASE(SADDSAT_VL)
11694   NODE_NAME_CASE(UADDSAT_VL)
11695   NODE_NAME_CASE(SSUBSAT_VL)
11696   NODE_NAME_CASE(USUBSAT_VL)
11697   NODE_NAME_CASE(FADD_VL)
11698   NODE_NAME_CASE(FSUB_VL)
11699   NODE_NAME_CASE(FMUL_VL)
11700   NODE_NAME_CASE(FDIV_VL)
11701   NODE_NAME_CASE(FNEG_VL)
11702   NODE_NAME_CASE(FABS_VL)
11703   NODE_NAME_CASE(FSQRT_VL)
11704   NODE_NAME_CASE(VFMADD_VL)
11705   NODE_NAME_CASE(VFNMADD_VL)
11706   NODE_NAME_CASE(VFMSUB_VL)
11707   NODE_NAME_CASE(VFNMSUB_VL)
11708   NODE_NAME_CASE(FCOPYSIGN_VL)
11709   NODE_NAME_CASE(SMIN_VL)
11710   NODE_NAME_CASE(SMAX_VL)
11711   NODE_NAME_CASE(UMIN_VL)
11712   NODE_NAME_CASE(UMAX_VL)
11713   NODE_NAME_CASE(FMINNUM_VL)
11714   NODE_NAME_CASE(FMAXNUM_VL)
11715   NODE_NAME_CASE(MULHS_VL)
11716   NODE_NAME_CASE(MULHU_VL)
11717   NODE_NAME_CASE(FP_TO_SINT_VL)
11718   NODE_NAME_CASE(FP_TO_UINT_VL)
11719   NODE_NAME_CASE(SINT_TO_FP_VL)
11720   NODE_NAME_CASE(UINT_TO_FP_VL)
11721   NODE_NAME_CASE(FP_EXTEND_VL)
11722   NODE_NAME_CASE(FP_ROUND_VL)
11723   NODE_NAME_CASE(VWMUL_VL)
11724   NODE_NAME_CASE(VWMULU_VL)
11725   NODE_NAME_CASE(VWMULSU_VL)
11726   NODE_NAME_CASE(VWADD_VL)
11727   NODE_NAME_CASE(VWADDU_VL)
11728   NODE_NAME_CASE(VWSUB_VL)
11729   NODE_NAME_CASE(VWSUBU_VL)
11730   NODE_NAME_CASE(VWADD_W_VL)
11731   NODE_NAME_CASE(VWADDU_W_VL)
11732   NODE_NAME_CASE(VWSUB_W_VL)
11733   NODE_NAME_CASE(VWSUBU_W_VL)
11734   NODE_NAME_CASE(SETCC_VL)
11735   NODE_NAME_CASE(VSELECT_VL)
11736   NODE_NAME_CASE(VP_MERGE_VL)
11737   NODE_NAME_CASE(VMAND_VL)
11738   NODE_NAME_CASE(VMOR_VL)
11739   NODE_NAME_CASE(VMXOR_VL)
11740   NODE_NAME_CASE(VMCLR_VL)
11741   NODE_NAME_CASE(VMSET_VL)
11742   NODE_NAME_CASE(VRGATHER_VX_VL)
11743   NODE_NAME_CASE(VRGATHER_VV_VL)
11744   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
11745   NODE_NAME_CASE(VSEXT_VL)
11746   NODE_NAME_CASE(VZEXT_VL)
11747   NODE_NAME_CASE(VCPOP_VL)
11748   NODE_NAME_CASE(READ_CSR)
11749   NODE_NAME_CASE(WRITE_CSR)
11750   NODE_NAME_CASE(SWAP_CSR)
11751   }
11752   // clang-format on
11753   return nullptr;
11754 #undef NODE_NAME_CASE
11755 }
11756 
11757 /// getConstraintType - Given a constraint letter, return the type of
11758 /// constraint it is for this target.
11759 RISCVTargetLowering::ConstraintType
11760 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
11761   if (Constraint.size() == 1) {
11762     switch (Constraint[0]) {
11763     default:
11764       break;
11765     case 'f':
11766       return C_RegisterClass;
11767     case 'I':
11768     case 'J':
11769     case 'K':
11770       return C_Immediate;
11771     case 'A':
11772       return C_Memory;
11773     case 'S': // A symbolic address
11774       return C_Other;
11775     }
11776   } else {
11777     if (Constraint == "vr" || Constraint == "vm")
11778       return C_RegisterClass;
11779   }
11780   return TargetLowering::getConstraintType(Constraint);
11781 }
11782 
11783 std::pair<unsigned, const TargetRegisterClass *>
11784 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11785                                                   StringRef Constraint,
11786                                                   MVT VT) const {
11787   // First, see if this is a constraint that directly corresponds to a
11788   // RISCV register class.
11789   if (Constraint.size() == 1) {
11790     switch (Constraint[0]) {
11791     case 'r':
11792       // TODO: Support fixed vectors up to XLen for P extension?
11793       if (VT.isVector())
11794         break;
11795       return std::make_pair(0U, &RISCV::GPRRegClass);
11796     case 'f':
11797       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11798         return std::make_pair(0U, &RISCV::FPR16RegClass);
11799       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11800         return std::make_pair(0U, &RISCV::FPR32RegClass);
11801       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11802         return std::make_pair(0U, &RISCV::FPR64RegClass);
11803       break;
11804     default:
11805       break;
11806     }
11807   } else if (Constraint == "vr") {
11808     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11809                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11810       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11811         return std::make_pair(0U, RC);
11812     }
11813   } else if (Constraint == "vm") {
11814     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11815       return std::make_pair(0U, &RISCV::VMV0RegClass);
11816   }
11817 
11818   // Clang will correctly decode the usage of register name aliases into their
11819   // official names. However, other frontends like `rustc` do not. This allows
11820   // users of these frontends to use the ABI names for registers in LLVM-style
11821   // register constraints.
11822   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11823                                .Case("{zero}", RISCV::X0)
11824                                .Case("{ra}", RISCV::X1)
11825                                .Case("{sp}", RISCV::X2)
11826                                .Case("{gp}", RISCV::X3)
11827                                .Case("{tp}", RISCV::X4)
11828                                .Case("{t0}", RISCV::X5)
11829                                .Case("{t1}", RISCV::X6)
11830                                .Case("{t2}", RISCV::X7)
11831                                .Cases("{s0}", "{fp}", RISCV::X8)
11832                                .Case("{s1}", RISCV::X9)
11833                                .Case("{a0}", RISCV::X10)
11834                                .Case("{a1}", RISCV::X11)
11835                                .Case("{a2}", RISCV::X12)
11836                                .Case("{a3}", RISCV::X13)
11837                                .Case("{a4}", RISCV::X14)
11838                                .Case("{a5}", RISCV::X15)
11839                                .Case("{a6}", RISCV::X16)
11840                                .Case("{a7}", RISCV::X17)
11841                                .Case("{s2}", RISCV::X18)
11842                                .Case("{s3}", RISCV::X19)
11843                                .Case("{s4}", RISCV::X20)
11844                                .Case("{s5}", RISCV::X21)
11845                                .Case("{s6}", RISCV::X22)
11846                                .Case("{s7}", RISCV::X23)
11847                                .Case("{s8}", RISCV::X24)
11848                                .Case("{s9}", RISCV::X25)
11849                                .Case("{s10}", RISCV::X26)
11850                                .Case("{s11}", RISCV::X27)
11851                                .Case("{t3}", RISCV::X28)
11852                                .Case("{t4}", RISCV::X29)
11853                                .Case("{t5}", RISCV::X30)
11854                                .Case("{t6}", RISCV::X31)
11855                                .Default(RISCV::NoRegister);
11856   if (XRegFromAlias != RISCV::NoRegister)
11857     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11858 
11859   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11860   // TableGen record rather than the AsmName to choose registers for InlineAsm
11861   // constraints, plus we want to match those names to the widest floating point
11862   // register type available, manually select floating point registers here.
11863   //
11864   // The second case is the ABI name of the register, so that frontends can also
11865   // use the ABI names in register constraint lists.
11866   if (Subtarget.hasStdExtF()) {
11867     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11868                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11869                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11870                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11871                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11872                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11873                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11874                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11875                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11876                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11877                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11878                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11879                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11880                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11881                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11882                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11883                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11884                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11885                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11886                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11887                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11888                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11889                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11890                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11891                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11892                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11893                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11894                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11895                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11896                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11897                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11898                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11899                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11900                         .Default(RISCV::NoRegister);
11901     if (FReg != RISCV::NoRegister) {
11902       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11903       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11904         unsigned RegNo = FReg - RISCV::F0_F;
11905         unsigned DReg = RISCV::F0_D + RegNo;
11906         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11907       }
11908       if (VT == MVT::f32 || VT == MVT::Other)
11909         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11910       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11911         unsigned RegNo = FReg - RISCV::F0_F;
11912         unsigned HReg = RISCV::F0_H + RegNo;
11913         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11914       }
11915     }
11916   }
11917 
11918   if (Subtarget.hasVInstructions()) {
11919     Register VReg = StringSwitch<Register>(Constraint.lower())
11920                         .Case("{v0}", RISCV::V0)
11921                         .Case("{v1}", RISCV::V1)
11922                         .Case("{v2}", RISCV::V2)
11923                         .Case("{v3}", RISCV::V3)
11924                         .Case("{v4}", RISCV::V4)
11925                         .Case("{v5}", RISCV::V5)
11926                         .Case("{v6}", RISCV::V6)
11927                         .Case("{v7}", RISCV::V7)
11928                         .Case("{v8}", RISCV::V8)
11929                         .Case("{v9}", RISCV::V9)
11930                         .Case("{v10}", RISCV::V10)
11931                         .Case("{v11}", RISCV::V11)
11932                         .Case("{v12}", RISCV::V12)
11933                         .Case("{v13}", RISCV::V13)
11934                         .Case("{v14}", RISCV::V14)
11935                         .Case("{v15}", RISCV::V15)
11936                         .Case("{v16}", RISCV::V16)
11937                         .Case("{v17}", RISCV::V17)
11938                         .Case("{v18}", RISCV::V18)
11939                         .Case("{v19}", RISCV::V19)
11940                         .Case("{v20}", RISCV::V20)
11941                         .Case("{v21}", RISCV::V21)
11942                         .Case("{v22}", RISCV::V22)
11943                         .Case("{v23}", RISCV::V23)
11944                         .Case("{v24}", RISCV::V24)
11945                         .Case("{v25}", RISCV::V25)
11946                         .Case("{v26}", RISCV::V26)
11947                         .Case("{v27}", RISCV::V27)
11948                         .Case("{v28}", RISCV::V28)
11949                         .Case("{v29}", RISCV::V29)
11950                         .Case("{v30}", RISCV::V30)
11951                         .Case("{v31}", RISCV::V31)
11952                         .Default(RISCV::NoRegister);
11953     if (VReg != RISCV::NoRegister) {
11954       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11955         return std::make_pair(VReg, &RISCV::VMRegClass);
11956       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11957         return std::make_pair(VReg, &RISCV::VRRegClass);
11958       for (const auto *RC :
11959            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11960         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11961           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11962           return std::make_pair(VReg, RC);
11963         }
11964       }
11965     }
11966   }
11967 
11968   std::pair<Register, const TargetRegisterClass *> Res =
11969       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11970 
11971   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11972   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11973   // Subtarget into account.
11974   if (Res.second == &RISCV::GPRF16RegClass ||
11975       Res.second == &RISCV::GPRF32RegClass ||
11976       Res.second == &RISCV::GPRF64RegClass)
11977     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11978 
11979   return Res;
11980 }
11981 
11982 unsigned
11983 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11984   // Currently only support length 1 constraints.
11985   if (ConstraintCode.size() == 1) {
11986     switch (ConstraintCode[0]) {
11987     case 'A':
11988       return InlineAsm::Constraint_A;
11989     default:
11990       break;
11991     }
11992   }
11993 
11994   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11995 }
11996 
11997 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11998     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11999     SelectionDAG &DAG) const {
12000   // Currently only support length 1 constraints.
12001   if (Constraint.length() == 1) {
12002     switch (Constraint[0]) {
12003     case 'I':
12004       // Validate & create a 12-bit signed immediate operand.
12005       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
12006         uint64_t CVal = C->getSExtValue();
12007         if (isInt<12>(CVal))
12008           Ops.push_back(
12009               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
12010       }
12011       return;
12012     case 'J':
12013       // Validate & create an integer zero operand.
12014       if (auto *C = dyn_cast<ConstantSDNode>(Op))
12015         if (C->getZExtValue() == 0)
12016           Ops.push_back(
12017               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
12018       return;
12019     case 'K':
12020       // Validate & create a 5-bit unsigned immediate operand.
12021       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
12022         uint64_t CVal = C->getZExtValue();
12023         if (isUInt<5>(CVal))
12024           Ops.push_back(
12025               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
12026       }
12027       return;
12028     case 'S':
12029       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
12030         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
12031                                                  GA->getValueType(0)));
12032       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
12033         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
12034                                                 BA->getValueType(0)));
12035       }
12036       return;
12037     default:
12038       break;
12039     }
12040   }
12041   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12042 }
12043 
12044 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
12045                                                    Instruction *Inst,
12046                                                    AtomicOrdering Ord) const {
12047   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
12048     return Builder.CreateFence(Ord);
12049   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
12050     return Builder.CreateFence(AtomicOrdering::Release);
12051   return nullptr;
12052 }
12053 
12054 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
12055                                                     Instruction *Inst,
12056                                                     AtomicOrdering Ord) const {
12057   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
12058     return Builder.CreateFence(AtomicOrdering::Acquire);
12059   return nullptr;
12060 }
12061 
12062 TargetLowering::AtomicExpansionKind
12063 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
12064   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
12065   // point operations can't be used in an lr/sc sequence without breaking the
12066   // forward-progress guarantee.
12067   if (AI->isFloatingPointOperation())
12068     return AtomicExpansionKind::CmpXChg;
12069 
12070   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
12071   if (Size == 8 || Size == 16)
12072     return AtomicExpansionKind::MaskedIntrinsic;
12073   return AtomicExpansionKind::None;
12074 }
12075 
12076 static Intrinsic::ID
12077 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
12078   if (XLen == 32) {
12079     switch (BinOp) {
12080     default:
12081       llvm_unreachable("Unexpected AtomicRMW BinOp");
12082     case AtomicRMWInst::Xchg:
12083       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
12084     case AtomicRMWInst::Add:
12085       return Intrinsic::riscv_masked_atomicrmw_add_i32;
12086     case AtomicRMWInst::Sub:
12087       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
12088     case AtomicRMWInst::Nand:
12089       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
12090     case AtomicRMWInst::Max:
12091       return Intrinsic::riscv_masked_atomicrmw_max_i32;
12092     case AtomicRMWInst::Min:
12093       return Intrinsic::riscv_masked_atomicrmw_min_i32;
12094     case AtomicRMWInst::UMax:
12095       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
12096     case AtomicRMWInst::UMin:
12097       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
12098     }
12099   }
12100 
12101   if (XLen == 64) {
12102     switch (BinOp) {
12103     default:
12104       llvm_unreachable("Unexpected AtomicRMW BinOp");
12105     case AtomicRMWInst::Xchg:
12106       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
12107     case AtomicRMWInst::Add:
12108       return Intrinsic::riscv_masked_atomicrmw_add_i64;
12109     case AtomicRMWInst::Sub:
12110       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
12111     case AtomicRMWInst::Nand:
12112       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
12113     case AtomicRMWInst::Max:
12114       return Intrinsic::riscv_masked_atomicrmw_max_i64;
12115     case AtomicRMWInst::Min:
12116       return Intrinsic::riscv_masked_atomicrmw_min_i64;
12117     case AtomicRMWInst::UMax:
12118       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
12119     case AtomicRMWInst::UMin:
12120       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
12121     }
12122   }
12123 
12124   llvm_unreachable("Unexpected XLen\n");
12125 }
12126 
12127 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
12128     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
12129     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
12130   unsigned XLen = Subtarget.getXLen();
12131   Value *Ordering =
12132       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
12133   Type *Tys[] = {AlignedAddr->getType()};
12134   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
12135       AI->getModule(),
12136       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
12137 
12138   if (XLen == 64) {
12139     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
12140     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
12141     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
12142   }
12143 
12144   Value *Result;
12145 
12146   // Must pass the shift amount needed to sign extend the loaded value prior
12147   // to performing a signed comparison for min/max. ShiftAmt is the number of
12148   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
12149   // is the number of bits to left+right shift the value in order to
12150   // sign-extend.
12151   if (AI->getOperation() == AtomicRMWInst::Min ||
12152       AI->getOperation() == AtomicRMWInst::Max) {
12153     const DataLayout &DL = AI->getModule()->getDataLayout();
12154     unsigned ValWidth =
12155         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
12156     Value *SextShamt =
12157         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
12158     Result = Builder.CreateCall(LrwOpScwLoop,
12159                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
12160   } else {
12161     Result =
12162         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
12163   }
12164 
12165   if (XLen == 64)
12166     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
12167   return Result;
12168 }
12169 
12170 TargetLowering::AtomicExpansionKind
12171 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
12172     AtomicCmpXchgInst *CI) const {
12173   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
12174   if (Size == 8 || Size == 16)
12175     return AtomicExpansionKind::MaskedIntrinsic;
12176   return AtomicExpansionKind::None;
12177 }
12178 
12179 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
12180     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
12181     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
12182   unsigned XLen = Subtarget.getXLen();
12183   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
12184   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
12185   if (XLen == 64) {
12186     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
12187     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
12188     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
12189     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
12190   }
12191   Type *Tys[] = {AlignedAddr->getType()};
12192   Function *MaskedCmpXchg =
12193       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
12194   Value *Result = Builder.CreateCall(
12195       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
12196   if (XLen == 64)
12197     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
12198   return Result;
12199 }
12200 
12201 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT,
12202                                                         EVT DataVT) const {
12203   return false;
12204 }
12205 
12206 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
12207                                                EVT VT) const {
12208   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
12209     return false;
12210 
12211   switch (FPVT.getSimpleVT().SimpleTy) {
12212   case MVT::f16:
12213     return Subtarget.hasStdExtZfh();
12214   case MVT::f32:
12215     return Subtarget.hasStdExtF();
12216   case MVT::f64:
12217     return Subtarget.hasStdExtD();
12218   default:
12219     return false;
12220   }
12221 }
12222 
12223 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
12224   // If we are using the small code model, we can reduce size of jump table
12225   // entry to 4 bytes.
12226   if (Subtarget.is64Bit() && !isPositionIndependent() &&
12227       getTargetMachine().getCodeModel() == CodeModel::Small) {
12228     return MachineJumpTableInfo::EK_Custom32;
12229   }
12230   return TargetLowering::getJumpTableEncoding();
12231 }
12232 
12233 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
12234     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
12235     unsigned uid, MCContext &Ctx) const {
12236   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
12237          getTargetMachine().getCodeModel() == CodeModel::Small);
12238   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
12239 }
12240 
12241 bool RISCVTargetLowering::isVScaleKnownToBeAPowerOfTwo() const {
12242   // We define vscale to be VLEN/RVVBitsPerBlock.  VLEN is always a power
12243   // of two >= 64, and RVVBitsPerBlock is 64.  Thus, vscale must be
12244   // a power of two as well.
12245   // FIXME: This doesn't work for zve32, but that's already broken
12246   // elsewhere for the same reason.
12247   assert(Subtarget.getRealMinVLen() >= 64 && "zve32* unsupported");
12248   static_assert(RISCV::RVVBitsPerBlock == 64,
12249                 "RVVBitsPerBlock changed, audit needed");
12250   return true;
12251 }
12252 
12253 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
12254                                                      EVT VT) const {
12255   VT = VT.getScalarType();
12256 
12257   if (!VT.isSimple())
12258     return false;
12259 
12260   switch (VT.getSimpleVT().SimpleTy) {
12261   case MVT::f16:
12262     return Subtarget.hasStdExtZfh();
12263   case MVT::f32:
12264     return Subtarget.hasStdExtF();
12265   case MVT::f64:
12266     return Subtarget.hasStdExtD();
12267   default:
12268     break;
12269   }
12270 
12271   return false;
12272 }
12273 
12274 Register RISCVTargetLowering::getExceptionPointerRegister(
12275     const Constant *PersonalityFn) const {
12276   return RISCV::X10;
12277 }
12278 
12279 Register RISCVTargetLowering::getExceptionSelectorRegister(
12280     const Constant *PersonalityFn) const {
12281   return RISCV::X11;
12282 }
12283 
12284 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
12285   // Return false to suppress the unnecessary extensions if the LibCall
12286   // arguments or return value is f32 type for LP64 ABI.
12287   RISCVABI::ABI ABI = Subtarget.getTargetABI();
12288   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
12289     return false;
12290 
12291   return true;
12292 }
12293 
12294 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
12295   if (Subtarget.is64Bit() && Type == MVT::i32)
12296     return true;
12297 
12298   return IsSigned;
12299 }
12300 
12301 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
12302                                                  SDValue C) const {
12303   // Check integral scalar types.
12304   const bool HasExtMOrZmmul =
12305       Subtarget.hasStdExtM() || Subtarget.hasStdExtZmmul();
12306   if (VT.isScalarInteger()) {
12307     // Omit the optimization if the sub target has the M extension and the data
12308     // size exceeds XLen.
12309     if (HasExtMOrZmmul && VT.getSizeInBits() > Subtarget.getXLen())
12310       return false;
12311     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
12312       // Break the MUL to a SLLI and an ADD/SUB.
12313       const APInt &Imm = ConstNode->getAPIntValue();
12314       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
12315           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
12316         return true;
12317       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
12318       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
12319           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
12320            (Imm - 8).isPowerOf2()))
12321         return true;
12322       // Omit the following optimization if the sub target has the M extension
12323       // and the data size >= XLen.
12324       if (HasExtMOrZmmul && VT.getSizeInBits() >= Subtarget.getXLen())
12325         return false;
12326       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
12327       // a pair of LUI/ADDI.
12328       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
12329         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
12330         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
12331             (1 - ImmS).isPowerOf2())
12332           return true;
12333       }
12334     }
12335   }
12336 
12337   return false;
12338 }
12339 
12340 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
12341                                                       SDValue ConstNode) const {
12342   // Let the DAGCombiner decide for vectors.
12343   EVT VT = AddNode.getValueType();
12344   if (VT.isVector())
12345     return true;
12346 
12347   // Let the DAGCombiner decide for larger types.
12348   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
12349     return true;
12350 
12351   // It is worse if c1 is simm12 while c1*c2 is not.
12352   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
12353   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
12354   const APInt &C1 = C1Node->getAPIntValue();
12355   const APInt &C2 = C2Node->getAPIntValue();
12356   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
12357     return false;
12358 
12359   // Default to true and let the DAGCombiner decide.
12360   return true;
12361 }
12362 
12363 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
12364     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
12365     bool *Fast) const {
12366   if (!VT.isVector()) {
12367     if (Fast)
12368       *Fast = false;
12369     return Subtarget.enableUnalignedScalarMem();
12370   }
12371 
12372   // All vector implementations must support element alignment
12373   EVT ElemVT = VT.getVectorElementType();
12374   if (Alignment >= ElemVT.getStoreSize()) {
12375     if (Fast)
12376       *Fast = true;
12377     return true;
12378   }
12379 
12380   return false;
12381 }
12382 
12383 bool RISCVTargetLowering::splitValueIntoRegisterParts(
12384     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
12385     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
12386   bool IsABIRegCopy = CC.has_value();
12387   EVT ValueVT = Val.getValueType();
12388   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
12389     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
12390     // and cast to f32.
12391     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
12392     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
12393     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
12394                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
12395     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
12396     Parts[0] = Val;
12397     return true;
12398   }
12399 
12400   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
12401     LLVMContext &Context = *DAG.getContext();
12402     EVT ValueEltVT = ValueVT.getVectorElementType();
12403     EVT PartEltVT = PartVT.getVectorElementType();
12404     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
12405     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
12406     if (PartVTBitSize % ValueVTBitSize == 0) {
12407       assert(PartVTBitSize >= ValueVTBitSize);
12408       // If the element types are different, bitcast to the same element type of
12409       // PartVT first.
12410       // Give an example here, we want copy a <vscale x 1 x i8> value to
12411       // <vscale x 4 x i16>.
12412       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
12413       // subvector, then we can bitcast to <vscale x 4 x i16>.
12414       if (ValueEltVT != PartEltVT) {
12415         if (PartVTBitSize > ValueVTBitSize) {
12416           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
12417           assert(Count != 0 && "The number of element should not be zero.");
12418           EVT SameEltTypeVT =
12419               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
12420           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
12421                             DAG.getUNDEF(SameEltTypeVT), Val,
12422                             DAG.getVectorIdxConstant(0, DL));
12423         }
12424         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
12425       } else {
12426         Val =
12427             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
12428                         Val, DAG.getVectorIdxConstant(0, DL));
12429       }
12430       Parts[0] = Val;
12431       return true;
12432     }
12433   }
12434   return false;
12435 }
12436 
12437 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
12438     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
12439     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
12440   bool IsABIRegCopy = CC.has_value();
12441   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
12442     SDValue Val = Parts[0];
12443 
12444     // Cast the f32 to i32, truncate to i16, and cast back to f16.
12445     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
12446     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
12447     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
12448     return Val;
12449   }
12450 
12451   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
12452     LLVMContext &Context = *DAG.getContext();
12453     SDValue Val = Parts[0];
12454     EVT ValueEltVT = ValueVT.getVectorElementType();
12455     EVT PartEltVT = PartVT.getVectorElementType();
12456     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
12457     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
12458     if (PartVTBitSize % ValueVTBitSize == 0) {
12459       assert(PartVTBitSize >= ValueVTBitSize);
12460       EVT SameEltTypeVT = ValueVT;
12461       // If the element types are different, convert it to the same element type
12462       // of PartVT.
12463       // Give an example here, we want copy a <vscale x 1 x i8> value from
12464       // <vscale x 4 x i16>.
12465       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
12466       // then we can extract <vscale x 1 x i8>.
12467       if (ValueEltVT != PartEltVT) {
12468         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
12469         assert(Count != 0 && "The number of element should not be zero.");
12470         SameEltTypeVT =
12471             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
12472         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
12473       }
12474       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
12475                         DAG.getVectorIdxConstant(0, DL));
12476       return Val;
12477     }
12478   }
12479   return SDValue();
12480 }
12481 
12482 SDValue
12483 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12484                                    SelectionDAG &DAG,
12485                                    SmallVectorImpl<SDNode *> &Created) const {
12486   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
12487   if (isIntDivCheap(N->getValueType(0), Attr))
12488     return SDValue(N, 0); // Lower SDIV as SDIV
12489 
12490   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
12491          "Unexpected divisor!");
12492 
12493   // Conditional move is needed, so do the transformation iff Zbt is enabled.
12494   if (!Subtarget.hasStdExtZbt())
12495     return SDValue();
12496 
12497   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
12498   // Besides, more critical path instructions will be generated when dividing
12499   // by 2. So we keep using the original DAGs for these cases.
12500   unsigned Lg2 = Divisor.countTrailingZeros();
12501   if (Lg2 == 1 || Lg2 >= 12)
12502     return SDValue();
12503 
12504   // fold (sdiv X, pow2)
12505   EVT VT = N->getValueType(0);
12506   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
12507     return SDValue();
12508 
12509   SDLoc DL(N);
12510   SDValue N0 = N->getOperand(0);
12511   SDValue Zero = DAG.getConstant(0, DL, VT);
12512   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
12513 
12514   // Add (N0 < 0) ? Pow2 - 1 : 0;
12515   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
12516   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
12517   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
12518 
12519   Created.push_back(Cmp.getNode());
12520   Created.push_back(Add.getNode());
12521   Created.push_back(Sel.getNode());
12522 
12523   // Divide by pow2.
12524   SDValue SRA =
12525       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
12526 
12527   // If we're dividing by a positive value, we're done.  Otherwise, we must
12528   // negate the result.
12529   if (Divisor.isNonNegative())
12530     return SRA;
12531 
12532   Created.push_back(SRA.getNode());
12533   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
12534 }
12535 
12536 #define GET_REGISTER_MATCHER
12537 #include "RISCVGenAsmMatcher.inc"
12538 
12539 Register
12540 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
12541                                        const MachineFunction &MF) const {
12542   Register Reg = MatchRegisterAltName(RegName);
12543   if (Reg == RISCV::NoRegister)
12544     Reg = MatchRegisterName(RegName);
12545   if (Reg == RISCV::NoRegister)
12546     report_fatal_error(
12547         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
12548   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
12549   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
12550     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
12551                              StringRef(RegName) + "\"."));
12552   return Reg;
12553 }
12554 
12555 namespace llvm {
12556 namespace RISCVVIntrinsicsTable {
12557 
12558 #define GET_RISCVVIntrinsicsTable_IMPL
12559 #include "RISCVGenSearchableTables.inc"
12560 
12561 } // namespace RISCVVIntrinsicsTable
12562 
12563 } // namespace llvm
12564