1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/DiagnosticPrinter.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/IntrinsicsRISCV.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/KnownBits.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "riscv-lower"
45 
46 STATISTIC(NumTailCalls, "Number of tail calls");
47 
48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
49                                          const RISCVSubtarget &STI)
50     : TargetLowering(TM), Subtarget(STI) {
51 
52   if (Subtarget.isRV32E())
53     report_fatal_error("Codegen not yet implemented for RV32E");
54 
55   RISCVABI::ABI ABI = Subtarget.getTargetABI();
56   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
57 
58   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
59       !Subtarget.hasStdExtF()) {
60     errs() << "Hard-float 'f' ABI can't be used for a target that "
61                 "doesn't support the F instruction set extension (ignoring "
62                           "target-abi)\n";
63     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
64   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
65              !Subtarget.hasStdExtD()) {
66     errs() << "Hard-float 'd' ABI can't be used for a target that "
67               "doesn't support the D instruction set extension (ignoring "
68               "target-abi)\n";
69     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
70   }
71 
72   switch (ABI) {
73   default:
74     report_fatal_error("Don't know how to lower this ABI");
75   case RISCVABI::ABI_ILP32:
76   case RISCVABI::ABI_ILP32F:
77   case RISCVABI::ABI_ILP32D:
78   case RISCVABI::ABI_LP64:
79   case RISCVABI::ABI_LP64F:
80   case RISCVABI::ABI_LP64D:
81     break;
82   }
83 
84   MVT XLenVT = Subtarget.getXLenVT();
85 
86   // Set up the register classes.
87   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
88 
89   if (Subtarget.hasStdExtZfh())
90     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
91   if (Subtarget.hasStdExtF())
92     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
93   if (Subtarget.hasStdExtD())
94     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
95 
96   static const MVT::SimpleValueType BoolVecVTs[] = {
97       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
98       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
99   static const MVT::SimpleValueType IntVecVTs[] = {
100       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
101       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
102       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
103       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
104       MVT::nxv4i64, MVT::nxv8i64};
105   static const MVT::SimpleValueType F16VecVTs[] = {
106       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
107       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
108   static const MVT::SimpleValueType F32VecVTs[] = {
109       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
110   static const MVT::SimpleValueType F64VecVTs[] = {
111       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
112 
113   if (Subtarget.hasVInstructions()) {
114     auto addRegClassForRVV = [this](MVT VT) {
115       unsigned Size = VT.getSizeInBits().getKnownMinValue();
116       assert(Size <= 512 && isPowerOf2_32(Size));
117       const TargetRegisterClass *RC;
118       if (Size <= 64)
119         RC = &RISCV::VRRegClass;
120       else if (Size == 128)
121         RC = &RISCV::VRM2RegClass;
122       else if (Size == 256)
123         RC = &RISCV::VRM4RegClass;
124       else
125         RC = &RISCV::VRM8RegClass;
126 
127       addRegisterClass(VT, RC);
128     };
129 
130     for (MVT VT : BoolVecVTs)
131       addRegClassForRVV(VT);
132     for (MVT VT : IntVecVTs) {
133       if (VT.getVectorElementType() == MVT::i64 &&
134           !Subtarget.hasVInstructionsI64())
135         continue;
136       addRegClassForRVV(VT);
137     }
138 
139     if (Subtarget.hasVInstructionsF16())
140       for (MVT VT : F16VecVTs)
141         addRegClassForRVV(VT);
142 
143     if (Subtarget.hasVInstructionsF32())
144       for (MVT VT : F32VecVTs)
145         addRegClassForRVV(VT);
146 
147     if (Subtarget.hasVInstructionsF64())
148       for (MVT VT : F64VecVTs)
149         addRegClassForRVV(VT);
150 
151     if (Subtarget.useRVVForFixedLengthVectors()) {
152       auto addRegClassForFixedVectors = [this](MVT VT) {
153         MVT ContainerVT = getContainerForFixedLengthVector(VT);
154         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
155         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
156         addRegisterClass(VT, TRI.getRegClass(RCID));
157       };
158       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
159         if (useRVVForFixedLengthVectorVT(VT))
160           addRegClassForFixedVectors(VT);
161 
162       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
163         if (useRVVForFixedLengthVectorVT(VT))
164           addRegClassForFixedVectors(VT);
165     }
166   }
167 
168   // Compute derived properties from the register classes.
169   computeRegisterProperties(STI.getRegisterInfo());
170 
171   setStackPointerRegisterToSaveRestore(RISCV::X2);
172 
173   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
174     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
175 
176   // TODO: add all necessary setOperationAction calls.
177   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
178 
179   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
180   setOperationAction(ISD::BR_CC, XLenVT, Expand);
181   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
182   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
183 
184   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
185   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
186 
187   setOperationAction(ISD::VASTART, MVT::Other, Custom);
188   setOperationAction(ISD::VAARG, MVT::Other, Expand);
189   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
190   setOperationAction(ISD::VAEND, MVT::Other, Expand);
191 
192   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
193   if (!Subtarget.hasStdExtZbb()) {
194     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
195     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
196   }
197 
198   if (Subtarget.is64Bit()) {
199     setOperationAction(ISD::ADD, MVT::i32, Custom);
200     setOperationAction(ISD::SUB, MVT::i32, Custom);
201     setOperationAction(ISD::SHL, MVT::i32, Custom);
202     setOperationAction(ISD::SRA, MVT::i32, Custom);
203     setOperationAction(ISD::SRL, MVT::i32, Custom);
204 
205     setOperationAction(ISD::UADDO, MVT::i32, Custom);
206     setOperationAction(ISD::USUBO, MVT::i32, Custom);
207     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
208     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
209   } else {
210     setLibcallName(RTLIB::SHL_I128, nullptr);
211     setLibcallName(RTLIB::SRL_I128, nullptr);
212     setLibcallName(RTLIB::SRA_I128, nullptr);
213     setLibcallName(RTLIB::MUL_I128, nullptr);
214     setLibcallName(RTLIB::MULO_I64, nullptr);
215   }
216 
217   if (!Subtarget.hasStdExtM()) {
218     setOperationAction(ISD::MUL, XLenVT, Expand);
219     setOperationAction(ISD::MULHS, XLenVT, Expand);
220     setOperationAction(ISD::MULHU, XLenVT, Expand);
221     setOperationAction(ISD::SDIV, XLenVT, Expand);
222     setOperationAction(ISD::UDIV, XLenVT, Expand);
223     setOperationAction(ISD::SREM, XLenVT, Expand);
224     setOperationAction(ISD::UREM, XLenVT, Expand);
225   } else {
226     if (Subtarget.is64Bit()) {
227       setOperationAction(ISD::MUL, MVT::i32, Custom);
228       setOperationAction(ISD::MUL, MVT::i128, Custom);
229 
230       setOperationAction(ISD::SDIV, MVT::i8, Custom);
231       setOperationAction(ISD::UDIV, MVT::i8, Custom);
232       setOperationAction(ISD::UREM, MVT::i8, Custom);
233       setOperationAction(ISD::SDIV, MVT::i16, Custom);
234       setOperationAction(ISD::UDIV, MVT::i16, Custom);
235       setOperationAction(ISD::UREM, MVT::i16, Custom);
236       setOperationAction(ISD::SDIV, MVT::i32, Custom);
237       setOperationAction(ISD::UDIV, MVT::i32, Custom);
238       setOperationAction(ISD::UREM, MVT::i32, Custom);
239     } else {
240       setOperationAction(ISD::MUL, MVT::i64, Custom);
241     }
242   }
243 
244   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
245   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
246   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
247   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
248 
249   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
250   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
251   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
252 
253   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
254       Subtarget.hasStdExtZbkb()) {
255     if (Subtarget.is64Bit()) {
256       setOperationAction(ISD::ROTL, MVT::i32, Custom);
257       setOperationAction(ISD::ROTR, MVT::i32, Custom);
258     }
259   } else {
260     setOperationAction(ISD::ROTL, XLenVT, Expand);
261     setOperationAction(ISD::ROTR, XLenVT, Expand);
262   }
263 
264   if (Subtarget.hasStdExtZbp()) {
265     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
266     // more combining.
267     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
268     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
269     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
270     // BSWAP i8 doesn't exist.
271     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
272     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
273 
274     if (Subtarget.is64Bit()) {
275       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
276       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
277     }
278   } else {
279     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
280     // pattern match it directly in isel.
281     setOperationAction(ISD::BSWAP, XLenVT,
282                        (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
283                            ? Legal
284                            : Expand);
285     // Zbkb can use rev8+brev8 to implement bitreverse.
286     setOperationAction(ISD::BITREVERSE, XLenVT,
287                        Subtarget.hasStdExtZbkb() ? Custom : Expand);
288   }
289 
290   if (Subtarget.hasStdExtZbb()) {
291     setOperationAction(ISD::SMIN, XLenVT, Legal);
292     setOperationAction(ISD::SMAX, XLenVT, Legal);
293     setOperationAction(ISD::UMIN, XLenVT, Legal);
294     setOperationAction(ISD::UMAX, XLenVT, Legal);
295 
296     if (Subtarget.is64Bit()) {
297       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
298       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
299       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
300       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
301     }
302   } else {
303     setOperationAction(ISD::CTTZ, XLenVT, Expand);
304     setOperationAction(ISD::CTLZ, XLenVT, Expand);
305     setOperationAction(ISD::CTPOP, XLenVT, Expand);
306 
307     if (Subtarget.is64Bit())
308       setOperationAction(ISD::ABS, MVT::i32, Custom);
309   }
310 
311   if (Subtarget.hasStdExtZbt()) {
312     setOperationAction(ISD::FSHL, XLenVT, Custom);
313     setOperationAction(ISD::FSHR, XLenVT, Custom);
314     setOperationAction(ISD::SELECT, XLenVT, Legal);
315 
316     if (Subtarget.is64Bit()) {
317       setOperationAction(ISD::FSHL, MVT::i32, Custom);
318       setOperationAction(ISD::FSHR, MVT::i32, Custom);
319     }
320   } else {
321     setOperationAction(ISD::SELECT, XLenVT, Custom);
322   }
323 
324   static constexpr ISD::NodeType FPLegalNodeTypes[] = {
325       ISD::FMINNUM,        ISD::FMAXNUM,       ISD::LRINT,
326       ISD::LLRINT,         ISD::LROUND,        ISD::LLROUND,
327       ISD::STRICT_LRINT,   ISD::STRICT_LLRINT, ISD::STRICT_LROUND,
328       ISD::STRICT_LLROUND, ISD::STRICT_FMA,    ISD::STRICT_FADD,
329       ISD::STRICT_FSUB,    ISD::STRICT_FMUL,   ISD::STRICT_FDIV,
330       ISD::STRICT_FSQRT,   ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS};
331 
332   static const ISD::CondCode FPCCToExpand[] = {
333       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
334       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
335       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
336 
337   static const ISD::NodeType FPOpToExpand[] = {
338       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
339       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
340 
341   if (Subtarget.hasStdExtZfh())
342     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
343 
344   if (Subtarget.hasStdExtZfh()) {
345     for (auto NT : FPLegalNodeTypes)
346       setOperationAction(NT, MVT::f16, Legal);
347     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
348     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
349     for (auto CC : FPCCToExpand)
350       setCondCodeAction(CC, MVT::f16, Expand);
351     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
352     setOperationAction(ISD::SELECT, MVT::f16, Custom);
353     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
354 
355     setOperationAction(ISD::FREM,       MVT::f16, Promote);
356     setOperationAction(ISD::FCEIL,      MVT::f16, Promote);
357     setOperationAction(ISD::FFLOOR,     MVT::f16, Promote);
358     setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
359     setOperationAction(ISD::FRINT,      MVT::f16, Promote);
360     setOperationAction(ISD::FROUND,     MVT::f16, Promote);
361     setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote);
362     setOperationAction(ISD::FTRUNC,     MVT::f16, Promote);
363     setOperationAction(ISD::FPOW,       MVT::f16, Promote);
364     setOperationAction(ISD::FPOWI,      MVT::f16, Promote);
365     setOperationAction(ISD::FCOS,       MVT::f16, Promote);
366     setOperationAction(ISD::FSIN,       MVT::f16, Promote);
367     setOperationAction(ISD::FSINCOS,    MVT::f16, Promote);
368     setOperationAction(ISD::FEXP,       MVT::f16, Promote);
369     setOperationAction(ISD::FEXP2,      MVT::f16, Promote);
370     setOperationAction(ISD::FLOG,       MVT::f16, Promote);
371     setOperationAction(ISD::FLOG2,      MVT::f16, Promote);
372     setOperationAction(ISD::FLOG10,     MVT::f16, Promote);
373 
374     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
375     // complete support for all operations in LegalizeDAG.
376 
377     // We need to custom promote this.
378     if (Subtarget.is64Bit())
379       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
380   }
381 
382   if (Subtarget.hasStdExtF()) {
383     for (auto NT : FPLegalNodeTypes)
384       setOperationAction(NT, MVT::f32, Legal);
385     for (auto CC : FPCCToExpand)
386       setCondCodeAction(CC, MVT::f32, Expand);
387     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
388     setOperationAction(ISD::SELECT, MVT::f32, Custom);
389     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
390     for (auto Op : FPOpToExpand)
391       setOperationAction(Op, MVT::f32, Expand);
392     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
393     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
394   }
395 
396   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
397     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
398 
399   if (Subtarget.hasStdExtD()) {
400     for (auto NT : FPLegalNodeTypes)
401       setOperationAction(NT, MVT::f64, Legal);
402     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
403     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
404     for (auto CC : FPCCToExpand)
405       setCondCodeAction(CC, MVT::f64, Expand);
406     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
407     setOperationAction(ISD::SELECT, MVT::f64, Custom);
408     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
409     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
410     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
411     for (auto Op : FPOpToExpand)
412       setOperationAction(Op, MVT::f64, Expand);
413     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
414     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
415   }
416 
417   if (Subtarget.is64Bit()) {
418     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
419     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
420     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
421     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
422   }
423 
424   if (Subtarget.hasStdExtF()) {
425     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
426     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
427 
428     setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal);
429     setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal);
430     setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal);
431     setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal);
432 
433     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
434     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
435   }
436 
437   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
438   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
439   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
440   setOperationAction(ISD::JumpTable, XLenVT, Custom);
441 
442   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
443 
444   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
445   // Unfortunately this can't be determined just from the ISA naming string.
446   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
447                      Subtarget.is64Bit() ? Legal : Custom);
448 
449   setOperationAction(ISD::TRAP, MVT::Other, Legal);
450   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
451   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
452   if (Subtarget.is64Bit())
453     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
454 
455   if (Subtarget.hasStdExtA()) {
456     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
457     setMinCmpXchgSizeInBits(32);
458   } else {
459     setMaxAtomicSizeInBitsSupported(0);
460   }
461 
462   setBooleanContents(ZeroOrOneBooleanContent);
463 
464   if (Subtarget.hasVInstructions()) {
465     setBooleanVectorContents(ZeroOrOneBooleanContent);
466 
467     setOperationAction(ISD::VSCALE, XLenVT, Custom);
468 
469     // RVV intrinsics may have illegal operands.
470     // We also need to custom legalize vmv.x.s.
471     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
472     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
473     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
474     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
475     if (Subtarget.is64Bit()) {
476       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
477     } else {
478       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
479       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
480     }
481 
482     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
483     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
484 
485     static const unsigned IntegerVPOps[] = {
486         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
487         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
488         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
489         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
490         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
491         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
492         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
493         ISD::VP_MERGE,       ISD::VP_SELECT};
494 
495     static const unsigned FloatingPointVPOps[] = {
496         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
497         ISD::VP_FDIV,        ISD::VP_FNEG,        ISD::VP_FMA,
498         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, ISD::VP_REDUCE_FMIN,
499         ISD::VP_REDUCE_FMAX, ISD::VP_MERGE,       ISD::VP_SELECT};
500 
501     if (!Subtarget.is64Bit()) {
502       // We must custom-lower certain vXi64 operations on RV32 due to the vector
503       // element type being illegal.
504       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
505       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
506 
507       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
508       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
509       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
510       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
511       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
512       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
513       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
514       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
515 
516       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
517       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
518       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
519       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
520       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
521       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
522       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
523       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
524     }
525 
526     for (MVT VT : BoolVecVTs) {
527       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
528 
529       // Mask VTs are custom-expanded into a series of standard nodes
530       setOperationAction(ISD::TRUNCATE, VT, Custom);
531       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
532       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
533       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
534 
535       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
536       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
537 
538       setOperationAction(ISD::SELECT, VT, Custom);
539       setOperationAction(ISD::SELECT_CC, VT, Expand);
540       setOperationAction(ISD::VSELECT, VT, Expand);
541       setOperationAction(ISD::VP_MERGE, VT, Expand);
542       setOperationAction(ISD::VP_SELECT, VT, Expand);
543 
544       setOperationAction(ISD::VP_AND, VT, Custom);
545       setOperationAction(ISD::VP_OR, VT, Custom);
546       setOperationAction(ISD::VP_XOR, VT, Custom);
547 
548       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
549       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
550       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
551 
552       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
553       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
554       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
555 
556       // RVV has native int->float & float->int conversions where the
557       // element type sizes are within one power-of-two of each other. Any
558       // wider distances between type sizes have to be lowered as sequences
559       // which progressively narrow the gap in stages.
560       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
561       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
562       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
563       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
564 
565       // Expand all extending loads to types larger than this, and truncating
566       // stores from types larger than this.
567       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
568         setTruncStoreAction(OtherVT, VT, Expand);
569         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
570         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
571         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
572       }
573     }
574 
575     for (MVT VT : IntVecVTs) {
576       if (VT.getVectorElementType() == MVT::i64 &&
577           !Subtarget.hasVInstructionsI64())
578         continue;
579 
580       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
581       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
582 
583       // Vectors implement MULHS/MULHU.
584       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
585       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
586 
587       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
588       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) {
589         setOperationAction(ISD::MULHU, VT, Expand);
590         setOperationAction(ISD::MULHS, VT, Expand);
591       }
592 
593       setOperationAction(ISD::SMIN, VT, Legal);
594       setOperationAction(ISD::SMAX, VT, Legal);
595       setOperationAction(ISD::UMIN, VT, Legal);
596       setOperationAction(ISD::UMAX, VT, Legal);
597 
598       setOperationAction(ISD::ROTL, VT, Expand);
599       setOperationAction(ISD::ROTR, VT, Expand);
600 
601       setOperationAction(ISD::CTTZ, VT, Expand);
602       setOperationAction(ISD::CTLZ, VT, Expand);
603       setOperationAction(ISD::CTPOP, VT, Expand);
604 
605       setOperationAction(ISD::BSWAP, VT, Expand);
606 
607       // Custom-lower extensions and truncations from/to mask types.
608       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
609       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
610       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
611 
612       // RVV has native int->float & float->int conversions where the
613       // element type sizes are within one power-of-two of each other. Any
614       // wider distances between type sizes have to be lowered as sequences
615       // which progressively narrow the gap in stages.
616       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
617       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
618       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
619       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
620 
621       setOperationAction(ISD::SADDSAT, VT, Legal);
622       setOperationAction(ISD::UADDSAT, VT, Legal);
623       setOperationAction(ISD::SSUBSAT, VT, Legal);
624       setOperationAction(ISD::USUBSAT, VT, Legal);
625 
626       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
627       // nodes which truncate by one power of two at a time.
628       setOperationAction(ISD::TRUNCATE, VT, Custom);
629 
630       // Custom-lower insert/extract operations to simplify patterns.
631       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
632       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
633 
634       // Custom-lower reduction operations to set up the corresponding custom
635       // nodes' operands.
636       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
637       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
638       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
639       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
640       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
641       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
642       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
643       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
644 
645       for (unsigned VPOpc : IntegerVPOps)
646         setOperationAction(VPOpc, VT, Custom);
647 
648       setOperationAction(ISD::LOAD, VT, Custom);
649       setOperationAction(ISD::STORE, VT, Custom);
650 
651       setOperationAction(ISD::MLOAD, VT, Custom);
652       setOperationAction(ISD::MSTORE, VT, Custom);
653       setOperationAction(ISD::MGATHER, VT, Custom);
654       setOperationAction(ISD::MSCATTER, VT, Custom);
655 
656       setOperationAction(ISD::VP_LOAD, VT, Custom);
657       setOperationAction(ISD::VP_STORE, VT, Custom);
658       setOperationAction(ISD::VP_GATHER, VT, Custom);
659       setOperationAction(ISD::VP_SCATTER, VT, Custom);
660 
661       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
662       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
663       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
664 
665       setOperationAction(ISD::SELECT, VT, Custom);
666       setOperationAction(ISD::SELECT_CC, VT, Expand);
667 
668       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
669       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
670 
671       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
672         setTruncStoreAction(VT, OtherVT, Expand);
673         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
674         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
675         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
676       }
677 
678       // Splice
679       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
680 
681       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
682       // type that can represent the value exactly.
683       if (VT.getVectorElementType() != MVT::i64) {
684         MVT FloatEltVT =
685             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
686         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
687         if (isTypeLegal(FloatVT)) {
688           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
689           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
690         }
691       }
692     }
693 
694     // Expand various CCs to best match the RVV ISA, which natively supports UNE
695     // but no other unordered comparisons, and supports all ordered comparisons
696     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
697     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
698     // and we pattern-match those back to the "original", swapping operands once
699     // more. This way we catch both operations and both "vf" and "fv" forms with
700     // fewer patterns.
701     static const ISD::CondCode VFPCCToExpand[] = {
702         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
703         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
704         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
705     };
706 
707     // Sets common operation actions on RVV floating-point vector types.
708     const auto SetCommonVFPActions = [&](MVT VT) {
709       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
710       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
711       // sizes are within one power-of-two of each other. Therefore conversions
712       // between vXf16 and vXf64 must be lowered as sequences which convert via
713       // vXf32.
714       setOperationAction(ISD::FP_ROUND, VT, Custom);
715       setOperationAction(ISD::FP_EXTEND, VT, Custom);
716       // Custom-lower insert/extract operations to simplify patterns.
717       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
718       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
719       // Expand various condition codes (explained above).
720       for (auto CC : VFPCCToExpand)
721         setCondCodeAction(CC, VT, Expand);
722 
723       setOperationAction(ISD::FMINNUM, VT, Legal);
724       setOperationAction(ISD::FMAXNUM, VT, Legal);
725 
726       setOperationAction(ISD::FTRUNC, VT, Custom);
727       setOperationAction(ISD::FCEIL, VT, Custom);
728       setOperationAction(ISD::FFLOOR, VT, Custom);
729       setOperationAction(ISD::FROUND, VT, Custom);
730 
731       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
732       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
733       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
734       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
735 
736       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
737 
738       setOperationAction(ISD::LOAD, VT, Custom);
739       setOperationAction(ISD::STORE, VT, Custom);
740 
741       setOperationAction(ISD::MLOAD, VT, Custom);
742       setOperationAction(ISD::MSTORE, VT, Custom);
743       setOperationAction(ISD::MGATHER, VT, Custom);
744       setOperationAction(ISD::MSCATTER, VT, Custom);
745 
746       setOperationAction(ISD::VP_LOAD, VT, Custom);
747       setOperationAction(ISD::VP_STORE, VT, Custom);
748       setOperationAction(ISD::VP_GATHER, VT, Custom);
749       setOperationAction(ISD::VP_SCATTER, VT, Custom);
750 
751       setOperationAction(ISD::SELECT, VT, Custom);
752       setOperationAction(ISD::SELECT_CC, VT, Expand);
753 
754       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
755       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
756       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
757 
758       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
759       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
760 
761       for (unsigned VPOpc : FloatingPointVPOps)
762         setOperationAction(VPOpc, VT, Custom);
763     };
764 
765     // Sets common extload/truncstore actions on RVV floating-point vector
766     // types.
767     const auto SetCommonVFPExtLoadTruncStoreActions =
768         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
769           for (auto SmallVT : SmallerVTs) {
770             setTruncStoreAction(VT, SmallVT, Expand);
771             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
772           }
773         };
774 
775     if (Subtarget.hasVInstructionsF16())
776       for (MVT VT : F16VecVTs)
777         SetCommonVFPActions(VT);
778 
779     for (MVT VT : F32VecVTs) {
780       if (Subtarget.hasVInstructionsF32())
781         SetCommonVFPActions(VT);
782       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
783     }
784 
785     for (MVT VT : F64VecVTs) {
786       if (Subtarget.hasVInstructionsF64())
787         SetCommonVFPActions(VT);
788       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
789       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
790     }
791 
792     if (Subtarget.useRVVForFixedLengthVectors()) {
793       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
794         if (!useRVVForFixedLengthVectorVT(VT))
795           continue;
796 
797         // By default everything must be expanded.
798         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
799           setOperationAction(Op, VT, Expand);
800         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
801           setTruncStoreAction(VT, OtherVT, Expand);
802           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
803           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
804           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
805         }
806 
807         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
808         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
809         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
810 
811         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
812         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
813 
814         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
815         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
816 
817         setOperationAction(ISD::LOAD, VT, Custom);
818         setOperationAction(ISD::STORE, VT, Custom);
819 
820         setOperationAction(ISD::SETCC, VT, Custom);
821 
822         setOperationAction(ISD::SELECT, VT, Custom);
823 
824         setOperationAction(ISD::TRUNCATE, VT, Custom);
825 
826         setOperationAction(ISD::BITCAST, VT, Custom);
827 
828         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
829         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
830         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
831 
832         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
833         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
834         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
835 
836         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
837         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
838         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
839         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
840 
841         // Operations below are different for between masks and other vectors.
842         if (VT.getVectorElementType() == MVT::i1) {
843           setOperationAction(ISD::VP_AND, VT, Custom);
844           setOperationAction(ISD::VP_OR, VT, Custom);
845           setOperationAction(ISD::VP_XOR, VT, Custom);
846           setOperationAction(ISD::AND, VT, Custom);
847           setOperationAction(ISD::OR, VT, Custom);
848           setOperationAction(ISD::XOR, VT, Custom);
849           continue;
850         }
851 
852         // Use SPLAT_VECTOR to prevent type legalization from destroying the
853         // splats when type legalizing i64 scalar on RV32.
854         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
855         // improvements first.
856         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
857           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
858           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
859         }
860 
861         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
862         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
863 
864         setOperationAction(ISD::MLOAD, VT, Custom);
865         setOperationAction(ISD::MSTORE, VT, Custom);
866         setOperationAction(ISD::MGATHER, VT, Custom);
867         setOperationAction(ISD::MSCATTER, VT, Custom);
868 
869         setOperationAction(ISD::VP_LOAD, VT, Custom);
870         setOperationAction(ISD::VP_STORE, VT, Custom);
871         setOperationAction(ISD::VP_GATHER, VT, Custom);
872         setOperationAction(ISD::VP_SCATTER, VT, Custom);
873 
874         setOperationAction(ISD::ADD, VT, Custom);
875         setOperationAction(ISD::MUL, VT, Custom);
876         setOperationAction(ISD::SUB, VT, Custom);
877         setOperationAction(ISD::AND, VT, Custom);
878         setOperationAction(ISD::OR, VT, Custom);
879         setOperationAction(ISD::XOR, VT, Custom);
880         setOperationAction(ISD::SDIV, VT, Custom);
881         setOperationAction(ISD::SREM, VT, Custom);
882         setOperationAction(ISD::UDIV, VT, Custom);
883         setOperationAction(ISD::UREM, VT, Custom);
884         setOperationAction(ISD::SHL, VT, Custom);
885         setOperationAction(ISD::SRA, VT, Custom);
886         setOperationAction(ISD::SRL, VT, Custom);
887 
888         setOperationAction(ISD::SMIN, VT, Custom);
889         setOperationAction(ISD::SMAX, VT, Custom);
890         setOperationAction(ISD::UMIN, VT, Custom);
891         setOperationAction(ISD::UMAX, VT, Custom);
892         setOperationAction(ISD::ABS,  VT, Custom);
893 
894         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
895         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) {
896           setOperationAction(ISD::MULHS, VT, Custom);
897           setOperationAction(ISD::MULHU, VT, Custom);
898         }
899 
900         setOperationAction(ISD::SADDSAT, VT, Custom);
901         setOperationAction(ISD::UADDSAT, VT, Custom);
902         setOperationAction(ISD::SSUBSAT, VT, Custom);
903         setOperationAction(ISD::USUBSAT, VT, Custom);
904 
905         setOperationAction(ISD::VSELECT, VT, Custom);
906         setOperationAction(ISD::SELECT_CC, VT, Expand);
907 
908         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
909         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
910         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
911 
912         // Custom-lower reduction operations to set up the corresponding custom
913         // nodes' operands.
914         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
915         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
916         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
917         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
918         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
919 
920         for (unsigned VPOpc : IntegerVPOps)
921           setOperationAction(VPOpc, VT, Custom);
922 
923         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
924         // type that can represent the value exactly.
925         if (VT.getVectorElementType() != MVT::i64) {
926           MVT FloatEltVT =
927               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
928           EVT FloatVT =
929               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
930           if (isTypeLegal(FloatVT)) {
931             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
932             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
933           }
934         }
935       }
936 
937       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
938         if (!useRVVForFixedLengthVectorVT(VT))
939           continue;
940 
941         // By default everything must be expanded.
942         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
943           setOperationAction(Op, VT, Expand);
944         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
945           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
946           setTruncStoreAction(VT, OtherVT, Expand);
947         }
948 
949         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
950         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
951         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
952 
953         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
954         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
955         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
956         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
957         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
958 
959         setOperationAction(ISD::LOAD, VT, Custom);
960         setOperationAction(ISD::STORE, VT, Custom);
961         setOperationAction(ISD::MLOAD, VT, Custom);
962         setOperationAction(ISD::MSTORE, VT, Custom);
963         setOperationAction(ISD::MGATHER, VT, Custom);
964         setOperationAction(ISD::MSCATTER, VT, Custom);
965 
966         setOperationAction(ISD::VP_LOAD, VT, Custom);
967         setOperationAction(ISD::VP_STORE, VT, Custom);
968         setOperationAction(ISD::VP_GATHER, VT, Custom);
969         setOperationAction(ISD::VP_SCATTER, VT, Custom);
970 
971         setOperationAction(ISD::FADD, VT, Custom);
972         setOperationAction(ISD::FSUB, VT, Custom);
973         setOperationAction(ISD::FMUL, VT, Custom);
974         setOperationAction(ISD::FDIV, VT, Custom);
975         setOperationAction(ISD::FNEG, VT, Custom);
976         setOperationAction(ISD::FABS, VT, Custom);
977         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
978         setOperationAction(ISD::FSQRT, VT, Custom);
979         setOperationAction(ISD::FMA, VT, Custom);
980         setOperationAction(ISD::FMINNUM, VT, Custom);
981         setOperationAction(ISD::FMAXNUM, VT, Custom);
982 
983         setOperationAction(ISD::FP_ROUND, VT, Custom);
984         setOperationAction(ISD::FP_EXTEND, VT, Custom);
985 
986         setOperationAction(ISD::FTRUNC, VT, Custom);
987         setOperationAction(ISD::FCEIL, VT, Custom);
988         setOperationAction(ISD::FFLOOR, VT, Custom);
989         setOperationAction(ISD::FROUND, VT, Custom);
990 
991         for (auto CC : VFPCCToExpand)
992           setCondCodeAction(CC, VT, Expand);
993 
994         setOperationAction(ISD::VSELECT, VT, Custom);
995         setOperationAction(ISD::SELECT, VT, Custom);
996         setOperationAction(ISD::SELECT_CC, VT, Expand);
997 
998         setOperationAction(ISD::BITCAST, VT, Custom);
999 
1000         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1001         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1002         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1003         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1004 
1005         for (unsigned VPOpc : FloatingPointVPOps)
1006           setOperationAction(VPOpc, VT, Custom);
1007       }
1008 
1009       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1010       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1011       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1012       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
1013       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1014       if (Subtarget.hasStdExtZfh())
1015         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
1016       if (Subtarget.hasStdExtF())
1017         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
1018       if (Subtarget.hasStdExtD())
1019         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
1020     }
1021   }
1022 
1023   // Function alignments.
1024   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
1025   setMinFunctionAlignment(FunctionAlignment);
1026   setPrefFunctionAlignment(FunctionAlignment);
1027 
1028   setMinimumJumpTableEntries(5);
1029 
1030   // Jumps are expensive, compared to logic
1031   setJumpIsExpensive();
1032 
1033   setTargetDAGCombine(ISD::ADD);
1034   setTargetDAGCombine(ISD::SUB);
1035   setTargetDAGCombine(ISD::AND);
1036   setTargetDAGCombine(ISD::OR);
1037   setTargetDAGCombine(ISD::XOR);
1038   if (Subtarget.hasStdExtZbp()) {
1039     setTargetDAGCombine(ISD::ROTL);
1040     setTargetDAGCombine(ISD::ROTR);
1041   }
1042   if (Subtarget.hasStdExtZbkb())
1043     setTargetDAGCombine(ISD::BITREVERSE);
1044   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1045   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
1046     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1047   if (Subtarget.hasStdExtF()) {
1048     setTargetDAGCombine(ISD::ZERO_EXTEND);
1049     setTargetDAGCombine(ISD::FP_TO_SINT);
1050     setTargetDAGCombine(ISD::FP_TO_UINT);
1051     setTargetDAGCombine(ISD::FP_TO_SINT_SAT);
1052     setTargetDAGCombine(ISD::FP_TO_UINT_SAT);
1053   }
1054   if (Subtarget.hasVInstructions()) {
1055     setTargetDAGCombine(ISD::FCOPYSIGN);
1056     setTargetDAGCombine(ISD::MGATHER);
1057     setTargetDAGCombine(ISD::MSCATTER);
1058     setTargetDAGCombine(ISD::VP_GATHER);
1059     setTargetDAGCombine(ISD::VP_SCATTER);
1060     setTargetDAGCombine(ISD::SRA);
1061     setTargetDAGCombine(ISD::SRL);
1062     setTargetDAGCombine(ISD::SHL);
1063     setTargetDAGCombine(ISD::STORE);
1064     setTargetDAGCombine(ISD::SPLAT_VECTOR);
1065   }
1066 
1067   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
1068   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
1069 }
1070 
1071 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1072                                             LLVMContext &Context,
1073                                             EVT VT) const {
1074   if (!VT.isVector())
1075     return getPointerTy(DL);
1076   if (Subtarget.hasVInstructions() &&
1077       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1078     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1079   return VT.changeVectorElementTypeToInteger();
1080 }
1081 
1082 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1083   return Subtarget.getXLenVT();
1084 }
1085 
1086 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1087                                              const CallInst &I,
1088                                              MachineFunction &MF,
1089                                              unsigned Intrinsic) const {
1090   auto &DL = I.getModule()->getDataLayout();
1091   switch (Intrinsic) {
1092   default:
1093     return false;
1094   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1095   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1096   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1097   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1098   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1099   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1100   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1101   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1102   case Intrinsic::riscv_masked_cmpxchg_i32:
1103     Info.opc = ISD::INTRINSIC_W_CHAIN;
1104     Info.memVT = MVT::i32;
1105     Info.ptrVal = I.getArgOperand(0);
1106     Info.offset = 0;
1107     Info.align = Align(4);
1108     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1109                  MachineMemOperand::MOVolatile;
1110     return true;
1111   case Intrinsic::riscv_masked_strided_load:
1112     Info.opc = ISD::INTRINSIC_W_CHAIN;
1113     Info.ptrVal = I.getArgOperand(1);
1114     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1115     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1116     Info.size = MemoryLocation::UnknownSize;
1117     Info.flags |= MachineMemOperand::MOLoad;
1118     return true;
1119   case Intrinsic::riscv_masked_strided_store:
1120     Info.opc = ISD::INTRINSIC_VOID;
1121     Info.ptrVal = I.getArgOperand(1);
1122     Info.memVT =
1123         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1124     Info.align = Align(
1125         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1126         8);
1127     Info.size = MemoryLocation::UnknownSize;
1128     Info.flags |= MachineMemOperand::MOStore;
1129     return true;
1130   case Intrinsic::riscv_seg2_load:
1131   case Intrinsic::riscv_seg3_load:
1132   case Intrinsic::riscv_seg4_load:
1133   case Intrinsic::riscv_seg5_load:
1134   case Intrinsic::riscv_seg6_load:
1135   case Intrinsic::riscv_seg7_load:
1136   case Intrinsic::riscv_seg8_load:
1137     Info.opc = ISD::INTRINSIC_W_CHAIN;
1138     Info.ptrVal = I.getArgOperand(0);
1139     Info.memVT =
1140         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
1141     Info.align =
1142         Align(DL.getTypeSizeInBits(
1143                   I.getType()->getStructElementType(0)->getScalarType()) /
1144               8);
1145     Info.size = MemoryLocation::UnknownSize;
1146     Info.flags |= MachineMemOperand::MOLoad;
1147     return true;
1148   }
1149 }
1150 
1151 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1152                                                 const AddrMode &AM, Type *Ty,
1153                                                 unsigned AS,
1154                                                 Instruction *I) const {
1155   // No global is ever allowed as a base.
1156   if (AM.BaseGV)
1157     return false;
1158 
1159   // Require a 12-bit signed offset.
1160   if (!isInt<12>(AM.BaseOffs))
1161     return false;
1162 
1163   switch (AM.Scale) {
1164   case 0: // "r+i" or just "i", depending on HasBaseReg.
1165     break;
1166   case 1:
1167     if (!AM.HasBaseReg) // allow "r+i".
1168       break;
1169     return false; // disallow "r+r" or "r+r+i".
1170   default:
1171     return false;
1172   }
1173 
1174   return true;
1175 }
1176 
1177 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1178   return isInt<12>(Imm);
1179 }
1180 
1181 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1182   return isInt<12>(Imm);
1183 }
1184 
1185 // On RV32, 64-bit integers are split into their high and low parts and held
1186 // in two different registers, so the trunc is free since the low register can
1187 // just be used.
1188 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1189   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1190     return false;
1191   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1192   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1193   return (SrcBits == 64 && DestBits == 32);
1194 }
1195 
1196 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1197   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1198       !SrcVT.isInteger() || !DstVT.isInteger())
1199     return false;
1200   unsigned SrcBits = SrcVT.getSizeInBits();
1201   unsigned DestBits = DstVT.getSizeInBits();
1202   return (SrcBits == 64 && DestBits == 32);
1203 }
1204 
1205 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1206   // Zexts are free if they can be combined with a load.
1207   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1208   // poorly with type legalization of compares preferring sext.
1209   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1210     EVT MemVT = LD->getMemoryVT();
1211     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1212         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1213          LD->getExtensionType() == ISD::ZEXTLOAD))
1214       return true;
1215   }
1216 
1217   return TargetLowering::isZExtFree(Val, VT2);
1218 }
1219 
1220 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1221   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1222 }
1223 
1224 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1225   return Subtarget.hasStdExtZbb();
1226 }
1227 
1228 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1229   return Subtarget.hasStdExtZbb();
1230 }
1231 
1232 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1233   EVT VT = Y.getValueType();
1234 
1235   // FIXME: Support vectors once we have tests.
1236   if (VT.isVector())
1237     return false;
1238 
1239   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1240           Subtarget.hasStdExtZbkb()) &&
1241          !isa<ConstantSDNode>(Y);
1242 }
1243 
1244 /// Check if sinking \p I's operands to I's basic block is profitable, because
1245 /// the operands can be folded into a target instruction, e.g.
1246 /// splats of scalars can fold into vector instructions.
1247 bool RISCVTargetLowering::shouldSinkOperands(
1248     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1249   using namespace llvm::PatternMatch;
1250 
1251   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1252     return false;
1253 
1254   auto IsSinker = [&](Instruction *I, int Operand) {
1255     switch (I->getOpcode()) {
1256     case Instruction::Add:
1257     case Instruction::Sub:
1258     case Instruction::Mul:
1259     case Instruction::And:
1260     case Instruction::Or:
1261     case Instruction::Xor:
1262     case Instruction::FAdd:
1263     case Instruction::FSub:
1264     case Instruction::FMul:
1265     case Instruction::FDiv:
1266     case Instruction::ICmp:
1267     case Instruction::FCmp:
1268       return true;
1269     case Instruction::Shl:
1270     case Instruction::LShr:
1271     case Instruction::AShr:
1272     case Instruction::UDiv:
1273     case Instruction::SDiv:
1274     case Instruction::URem:
1275     case Instruction::SRem:
1276       return Operand == 1;
1277     case Instruction::Call:
1278       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1279         switch (II->getIntrinsicID()) {
1280         case Intrinsic::fma:
1281         case Intrinsic::vp_fma:
1282           return Operand == 0 || Operand == 1;
1283         // FIXME: Our patterns can only match vx/vf instructions when the splat
1284         // it on the RHS, because TableGen doesn't recognize our VP operations
1285         // as commutative.
1286         case Intrinsic::vp_add:
1287         case Intrinsic::vp_mul:
1288         case Intrinsic::vp_and:
1289         case Intrinsic::vp_or:
1290         case Intrinsic::vp_xor:
1291         case Intrinsic::vp_fadd:
1292         case Intrinsic::vp_fmul:
1293         case Intrinsic::vp_shl:
1294         case Intrinsic::vp_lshr:
1295         case Intrinsic::vp_ashr:
1296         case Intrinsic::vp_udiv:
1297         case Intrinsic::vp_sdiv:
1298         case Intrinsic::vp_urem:
1299         case Intrinsic::vp_srem:
1300           return Operand == 1;
1301         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1302         // explicit patterns for both LHS and RHS (as 'vr' versions).
1303         case Intrinsic::vp_sub:
1304         case Intrinsic::vp_fsub:
1305         case Intrinsic::vp_fdiv:
1306           return Operand == 0 || Operand == 1;
1307         default:
1308           return false;
1309         }
1310       }
1311       return false;
1312     default:
1313       return false;
1314     }
1315   };
1316 
1317   for (auto OpIdx : enumerate(I->operands())) {
1318     if (!IsSinker(I, OpIdx.index()))
1319       continue;
1320 
1321     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1322     // Make sure we are not already sinking this operand
1323     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1324       continue;
1325 
1326     // We are looking for a splat that can be sunk.
1327     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1328                              m_Undef(), m_ZeroMask())))
1329       continue;
1330 
1331     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1332     // and vector registers
1333     for (Use &U : Op->uses()) {
1334       Instruction *Insn = cast<Instruction>(U.getUser());
1335       if (!IsSinker(Insn, U.getOperandNo()))
1336         return false;
1337     }
1338 
1339     Ops.push_back(&Op->getOperandUse(0));
1340     Ops.push_back(&OpIdx.value());
1341   }
1342   return true;
1343 }
1344 
1345 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1346                                        bool ForCodeSize) const {
1347   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1348   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1349     return false;
1350   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1351     return false;
1352   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1353     return false;
1354   return Imm.isZero();
1355 }
1356 
1357 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1358   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1359          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1360          (VT == MVT::f64 && Subtarget.hasStdExtD());
1361 }
1362 
1363 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1364                                                       CallingConv::ID CC,
1365                                                       EVT VT) const {
1366   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1367   // We might still end up using a GPR but that will be decided based on ABI.
1368   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1369   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1370     return MVT::f32;
1371 
1372   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1373 }
1374 
1375 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1376                                                            CallingConv::ID CC,
1377                                                            EVT VT) const {
1378   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1379   // We might still end up using a GPR but that will be decided based on ABI.
1380   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1381   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1382     return 1;
1383 
1384   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1385 }
1386 
1387 // Changes the condition code and swaps operands if necessary, so the SetCC
1388 // operation matches one of the comparisons supported directly by branches
1389 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1390 // with 1/-1.
1391 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1392                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1393   // Convert X > -1 to X >= 0.
1394   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1395     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1396     CC = ISD::SETGE;
1397     return;
1398   }
1399   // Convert X < 1 to 0 >= X.
1400   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1401     RHS = LHS;
1402     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1403     CC = ISD::SETGE;
1404     return;
1405   }
1406 
1407   switch (CC) {
1408   default:
1409     break;
1410   case ISD::SETGT:
1411   case ISD::SETLE:
1412   case ISD::SETUGT:
1413   case ISD::SETULE:
1414     CC = ISD::getSetCCSwappedOperands(CC);
1415     std::swap(LHS, RHS);
1416     break;
1417   }
1418 }
1419 
1420 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1421   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1422   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1423   if (VT.getVectorElementType() == MVT::i1)
1424     KnownSize *= 8;
1425 
1426   switch (KnownSize) {
1427   default:
1428     llvm_unreachable("Invalid LMUL.");
1429   case 8:
1430     return RISCVII::VLMUL::LMUL_F8;
1431   case 16:
1432     return RISCVII::VLMUL::LMUL_F4;
1433   case 32:
1434     return RISCVII::VLMUL::LMUL_F2;
1435   case 64:
1436     return RISCVII::VLMUL::LMUL_1;
1437   case 128:
1438     return RISCVII::VLMUL::LMUL_2;
1439   case 256:
1440     return RISCVII::VLMUL::LMUL_4;
1441   case 512:
1442     return RISCVII::VLMUL::LMUL_8;
1443   }
1444 }
1445 
1446 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1447   switch (LMul) {
1448   default:
1449     llvm_unreachable("Invalid LMUL.");
1450   case RISCVII::VLMUL::LMUL_F8:
1451   case RISCVII::VLMUL::LMUL_F4:
1452   case RISCVII::VLMUL::LMUL_F2:
1453   case RISCVII::VLMUL::LMUL_1:
1454     return RISCV::VRRegClassID;
1455   case RISCVII::VLMUL::LMUL_2:
1456     return RISCV::VRM2RegClassID;
1457   case RISCVII::VLMUL::LMUL_4:
1458     return RISCV::VRM4RegClassID;
1459   case RISCVII::VLMUL::LMUL_8:
1460     return RISCV::VRM8RegClassID;
1461   }
1462 }
1463 
1464 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1465   RISCVII::VLMUL LMUL = getLMUL(VT);
1466   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1467       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1468       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1469       LMUL == RISCVII::VLMUL::LMUL_1) {
1470     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1471                   "Unexpected subreg numbering");
1472     return RISCV::sub_vrm1_0 + Index;
1473   }
1474   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1475     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1476                   "Unexpected subreg numbering");
1477     return RISCV::sub_vrm2_0 + Index;
1478   }
1479   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1480     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1481                   "Unexpected subreg numbering");
1482     return RISCV::sub_vrm4_0 + Index;
1483   }
1484   llvm_unreachable("Invalid vector type.");
1485 }
1486 
1487 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1488   if (VT.getVectorElementType() == MVT::i1)
1489     return RISCV::VRRegClassID;
1490   return getRegClassIDForLMUL(getLMUL(VT));
1491 }
1492 
1493 // Attempt to decompose a subvector insert/extract between VecVT and
1494 // SubVecVT via subregister indices. Returns the subregister index that
1495 // can perform the subvector insert/extract with the given element index, as
1496 // well as the index corresponding to any leftover subvectors that must be
1497 // further inserted/extracted within the register class for SubVecVT.
1498 std::pair<unsigned, unsigned>
1499 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1500     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1501     const RISCVRegisterInfo *TRI) {
1502   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1503                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1504                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1505                 "Register classes not ordered");
1506   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1507   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1508   // Try to compose a subregister index that takes us from the incoming
1509   // LMUL>1 register class down to the outgoing one. At each step we half
1510   // the LMUL:
1511   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1512   // Note that this is not guaranteed to find a subregister index, such as
1513   // when we are extracting from one VR type to another.
1514   unsigned SubRegIdx = RISCV::NoSubRegister;
1515   for (const unsigned RCID :
1516        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1517     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1518       VecVT = VecVT.getHalfNumVectorElementsVT();
1519       bool IsHi =
1520           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1521       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1522                                             getSubregIndexByMVT(VecVT, IsHi));
1523       if (IsHi)
1524         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1525     }
1526   return {SubRegIdx, InsertExtractIdx};
1527 }
1528 
1529 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1530 // stores for those types.
1531 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1532   return !Subtarget.useRVVForFixedLengthVectors() ||
1533          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1534 }
1535 
1536 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1537   if (ScalarTy->isPointerTy())
1538     return true;
1539 
1540   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1541       ScalarTy->isIntegerTy(32))
1542     return true;
1543 
1544   if (ScalarTy->isIntegerTy(64))
1545     return Subtarget.hasVInstructionsI64();
1546 
1547   if (ScalarTy->isHalfTy())
1548     return Subtarget.hasVInstructionsF16();
1549   if (ScalarTy->isFloatTy())
1550     return Subtarget.hasVInstructionsF32();
1551   if (ScalarTy->isDoubleTy())
1552     return Subtarget.hasVInstructionsF64();
1553 
1554   return false;
1555 }
1556 
1557 static SDValue getVLOperand(SDValue Op) {
1558   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1559           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1560          "Unexpected opcode");
1561   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1562   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1563   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1564       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1565   if (!II)
1566     return SDValue();
1567   return Op.getOperand(II->VLOperand + 1 + HasChain);
1568 }
1569 
1570 static bool useRVVForFixedLengthVectorVT(MVT VT,
1571                                          const RISCVSubtarget &Subtarget) {
1572   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1573   if (!Subtarget.useRVVForFixedLengthVectors())
1574     return false;
1575 
1576   // We only support a set of vector types with a consistent maximum fixed size
1577   // across all supported vector element types to avoid legalization issues.
1578   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1579   // fixed-length vector type we support is 1024 bytes.
1580   if (VT.getFixedSizeInBits() > 1024 * 8)
1581     return false;
1582 
1583   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1584 
1585   MVT EltVT = VT.getVectorElementType();
1586 
1587   // Don't use RVV for vectors we cannot scalarize if required.
1588   switch (EltVT.SimpleTy) {
1589   // i1 is supported but has different rules.
1590   default:
1591     return false;
1592   case MVT::i1:
1593     // Masks can only use a single register.
1594     if (VT.getVectorNumElements() > MinVLen)
1595       return false;
1596     MinVLen /= 8;
1597     break;
1598   case MVT::i8:
1599   case MVT::i16:
1600   case MVT::i32:
1601     break;
1602   case MVT::i64:
1603     if (!Subtarget.hasVInstructionsI64())
1604       return false;
1605     break;
1606   case MVT::f16:
1607     if (!Subtarget.hasVInstructionsF16())
1608       return false;
1609     break;
1610   case MVT::f32:
1611     if (!Subtarget.hasVInstructionsF32())
1612       return false;
1613     break;
1614   case MVT::f64:
1615     if (!Subtarget.hasVInstructionsF64())
1616       return false;
1617     break;
1618   }
1619 
1620   // Reject elements larger than ELEN.
1621   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1622     return false;
1623 
1624   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1625   // Don't use RVV for types that don't fit.
1626   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1627     return false;
1628 
1629   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1630   // the base fixed length RVV support in place.
1631   if (!VT.isPow2VectorType())
1632     return false;
1633 
1634   return true;
1635 }
1636 
1637 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1638   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1639 }
1640 
1641 // Return the largest legal scalable vector type that matches VT's element type.
1642 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1643                                             const RISCVSubtarget &Subtarget) {
1644   // This may be called before legal types are setup.
1645   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1646           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1647          "Expected legal fixed length vector!");
1648 
1649   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1650   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1651 
1652   MVT EltVT = VT.getVectorElementType();
1653   switch (EltVT.SimpleTy) {
1654   default:
1655     llvm_unreachable("unexpected element type for RVV container");
1656   case MVT::i1:
1657   case MVT::i8:
1658   case MVT::i16:
1659   case MVT::i32:
1660   case MVT::i64:
1661   case MVT::f16:
1662   case MVT::f32:
1663   case MVT::f64: {
1664     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1665     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1666     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1667     unsigned NumElts =
1668         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1669     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1670     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1671     return MVT::getScalableVectorVT(EltVT, NumElts);
1672   }
1673   }
1674 }
1675 
1676 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1677                                             const RISCVSubtarget &Subtarget) {
1678   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1679                                           Subtarget);
1680 }
1681 
1682 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1683   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1684 }
1685 
1686 // Grow V to consume an entire RVV register.
1687 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1688                                        const RISCVSubtarget &Subtarget) {
1689   assert(VT.isScalableVector() &&
1690          "Expected to convert into a scalable vector!");
1691   assert(V.getValueType().isFixedLengthVector() &&
1692          "Expected a fixed length vector operand!");
1693   SDLoc DL(V);
1694   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1695   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1696 }
1697 
1698 // Shrink V so it's just big enough to maintain a VT's worth of data.
1699 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1700                                          const RISCVSubtarget &Subtarget) {
1701   assert(VT.isFixedLengthVector() &&
1702          "Expected to convert into a fixed length vector!");
1703   assert(V.getValueType().isScalableVector() &&
1704          "Expected a scalable vector operand!");
1705   SDLoc DL(V);
1706   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1707   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1708 }
1709 
1710 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1711 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1712 // the vector type that it is contained in.
1713 static std::pair<SDValue, SDValue>
1714 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1715                 const RISCVSubtarget &Subtarget) {
1716   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1717   MVT XLenVT = Subtarget.getXLenVT();
1718   SDValue VL = VecVT.isFixedLengthVector()
1719                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1720                    : DAG.getRegister(RISCV::X0, XLenVT);
1721   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1722   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1723   return {Mask, VL};
1724 }
1725 
1726 // As above but assuming the given type is a scalable vector type.
1727 static std::pair<SDValue, SDValue>
1728 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1729                         const RISCVSubtarget &Subtarget) {
1730   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1731   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1732 }
1733 
1734 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1735 // of either is (currently) supported. This can get us into an infinite loop
1736 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1737 // as a ..., etc.
1738 // Until either (or both) of these can reliably lower any node, reporting that
1739 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1740 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1741 // which is not desirable.
1742 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1743     EVT VT, unsigned DefinedValues) const {
1744   return false;
1745 }
1746 
1747 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1748                                   const RISCVSubtarget &Subtarget) {
1749   // RISCV FP-to-int conversions saturate to the destination register size, but
1750   // don't produce 0 for nan. We can use a conversion instruction and fix the
1751   // nan case with a compare and a select.
1752   SDValue Src = Op.getOperand(0);
1753 
1754   EVT DstVT = Op.getValueType();
1755   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1756 
1757   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1758   unsigned Opc;
1759   if (SatVT == DstVT)
1760     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1761   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1762     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1763   else
1764     return SDValue();
1765   // FIXME: Support other SatVTs by clamping before or after the conversion.
1766 
1767   SDLoc DL(Op);
1768   SDValue FpToInt = DAG.getNode(
1769       Opc, DL, DstVT, Src,
1770       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1771 
1772   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1773   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1774 }
1775 
1776 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1777 // and back. Taking care to avoid converting values that are nan or already
1778 // correct.
1779 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1780 // have FRM dependencies modeled yet.
1781 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1782   MVT VT = Op.getSimpleValueType();
1783   assert(VT.isVector() && "Unexpected type");
1784 
1785   SDLoc DL(Op);
1786 
1787   // Freeze the source since we are increasing the number of uses.
1788   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1789 
1790   // Truncate to integer and convert back to FP.
1791   MVT IntVT = VT.changeVectorElementTypeToInteger();
1792   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1793   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1794 
1795   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1796 
1797   if (Op.getOpcode() == ISD::FCEIL) {
1798     // If the truncated value is the greater than or equal to the original
1799     // value, we've computed the ceil. Otherwise, we went the wrong way and
1800     // need to increase by 1.
1801     // FIXME: This should use a masked operation. Handle here or in isel?
1802     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1803                                  DAG.getConstantFP(1.0, DL, VT));
1804     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1805     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1806   } else if (Op.getOpcode() == ISD::FFLOOR) {
1807     // If the truncated value is the less than or equal to the original value,
1808     // we've computed the floor. Otherwise, we went the wrong way and need to
1809     // decrease by 1.
1810     // FIXME: This should use a masked operation. Handle here or in isel?
1811     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1812                                  DAG.getConstantFP(1.0, DL, VT));
1813     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1814     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1815   }
1816 
1817   // Restore the original sign so that -0.0 is preserved.
1818   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1819 
1820   // Determine the largest integer that can be represented exactly. This and
1821   // values larger than it don't have any fractional bits so don't need to
1822   // be converted.
1823   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1824   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1825   APFloat MaxVal = APFloat(FltSem);
1826   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1827                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1828   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1829 
1830   // If abs(Src) was larger than MaxVal or nan, keep it.
1831   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1832   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1833   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1834 }
1835 
1836 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1837 // This mode isn't supported in vector hardware on RISCV. But as long as we
1838 // aren't compiling with trapping math, we can emulate this with
1839 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1840 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1841 // dependencies modeled yet.
1842 // FIXME: Use masked operations to avoid final merge.
1843 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1844   MVT VT = Op.getSimpleValueType();
1845   assert(VT.isVector() && "Unexpected type");
1846 
1847   SDLoc DL(Op);
1848 
1849   // Freeze the source since we are increasing the number of uses.
1850   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1851 
1852   // We do the conversion on the absolute value and fix the sign at the end.
1853   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1854 
1855   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1856   bool Ignored;
1857   APFloat Point5Pred = APFloat(0.5f);
1858   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1859   Point5Pred.next(/*nextDown*/ true);
1860 
1861   // Add the adjustment.
1862   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1863                                DAG.getConstantFP(Point5Pred, DL, VT));
1864 
1865   // Truncate to integer and convert back to fp.
1866   MVT IntVT = VT.changeVectorElementTypeToInteger();
1867   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1868   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1869 
1870   // Restore the original sign.
1871   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1872 
1873   // Determine the largest integer that can be represented exactly. This and
1874   // values larger than it don't have any fractional bits so don't need to
1875   // be converted.
1876   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1877   APFloat MaxVal = APFloat(FltSem);
1878   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1879                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1880   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1881 
1882   // If abs(Src) was larger than MaxVal or nan, keep it.
1883   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1884   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1885   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1886 }
1887 
1888 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1889                                  const RISCVSubtarget &Subtarget) {
1890   MVT VT = Op.getSimpleValueType();
1891   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1892 
1893   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1894 
1895   SDLoc DL(Op);
1896   SDValue Mask, VL;
1897   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1898 
1899   unsigned Opc =
1900       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1901   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
1902                               Op.getOperand(0), VL);
1903   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1904 }
1905 
1906 struct VIDSequence {
1907   int64_t StepNumerator;
1908   unsigned StepDenominator;
1909   int64_t Addend;
1910 };
1911 
1912 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1913 // to the (non-zero) step S and start value X. This can be then lowered as the
1914 // RVV sequence (VID * S) + X, for example.
1915 // The step S is represented as an integer numerator divided by a positive
1916 // denominator. Note that the implementation currently only identifies
1917 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1918 // cannot detect 2/3, for example.
1919 // Note that this method will also match potentially unappealing index
1920 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1921 // determine whether this is worth generating code for.
1922 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1923   unsigned NumElts = Op.getNumOperands();
1924   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1925   if (!Op.getValueType().isInteger())
1926     return None;
1927 
1928   Optional<unsigned> SeqStepDenom;
1929   Optional<int64_t> SeqStepNum, SeqAddend;
1930   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1931   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1932   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1933     // Assume undef elements match the sequence; we just have to be careful
1934     // when interpolating across them.
1935     if (Op.getOperand(Idx).isUndef())
1936       continue;
1937     // The BUILD_VECTOR must be all constants.
1938     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1939       return None;
1940 
1941     uint64_t Val = Op.getConstantOperandVal(Idx) &
1942                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1943 
1944     if (PrevElt) {
1945       // Calculate the step since the last non-undef element, and ensure
1946       // it's consistent across the entire sequence.
1947       unsigned IdxDiff = Idx - PrevElt->second;
1948       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1949 
1950       // A zero-value value difference means that we're somewhere in the middle
1951       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1952       // step change before evaluating the sequence.
1953       if (ValDiff != 0) {
1954         int64_t Remainder = ValDiff % IdxDiff;
1955         // Normalize the step if it's greater than 1.
1956         if (Remainder != ValDiff) {
1957           // The difference must cleanly divide the element span.
1958           if (Remainder != 0)
1959             return None;
1960           ValDiff /= IdxDiff;
1961           IdxDiff = 1;
1962         }
1963 
1964         if (!SeqStepNum)
1965           SeqStepNum = ValDiff;
1966         else if (ValDiff != SeqStepNum)
1967           return None;
1968 
1969         if (!SeqStepDenom)
1970           SeqStepDenom = IdxDiff;
1971         else if (IdxDiff != *SeqStepDenom)
1972           return None;
1973       }
1974     }
1975 
1976     // Record and/or check any addend.
1977     if (SeqStepNum && SeqStepDenom) {
1978       uint64_t ExpectedVal =
1979           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1980       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1981       if (!SeqAddend)
1982         SeqAddend = Addend;
1983       else if (SeqAddend != Addend)
1984         return None;
1985     }
1986 
1987     // Record this non-undef element for later.
1988     if (!PrevElt || PrevElt->first != Val)
1989       PrevElt = std::make_pair(Val, Idx);
1990   }
1991   // We need to have logged both a step and an addend for this to count as
1992   // a legal index sequence.
1993   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1994     return None;
1995 
1996   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1997 }
1998 
1999 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
2000 // and lower it as a VRGATHER_VX_VL from the source vector.
2001 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
2002                                   SelectionDAG &DAG,
2003                                   const RISCVSubtarget &Subtarget) {
2004   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
2005     return SDValue();
2006   SDValue Vec = SplatVal.getOperand(0);
2007   // Only perform this optimization on vectors of the same size for simplicity.
2008   if (Vec.getValueType() != VT)
2009     return SDValue();
2010   SDValue Idx = SplatVal.getOperand(1);
2011   // The index must be a legal type.
2012   if (Idx.getValueType() != Subtarget.getXLenVT())
2013     return SDValue();
2014 
2015   MVT ContainerVT = VT;
2016   if (VT.isFixedLengthVector()) {
2017     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2018     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2019   }
2020 
2021   SDValue Mask, VL;
2022   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2023 
2024   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
2025                                Idx, Mask, VL);
2026 
2027   if (!VT.isFixedLengthVector())
2028     return Gather;
2029 
2030   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2031 }
2032 
2033 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
2034                                  const RISCVSubtarget &Subtarget) {
2035   MVT VT = Op.getSimpleValueType();
2036   assert(VT.isFixedLengthVector() && "Unexpected vector!");
2037 
2038   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2039 
2040   SDLoc DL(Op);
2041   SDValue Mask, VL;
2042   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2043 
2044   MVT XLenVT = Subtarget.getXLenVT();
2045   unsigned NumElts = Op.getNumOperands();
2046 
2047   if (VT.getVectorElementType() == MVT::i1) {
2048     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
2049       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
2050       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
2051     }
2052 
2053     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
2054       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
2055       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
2056     }
2057 
2058     // Lower constant mask BUILD_VECTORs via an integer vector type, in
2059     // scalar integer chunks whose bit-width depends on the number of mask
2060     // bits and XLEN.
2061     // First, determine the most appropriate scalar integer type to use. This
2062     // is at most XLenVT, but may be shrunk to a smaller vector element type
2063     // according to the size of the final vector - use i8 chunks rather than
2064     // XLenVT if we're producing a v8i1. This results in more consistent
2065     // codegen across RV32 and RV64.
2066     unsigned NumViaIntegerBits =
2067         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2068     NumViaIntegerBits = std::min(NumViaIntegerBits,
2069                                  Subtarget.getMaxELENForFixedLengthVectors());
2070     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2071       // If we have to use more than one INSERT_VECTOR_ELT then this
2072       // optimization is likely to increase code size; avoid peforming it in
2073       // such a case. We can use a load from a constant pool in this case.
2074       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2075         return SDValue();
2076       // Now we can create our integer vector type. Note that it may be larger
2077       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2078       MVT IntegerViaVecVT =
2079           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2080                            divideCeil(NumElts, NumViaIntegerBits));
2081 
2082       uint64_t Bits = 0;
2083       unsigned BitPos = 0, IntegerEltIdx = 0;
2084       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2085 
2086       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2087         // Once we accumulate enough bits to fill our scalar type, insert into
2088         // our vector and clear our accumulated data.
2089         if (I != 0 && I % NumViaIntegerBits == 0) {
2090           if (NumViaIntegerBits <= 32)
2091             Bits = SignExtend64(Bits, 32);
2092           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2093           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2094                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2095           Bits = 0;
2096           BitPos = 0;
2097           IntegerEltIdx++;
2098         }
2099         SDValue V = Op.getOperand(I);
2100         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2101         Bits |= ((uint64_t)BitValue << BitPos);
2102       }
2103 
2104       // Insert the (remaining) scalar value into position in our integer
2105       // vector type.
2106       if (NumViaIntegerBits <= 32)
2107         Bits = SignExtend64(Bits, 32);
2108       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2109       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2110                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2111 
2112       if (NumElts < NumViaIntegerBits) {
2113         // If we're producing a smaller vector than our minimum legal integer
2114         // type, bitcast to the equivalent (known-legal) mask type, and extract
2115         // our final mask.
2116         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2117         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2118         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2119                           DAG.getConstant(0, DL, XLenVT));
2120       } else {
2121         // Else we must have produced an integer type with the same size as the
2122         // mask type; bitcast for the final result.
2123         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2124         Vec = DAG.getBitcast(VT, Vec);
2125       }
2126 
2127       return Vec;
2128     }
2129 
2130     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2131     // vector type, we have a legal equivalently-sized i8 type, so we can use
2132     // that.
2133     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2134     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2135 
2136     SDValue WideVec;
2137     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2138       // For a splat, perform a scalar truncate before creating the wider
2139       // vector.
2140       assert(Splat.getValueType() == XLenVT &&
2141              "Unexpected type for i1 splat value");
2142       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2143                           DAG.getConstant(1, DL, XLenVT));
2144       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2145     } else {
2146       SmallVector<SDValue, 8> Ops(Op->op_values());
2147       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2148       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2149       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2150     }
2151 
2152     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2153   }
2154 
2155   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2156     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2157       return Gather;
2158     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2159                                         : RISCVISD::VMV_V_X_VL;
2160     Splat =
2161         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2162     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2163   }
2164 
2165   // Try and match index sequences, which we can lower to the vid instruction
2166   // with optional modifications. An all-undef vector is matched by
2167   // getSplatValue, above.
2168   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2169     int64_t StepNumerator = SimpleVID->StepNumerator;
2170     unsigned StepDenominator = SimpleVID->StepDenominator;
2171     int64_t Addend = SimpleVID->Addend;
2172 
2173     assert(StepNumerator != 0 && "Invalid step");
2174     bool Negate = false;
2175     int64_t SplatStepVal = StepNumerator;
2176     unsigned StepOpcode = ISD::MUL;
2177     if (StepNumerator != 1) {
2178       if (isPowerOf2_64(std::abs(StepNumerator))) {
2179         Negate = StepNumerator < 0;
2180         StepOpcode = ISD::SHL;
2181         SplatStepVal = Log2_64(std::abs(StepNumerator));
2182       }
2183     }
2184 
2185     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2186     // threshold since it's the immediate value many RVV instructions accept.
2187     // There is no vmul.vi instruction so ensure multiply constant can fit in
2188     // a single addi instruction.
2189     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2190          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2191         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2192       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2193       // Convert right out of the scalable type so we can use standard ISD
2194       // nodes for the rest of the computation. If we used scalable types with
2195       // these, we'd lose the fixed-length vector info and generate worse
2196       // vsetvli code.
2197       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2198       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2199           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2200         SDValue SplatStep = DAG.getSplatVector(
2201             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2202         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2203       }
2204       if (StepDenominator != 1) {
2205         SDValue SplatStep = DAG.getSplatVector(
2206             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2207         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2208       }
2209       if (Addend != 0 || Negate) {
2210         SDValue SplatAddend =
2211             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2212         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2213       }
2214       return VID;
2215     }
2216   }
2217 
2218   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2219   // when re-interpreted as a vector with a larger element type. For example,
2220   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2221   // could be instead splat as
2222   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2223   // TODO: This optimization could also work on non-constant splats, but it
2224   // would require bit-manipulation instructions to construct the splat value.
2225   SmallVector<SDValue> Sequence;
2226   unsigned EltBitSize = VT.getScalarSizeInBits();
2227   const auto *BV = cast<BuildVectorSDNode>(Op);
2228   if (VT.isInteger() && EltBitSize < 64 &&
2229       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2230       BV->getRepeatedSequence(Sequence) &&
2231       (Sequence.size() * EltBitSize) <= 64) {
2232     unsigned SeqLen = Sequence.size();
2233     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2234     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2235     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2236             ViaIntVT == MVT::i64) &&
2237            "Unexpected sequence type");
2238 
2239     unsigned EltIdx = 0;
2240     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2241     uint64_t SplatValue = 0;
2242     // Construct the amalgamated value which can be splatted as this larger
2243     // vector type.
2244     for (const auto &SeqV : Sequence) {
2245       if (!SeqV.isUndef())
2246         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2247                        << (EltIdx * EltBitSize));
2248       EltIdx++;
2249     }
2250 
2251     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2252     // achieve better constant materializion.
2253     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2254       SplatValue = SignExtend64(SplatValue, 32);
2255 
2256     // Since we can't introduce illegal i64 types at this stage, we can only
2257     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2258     // way we can use RVV instructions to splat.
2259     assert((ViaIntVT.bitsLE(XLenVT) ||
2260             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2261            "Unexpected bitcast sequence");
2262     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2263       SDValue ViaVL =
2264           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2265       MVT ViaContainerVT =
2266           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2267       SDValue Splat =
2268           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2269                       DAG.getUNDEF(ViaContainerVT),
2270                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2271       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2272       return DAG.getBitcast(VT, Splat);
2273     }
2274   }
2275 
2276   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2277   // which constitute a large proportion of the elements. In such cases we can
2278   // splat a vector with the dominant element and make up the shortfall with
2279   // INSERT_VECTOR_ELTs.
2280   // Note that this includes vectors of 2 elements by association. The
2281   // upper-most element is the "dominant" one, allowing us to use a splat to
2282   // "insert" the upper element, and an insert of the lower element at position
2283   // 0, which improves codegen.
2284   SDValue DominantValue;
2285   unsigned MostCommonCount = 0;
2286   DenseMap<SDValue, unsigned> ValueCounts;
2287   unsigned NumUndefElts =
2288       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2289 
2290   // Track the number of scalar loads we know we'd be inserting, estimated as
2291   // any non-zero floating-point constant. Other kinds of element are either
2292   // already in registers or are materialized on demand. The threshold at which
2293   // a vector load is more desirable than several scalar materializion and
2294   // vector-insertion instructions is not known.
2295   unsigned NumScalarLoads = 0;
2296 
2297   for (SDValue V : Op->op_values()) {
2298     if (V.isUndef())
2299       continue;
2300 
2301     ValueCounts.insert(std::make_pair(V, 0));
2302     unsigned &Count = ValueCounts[V];
2303 
2304     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2305       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2306 
2307     // Is this value dominant? In case of a tie, prefer the highest element as
2308     // it's cheaper to insert near the beginning of a vector than it is at the
2309     // end.
2310     if (++Count >= MostCommonCount) {
2311       DominantValue = V;
2312       MostCommonCount = Count;
2313     }
2314   }
2315 
2316   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2317   unsigned NumDefElts = NumElts - NumUndefElts;
2318   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2319 
2320   // Don't perform this optimization when optimizing for size, since
2321   // materializing elements and inserting them tends to cause code bloat.
2322   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2323       ((MostCommonCount > DominantValueCountThreshold) ||
2324        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2325     // Start by splatting the most common element.
2326     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2327 
2328     DenseSet<SDValue> Processed{DominantValue};
2329     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2330     for (const auto &OpIdx : enumerate(Op->ops())) {
2331       const SDValue &V = OpIdx.value();
2332       if (V.isUndef() || !Processed.insert(V).second)
2333         continue;
2334       if (ValueCounts[V] == 1) {
2335         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2336                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2337       } else {
2338         // Blend in all instances of this value using a VSELECT, using a
2339         // mask where each bit signals whether that element is the one
2340         // we're after.
2341         SmallVector<SDValue> Ops;
2342         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2343           return DAG.getConstant(V == V1, DL, XLenVT);
2344         });
2345         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2346                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2347                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2348       }
2349     }
2350 
2351     return Vec;
2352   }
2353 
2354   return SDValue();
2355 }
2356 
2357 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2358                                    SDValue Lo, SDValue Hi, SDValue VL,
2359                                    SelectionDAG &DAG) {
2360   bool HasPassthru = Passthru && !Passthru.isUndef();
2361   if (!HasPassthru && !Passthru)
2362     Passthru = DAG.getUNDEF(VT);
2363   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2364     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2365     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2366     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2367     // node in order to try and match RVV vector/scalar instructions.
2368     if ((LoC >> 31) == HiC)
2369       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2370 
2371     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2372     // vmv.v.x whose EEW = 32 to lower it.
2373     auto *Const = dyn_cast<ConstantSDNode>(VL);
2374     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2375       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2376       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2377       // access the subtarget here now.
2378       auto InterVec = DAG.getNode(
2379           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2380                                   DAG.getRegister(RISCV::X0, MVT::i32));
2381       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2382     }
2383   }
2384 
2385   // Fall back to a stack store and stride x0 vector load.
2386   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2387                      Hi, VL);
2388 }
2389 
2390 // Called by type legalization to handle splat of i64 on RV32.
2391 // FIXME: We can optimize this when the type has sign or zero bits in one
2392 // of the halves.
2393 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2394                                    SDValue Scalar, SDValue VL,
2395                                    SelectionDAG &DAG) {
2396   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2397   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2398                            DAG.getConstant(0, DL, MVT::i32));
2399   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2400                            DAG.getConstant(1, DL, MVT::i32));
2401   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2402 }
2403 
2404 // This function lowers a splat of a scalar operand Splat with the vector
2405 // length VL. It ensures the final sequence is type legal, which is useful when
2406 // lowering a splat after type legalization.
2407 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2408                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2409                                 const RISCVSubtarget &Subtarget) {
2410   bool HasPassthru = Passthru && !Passthru.isUndef();
2411   if (!HasPassthru && !Passthru)
2412     Passthru = DAG.getUNDEF(VT);
2413   if (VT.isFloatingPoint()) {
2414     // If VL is 1, we could use vfmv.s.f.
2415     if (isOneConstant(VL))
2416       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2417     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2418   }
2419 
2420   MVT XLenVT = Subtarget.getXLenVT();
2421 
2422   // Simplest case is that the operand needs to be promoted to XLenVT.
2423   if (Scalar.getValueType().bitsLE(XLenVT)) {
2424     // If the operand is a constant, sign extend to increase our chances
2425     // of being able to use a .vi instruction. ANY_EXTEND would become a
2426     // a zero extend and the simm5 check in isel would fail.
2427     // FIXME: Should we ignore the upper bits in isel instead?
2428     unsigned ExtOpc =
2429         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2430     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2431     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2432     // If VL is 1 and the scalar value won't benefit from immediate, we could
2433     // use vmv.s.x.
2434     if (isOneConstant(VL) &&
2435         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2436       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2437     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2438   }
2439 
2440   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2441          "Unexpected scalar for splat lowering!");
2442 
2443   if (isOneConstant(VL) && isNullConstant(Scalar))
2444     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2445                        DAG.getConstant(0, DL, XLenVT), VL);
2446 
2447   // Otherwise use the more complicated splatting algorithm.
2448   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2449 }
2450 
2451 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2452                                 const RISCVSubtarget &Subtarget) {
2453   // We need to be able to widen elements to the next larger integer type.
2454   if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors())
2455     return false;
2456 
2457   int Size = Mask.size();
2458   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2459 
2460   int Srcs[] = {-1, -1};
2461   for (int i = 0; i != Size; ++i) {
2462     // Ignore undef elements.
2463     if (Mask[i] < 0)
2464       continue;
2465 
2466     // Is this an even or odd element.
2467     int Pol = i % 2;
2468 
2469     // Ensure we consistently use the same source for this element polarity.
2470     int Src = Mask[i] / Size;
2471     if (Srcs[Pol] < 0)
2472       Srcs[Pol] = Src;
2473     if (Srcs[Pol] != Src)
2474       return false;
2475 
2476     // Make sure the element within the source is appropriate for this element
2477     // in the destination.
2478     int Elt = Mask[i] % Size;
2479     if (Elt != i / 2)
2480       return false;
2481   }
2482 
2483   // We need to find a source for each polarity and they can't be the same.
2484   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2485     return false;
2486 
2487   // Swap the sources if the second source was in the even polarity.
2488   SwapSources = Srcs[0] > Srcs[1];
2489 
2490   return true;
2491 }
2492 
2493 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2494 /// and then extract the original number of elements from the rotated result.
2495 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2496 /// returned rotation amount is for a rotate right, where elements move from
2497 /// higher elements to lower elements. \p LoSrc indicates the first source
2498 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2499 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2500 /// 0 or 1 if a rotation is found.
2501 ///
2502 /// NOTE: We talk about rotate to the right which matches how bit shift and
2503 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2504 /// and the table below write vectors with the lowest elements on the left.
2505 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2506   int Size = Mask.size();
2507 
2508   // We need to detect various ways of spelling a rotation:
2509   //   [11, 12, 13, 14, 15,  0,  1,  2]
2510   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2511   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2512   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2513   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2514   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2515   int Rotation = 0;
2516   LoSrc = -1;
2517   HiSrc = -1;
2518   for (int i = 0; i != Size; ++i) {
2519     int M = Mask[i];
2520     if (M < 0)
2521       continue;
2522 
2523     // Determine where a rotate vector would have started.
2524     int StartIdx = i - (M % Size);
2525     // The identity rotation isn't interesting, stop.
2526     if (StartIdx == 0)
2527       return -1;
2528 
2529     // If we found the tail of a vector the rotation must be the missing
2530     // front. If we found the head of a vector, it must be how much of the
2531     // head.
2532     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2533 
2534     if (Rotation == 0)
2535       Rotation = CandidateRotation;
2536     else if (Rotation != CandidateRotation)
2537       // The rotations don't match, so we can't match this mask.
2538       return -1;
2539 
2540     // Compute which value this mask is pointing at.
2541     int MaskSrc = M < Size ? 0 : 1;
2542 
2543     // Compute which of the two target values this index should be assigned to.
2544     // This reflects whether the high elements are remaining or the low elemnts
2545     // are remaining.
2546     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2547 
2548     // Either set up this value if we've not encountered it before, or check
2549     // that it remains consistent.
2550     if (TargetSrc < 0)
2551       TargetSrc = MaskSrc;
2552     else if (TargetSrc != MaskSrc)
2553       // This may be a rotation, but it pulls from the inputs in some
2554       // unsupported interleaving.
2555       return -1;
2556   }
2557 
2558   // Check that we successfully analyzed the mask, and normalize the results.
2559   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2560   assert((LoSrc >= 0 || HiSrc >= 0) &&
2561          "Failed to find a rotated input vector!");
2562 
2563   return Rotation;
2564 }
2565 
2566 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2567                                    const RISCVSubtarget &Subtarget) {
2568   SDValue V1 = Op.getOperand(0);
2569   SDValue V2 = Op.getOperand(1);
2570   SDLoc DL(Op);
2571   MVT XLenVT = Subtarget.getXLenVT();
2572   MVT VT = Op.getSimpleValueType();
2573   unsigned NumElts = VT.getVectorNumElements();
2574   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2575 
2576   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2577 
2578   SDValue TrueMask, VL;
2579   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2580 
2581   if (SVN->isSplat()) {
2582     const int Lane = SVN->getSplatIndex();
2583     if (Lane >= 0) {
2584       MVT SVT = VT.getVectorElementType();
2585 
2586       // Turn splatted vector load into a strided load with an X0 stride.
2587       SDValue V = V1;
2588       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2589       // with undef.
2590       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2591       int Offset = Lane;
2592       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2593         int OpElements =
2594             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2595         V = V.getOperand(Offset / OpElements);
2596         Offset %= OpElements;
2597       }
2598 
2599       // We need to ensure the load isn't atomic or volatile.
2600       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2601         auto *Ld = cast<LoadSDNode>(V);
2602         Offset *= SVT.getStoreSize();
2603         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2604                                                    TypeSize::Fixed(Offset), DL);
2605 
2606         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2607         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2608           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2609           SDValue IntID =
2610               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2611           SDValue Ops[] = {Ld->getChain(),
2612                            IntID,
2613                            DAG.getUNDEF(ContainerVT),
2614                            NewAddr,
2615                            DAG.getRegister(RISCV::X0, XLenVT),
2616                            VL};
2617           SDValue NewLoad = DAG.getMemIntrinsicNode(
2618               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2619               DAG.getMachineFunction().getMachineMemOperand(
2620                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2621           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2622           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2623         }
2624 
2625         // Otherwise use a scalar load and splat. This will give the best
2626         // opportunity to fold a splat into the operation. ISel can turn it into
2627         // the x0 strided load if we aren't able to fold away the select.
2628         if (SVT.isFloatingPoint())
2629           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2630                           Ld->getPointerInfo().getWithOffset(Offset),
2631                           Ld->getOriginalAlign(),
2632                           Ld->getMemOperand()->getFlags());
2633         else
2634           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2635                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2636                              Ld->getOriginalAlign(),
2637                              Ld->getMemOperand()->getFlags());
2638         DAG.makeEquivalentMemoryOrdering(Ld, V);
2639 
2640         unsigned Opc =
2641             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2642         SDValue Splat =
2643             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2644         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2645       }
2646 
2647       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2648       assert(Lane < (int)NumElts && "Unexpected lane!");
2649       SDValue Gather =
2650           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2651                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2652       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2653     }
2654   }
2655 
2656   ArrayRef<int> Mask = SVN->getMask();
2657 
2658   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2659   // be undef which can be handled with a single SLIDEDOWN/UP.
2660   int LoSrc, HiSrc;
2661   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2662   if (Rotation > 0) {
2663     SDValue LoV, HiV;
2664     if (LoSrc >= 0) {
2665       LoV = LoSrc == 0 ? V1 : V2;
2666       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2667     }
2668     if (HiSrc >= 0) {
2669       HiV = HiSrc == 0 ? V1 : V2;
2670       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2671     }
2672 
2673     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2674     // to slide LoV up by (NumElts - Rotation).
2675     unsigned InvRotate = NumElts - Rotation;
2676 
2677     SDValue Res = DAG.getUNDEF(ContainerVT);
2678     if (HiV) {
2679       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2680       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2681       // causes multiple vsetvlis in some test cases such as lowering
2682       // reduce.mul
2683       SDValue DownVL = VL;
2684       if (LoV)
2685         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2686       Res =
2687           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2688                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2689     }
2690     if (LoV)
2691       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2692                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2693 
2694     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2695   }
2696 
2697   // Detect an interleave shuffle and lower to
2698   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2699   bool SwapSources;
2700   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2701     // Swap sources if needed.
2702     if (SwapSources)
2703       std::swap(V1, V2);
2704 
2705     // Extract the lower half of the vectors.
2706     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2707     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2708                      DAG.getConstant(0, DL, XLenVT));
2709     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2710                      DAG.getConstant(0, DL, XLenVT));
2711 
2712     // Double the element width and halve the number of elements in an int type.
2713     unsigned EltBits = VT.getScalarSizeInBits();
2714     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2715     MVT WideIntVT =
2716         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2717     // Convert this to a scalable vector. We need to base this on the
2718     // destination size to ensure there's always a type with a smaller LMUL.
2719     MVT WideIntContainerVT =
2720         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2721 
2722     // Convert sources to scalable vectors with the same element count as the
2723     // larger type.
2724     MVT HalfContainerVT = MVT::getVectorVT(
2725         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2726     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2727     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2728 
2729     // Cast sources to integer.
2730     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2731     MVT IntHalfVT =
2732         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2733     V1 = DAG.getBitcast(IntHalfVT, V1);
2734     V2 = DAG.getBitcast(IntHalfVT, V2);
2735 
2736     // Freeze V2 since we use it twice and we need to be sure that the add and
2737     // multiply see the same value.
2738     V2 = DAG.getFreeze(V2);
2739 
2740     // Recreate TrueMask using the widened type's element count.
2741     MVT MaskVT =
2742         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2743     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2744 
2745     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2746     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2747                               V2, TrueMask, VL);
2748     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2749     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2750                                      DAG.getUNDEF(IntHalfVT),
2751                                      DAG.getAllOnesConstant(DL, XLenVT));
2752     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2753                                    V2, Multiplier, TrueMask, VL);
2754     // Add the new copies to our previous addition giving us 2^eltbits copies of
2755     // V2. This is equivalent to shifting V2 left by eltbits. This should
2756     // combine with the vwmulu.vv above to form vwmaccu.vv.
2757     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2758                       TrueMask, VL);
2759     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2760     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2761     // vector VT.
2762     ContainerVT =
2763         MVT::getVectorVT(VT.getVectorElementType(),
2764                          WideIntContainerVT.getVectorElementCount() * 2);
2765     Add = DAG.getBitcast(ContainerVT, Add);
2766     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2767   }
2768 
2769   // Detect shuffles which can be re-expressed as vector selects; these are
2770   // shuffles in which each element in the destination is taken from an element
2771   // at the corresponding index in either source vectors.
2772   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2773     int MaskIndex = MaskIdx.value();
2774     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2775   });
2776 
2777   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2778 
2779   SmallVector<SDValue> MaskVals;
2780   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2781   // merged with a second vrgather.
2782   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2783 
2784   // By default we preserve the original operand order, and use a mask to
2785   // select LHS as true and RHS as false. However, since RVV vector selects may
2786   // feature splats but only on the LHS, we may choose to invert our mask and
2787   // instead select between RHS and LHS.
2788   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2789   bool InvertMask = IsSelect == SwapOps;
2790 
2791   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2792   // half.
2793   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2794 
2795   // Now construct the mask that will be used by the vselect or blended
2796   // vrgather operation. For vrgathers, construct the appropriate indices into
2797   // each vector.
2798   for (int MaskIndex : Mask) {
2799     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2800     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2801     if (!IsSelect) {
2802       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2803       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2804                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2805                                      : DAG.getUNDEF(XLenVT));
2806       GatherIndicesRHS.push_back(
2807           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2808                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2809       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2810         ++LHSIndexCounts[MaskIndex];
2811       if (!IsLHSOrUndefIndex)
2812         ++RHSIndexCounts[MaskIndex - NumElts];
2813     }
2814   }
2815 
2816   if (SwapOps) {
2817     std::swap(V1, V2);
2818     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2819   }
2820 
2821   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2822   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2823   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2824 
2825   if (IsSelect)
2826     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2827 
2828   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2829     // On such a large vector we're unable to use i8 as the index type.
2830     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2831     // may involve vector splitting if we're already at LMUL=8, or our
2832     // user-supplied maximum fixed-length LMUL.
2833     return SDValue();
2834   }
2835 
2836   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2837   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2838   MVT IndexVT = VT.changeTypeToInteger();
2839   // Since we can't introduce illegal index types at this stage, use i16 and
2840   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2841   // than XLenVT.
2842   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2843     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2844     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2845   }
2846 
2847   MVT IndexContainerVT =
2848       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2849 
2850   SDValue Gather;
2851   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2852   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2853   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2854     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2855                               Subtarget);
2856   } else {
2857     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2858     // If only one index is used, we can use a "splat" vrgather.
2859     // TODO: We can splat the most-common index and fix-up any stragglers, if
2860     // that's beneficial.
2861     if (LHSIndexCounts.size() == 1) {
2862       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2863       Gather =
2864           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2865                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2866     } else {
2867       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2868       LHSIndices =
2869           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2870 
2871       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2872                            TrueMask, VL);
2873     }
2874   }
2875 
2876   // If a second vector operand is used by this shuffle, blend it in with an
2877   // additional vrgather.
2878   if (!V2.isUndef()) {
2879     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2880     // If only one index is used, we can use a "splat" vrgather.
2881     // TODO: We can splat the most-common index and fix-up any stragglers, if
2882     // that's beneficial.
2883     if (RHSIndexCounts.size() == 1) {
2884       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2885       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2886                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2887     } else {
2888       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2889       RHSIndices =
2890           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2891       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2892                        VL);
2893     }
2894 
2895     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2896     SelectMask =
2897         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2898 
2899     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2900                          Gather, VL);
2901   }
2902 
2903   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2904 }
2905 
2906 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2907   // Support splats for any type. These should type legalize well.
2908   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2909     return true;
2910 
2911   // Only support legal VTs for other shuffles for now.
2912   if (!isTypeLegal(VT))
2913     return false;
2914 
2915   MVT SVT = VT.getSimpleVT();
2916 
2917   bool SwapSources;
2918   int LoSrc, HiSrc;
2919   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2920          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2921 }
2922 
2923 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2924                                      SDLoc DL, SelectionDAG &DAG,
2925                                      const RISCVSubtarget &Subtarget) {
2926   if (VT.isScalableVector())
2927     return DAG.getFPExtendOrRound(Op, DL, VT);
2928   assert(VT.isFixedLengthVector() &&
2929          "Unexpected value type for RVV FP extend/round lowering");
2930   SDValue Mask, VL;
2931   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2932   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2933                         ? RISCVISD::FP_EXTEND_VL
2934                         : RISCVISD::FP_ROUND_VL;
2935   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2936 }
2937 
2938 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2939 // the exponent.
2940 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2941   MVT VT = Op.getSimpleValueType();
2942   unsigned EltSize = VT.getScalarSizeInBits();
2943   SDValue Src = Op.getOperand(0);
2944   SDLoc DL(Op);
2945 
2946   // We need a FP type that can represent the value.
2947   // TODO: Use f16 for i8 when possible?
2948   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2949   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2950 
2951   // Legal types should have been checked in the RISCVTargetLowering
2952   // constructor.
2953   // TODO: Splitting may make sense in some cases.
2954   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2955          "Expected legal float type!");
2956 
2957   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2958   // The trailing zero count is equal to log2 of this single bit value.
2959   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2960     SDValue Neg =
2961         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2962     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2963   }
2964 
2965   // We have a legal FP type, convert to it.
2966   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2967   // Bitcast to integer and shift the exponent to the LSB.
2968   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2969   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2970   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2971   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2972                               DAG.getConstant(ShiftAmt, DL, IntVT));
2973   // Truncate back to original type to allow vnsrl.
2974   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2975   // The exponent contains log2 of the value in biased form.
2976   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2977 
2978   // For trailing zeros, we just need to subtract the bias.
2979   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2980     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2981                        DAG.getConstant(ExponentBias, DL, VT));
2982 
2983   // For leading zeros, we need to remove the bias and convert from log2 to
2984   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2985   unsigned Adjust = ExponentBias + (EltSize - 1);
2986   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2987 }
2988 
2989 // While RVV has alignment restrictions, we should always be able to load as a
2990 // legal equivalently-sized byte-typed vector instead. This method is
2991 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2992 // the load is already correctly-aligned, it returns SDValue().
2993 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2994                                                     SelectionDAG &DAG) const {
2995   auto *Load = cast<LoadSDNode>(Op);
2996   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2997 
2998   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2999                                      Load->getMemoryVT(),
3000                                      *Load->getMemOperand()))
3001     return SDValue();
3002 
3003   SDLoc DL(Op);
3004   MVT VT = Op.getSimpleValueType();
3005   unsigned EltSizeBits = VT.getScalarSizeInBits();
3006   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3007          "Unexpected unaligned RVV load type");
3008   MVT NewVT =
3009       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3010   assert(NewVT.isValid() &&
3011          "Expecting equally-sized RVV vector types to be legal");
3012   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
3013                           Load->getPointerInfo(), Load->getOriginalAlign(),
3014                           Load->getMemOperand()->getFlags());
3015   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
3016 }
3017 
3018 // While RVV has alignment restrictions, we should always be able to store as a
3019 // legal equivalently-sized byte-typed vector instead. This method is
3020 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
3021 // returns SDValue() if the store is already correctly aligned.
3022 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
3023                                                      SelectionDAG &DAG) const {
3024   auto *Store = cast<StoreSDNode>(Op);
3025   assert(Store && Store->getValue().getValueType().isVector() &&
3026          "Expected vector store");
3027 
3028   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3029                                      Store->getMemoryVT(),
3030                                      *Store->getMemOperand()))
3031     return SDValue();
3032 
3033   SDLoc DL(Op);
3034   SDValue StoredVal = Store->getValue();
3035   MVT VT = StoredVal.getSimpleValueType();
3036   unsigned EltSizeBits = VT.getScalarSizeInBits();
3037   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3038          "Unexpected unaligned RVV store type");
3039   MVT NewVT =
3040       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3041   assert(NewVT.isValid() &&
3042          "Expecting equally-sized RVV vector types to be legal");
3043   StoredVal = DAG.getBitcast(NewVT, StoredVal);
3044   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
3045                       Store->getPointerInfo(), Store->getOriginalAlign(),
3046                       Store->getMemOperand()->getFlags());
3047 }
3048 
3049 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
3050                                             SelectionDAG &DAG) const {
3051   switch (Op.getOpcode()) {
3052   default:
3053     report_fatal_error("unimplemented operand");
3054   case ISD::GlobalAddress:
3055     return lowerGlobalAddress(Op, DAG);
3056   case ISD::BlockAddress:
3057     return lowerBlockAddress(Op, DAG);
3058   case ISD::ConstantPool:
3059     return lowerConstantPool(Op, DAG);
3060   case ISD::JumpTable:
3061     return lowerJumpTable(Op, DAG);
3062   case ISD::GlobalTLSAddress:
3063     return lowerGlobalTLSAddress(Op, DAG);
3064   case ISD::SELECT:
3065     return lowerSELECT(Op, DAG);
3066   case ISD::BRCOND:
3067     return lowerBRCOND(Op, DAG);
3068   case ISD::VASTART:
3069     return lowerVASTART(Op, DAG);
3070   case ISD::FRAMEADDR:
3071     return lowerFRAMEADDR(Op, DAG);
3072   case ISD::RETURNADDR:
3073     return lowerRETURNADDR(Op, DAG);
3074   case ISD::SHL_PARTS:
3075     return lowerShiftLeftParts(Op, DAG);
3076   case ISD::SRA_PARTS:
3077     return lowerShiftRightParts(Op, DAG, true);
3078   case ISD::SRL_PARTS:
3079     return lowerShiftRightParts(Op, DAG, false);
3080   case ISD::BITCAST: {
3081     SDLoc DL(Op);
3082     EVT VT = Op.getValueType();
3083     SDValue Op0 = Op.getOperand(0);
3084     EVT Op0VT = Op0.getValueType();
3085     MVT XLenVT = Subtarget.getXLenVT();
3086     if (VT.isFixedLengthVector()) {
3087       // We can handle fixed length vector bitcasts with a simple replacement
3088       // in isel.
3089       if (Op0VT.isFixedLengthVector())
3090         return Op;
3091       // When bitcasting from scalar to fixed-length vector, insert the scalar
3092       // into a one-element vector of the result type, and perform a vector
3093       // bitcast.
3094       if (!Op0VT.isVector()) {
3095         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3096         if (!isTypeLegal(BVT))
3097           return SDValue();
3098         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3099                                               DAG.getUNDEF(BVT), Op0,
3100                                               DAG.getConstant(0, DL, XLenVT)));
3101       }
3102       return SDValue();
3103     }
3104     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3105     // thus: bitcast the vector to a one-element vector type whose element type
3106     // is the same as the result type, and extract the first element.
3107     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3108       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3109       if (!isTypeLegal(BVT))
3110         return SDValue();
3111       SDValue BVec = DAG.getBitcast(BVT, Op0);
3112       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3113                          DAG.getConstant(0, DL, XLenVT));
3114     }
3115     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3116       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3117       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3118       return FPConv;
3119     }
3120     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3121         Subtarget.hasStdExtF()) {
3122       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3123       SDValue FPConv =
3124           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3125       return FPConv;
3126     }
3127     return SDValue();
3128   }
3129   case ISD::INTRINSIC_WO_CHAIN:
3130     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3131   case ISD::INTRINSIC_W_CHAIN:
3132     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3133   case ISD::INTRINSIC_VOID:
3134     return LowerINTRINSIC_VOID(Op, DAG);
3135   case ISD::BSWAP:
3136   case ISD::BITREVERSE: {
3137     MVT VT = Op.getSimpleValueType();
3138     SDLoc DL(Op);
3139     if (Subtarget.hasStdExtZbp()) {
3140       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3141       // Start with the maximum immediate value which is the bitwidth - 1.
3142       unsigned Imm = VT.getSizeInBits() - 1;
3143       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3144       if (Op.getOpcode() == ISD::BSWAP)
3145         Imm &= ~0x7U;
3146       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3147                          DAG.getConstant(Imm, DL, VT));
3148     }
3149     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3150     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3151     // Expand bitreverse to a bswap(rev8) followed by brev8.
3152     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3153     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3154     // as brev8 by an isel pattern.
3155     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3156                        DAG.getConstant(7, DL, VT));
3157   }
3158   case ISD::FSHL:
3159   case ISD::FSHR: {
3160     MVT VT = Op.getSimpleValueType();
3161     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3162     SDLoc DL(Op);
3163     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3164     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3165     // accidentally setting the extra bit.
3166     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3167     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3168                                 DAG.getConstant(ShAmtWidth, DL, VT));
3169     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3170     // instruction use different orders. fshl will return its first operand for
3171     // shift of zero, fshr will return its second operand. fsl and fsr both
3172     // return rs1 so the ISD nodes need to have different operand orders.
3173     // Shift amount is in rs2.
3174     SDValue Op0 = Op.getOperand(0);
3175     SDValue Op1 = Op.getOperand(1);
3176     unsigned Opc = RISCVISD::FSL;
3177     if (Op.getOpcode() == ISD::FSHR) {
3178       std::swap(Op0, Op1);
3179       Opc = RISCVISD::FSR;
3180     }
3181     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3182   }
3183   case ISD::TRUNCATE: {
3184     SDLoc DL(Op);
3185     MVT VT = Op.getSimpleValueType();
3186     // Only custom-lower vector truncates
3187     if (!VT.isVector())
3188       return Op;
3189 
3190     // Truncates to mask types are handled differently
3191     if (VT.getVectorElementType() == MVT::i1)
3192       return lowerVectorMaskTrunc(Op, DAG);
3193 
3194     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
3195     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
3196     // truncate by one power of two at a time.
3197     MVT DstEltVT = VT.getVectorElementType();
3198 
3199     SDValue Src = Op.getOperand(0);
3200     MVT SrcVT = Src.getSimpleValueType();
3201     MVT SrcEltVT = SrcVT.getVectorElementType();
3202 
3203     assert(DstEltVT.bitsLT(SrcEltVT) &&
3204            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
3205            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
3206            "Unexpected vector truncate lowering");
3207 
3208     MVT ContainerVT = SrcVT;
3209     if (SrcVT.isFixedLengthVector()) {
3210       ContainerVT = getContainerForFixedLengthVector(SrcVT);
3211       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3212     }
3213 
3214     SDValue Result = Src;
3215     SDValue Mask, VL;
3216     std::tie(Mask, VL) =
3217         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
3218     LLVMContext &Context = *DAG.getContext();
3219     const ElementCount Count = ContainerVT.getVectorElementCount();
3220     do {
3221       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
3222       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
3223       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
3224                            Mask, VL);
3225     } while (SrcEltVT != DstEltVT);
3226 
3227     if (SrcVT.isFixedLengthVector())
3228       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3229 
3230     return Result;
3231   }
3232   case ISD::ANY_EXTEND:
3233   case ISD::ZERO_EXTEND:
3234     if (Op.getOperand(0).getValueType().isVector() &&
3235         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3236       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3237     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3238   case ISD::SIGN_EXTEND:
3239     if (Op.getOperand(0).getValueType().isVector() &&
3240         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3241       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3242     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3243   case ISD::SPLAT_VECTOR_PARTS:
3244     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3245   case ISD::INSERT_VECTOR_ELT:
3246     return lowerINSERT_VECTOR_ELT(Op, DAG);
3247   case ISD::EXTRACT_VECTOR_ELT:
3248     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3249   case ISD::VSCALE: {
3250     MVT VT = Op.getSimpleValueType();
3251     SDLoc DL(Op);
3252     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3253     // We define our scalable vector types for lmul=1 to use a 64 bit known
3254     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3255     // vscale as VLENB / 8.
3256     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3257     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3258       report_fatal_error("Support for VLEN==32 is incomplete.");
3259     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3260       // We assume VLENB is a multiple of 8. We manually choose the best shift
3261       // here because SimplifyDemandedBits isn't always able to simplify it.
3262       uint64_t Val = Op.getConstantOperandVal(0);
3263       if (isPowerOf2_64(Val)) {
3264         uint64_t Log2 = Log2_64(Val);
3265         if (Log2 < 3)
3266           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3267                              DAG.getConstant(3 - Log2, DL, VT));
3268         if (Log2 > 3)
3269           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3270                              DAG.getConstant(Log2 - 3, DL, VT));
3271         return VLENB;
3272       }
3273       // If the multiplier is a multiple of 8, scale it down to avoid needing
3274       // to shift the VLENB value.
3275       if ((Val % 8) == 0)
3276         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3277                            DAG.getConstant(Val / 8, DL, VT));
3278     }
3279 
3280     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3281                                  DAG.getConstant(3, DL, VT));
3282     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3283   }
3284   case ISD::FPOWI: {
3285     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3286     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3287     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3288         Op.getOperand(1).getValueType() == MVT::i32) {
3289       SDLoc DL(Op);
3290       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3291       SDValue Powi =
3292           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3293       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3294                          DAG.getIntPtrConstant(0, DL));
3295     }
3296     return SDValue();
3297   }
3298   case ISD::FP_EXTEND: {
3299     // RVV can only do fp_extend to types double the size as the source. We
3300     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3301     // via f32.
3302     SDLoc DL(Op);
3303     MVT VT = Op.getSimpleValueType();
3304     SDValue Src = Op.getOperand(0);
3305     MVT SrcVT = Src.getSimpleValueType();
3306 
3307     // Prepare any fixed-length vector operands.
3308     MVT ContainerVT = VT;
3309     if (SrcVT.isFixedLengthVector()) {
3310       ContainerVT = getContainerForFixedLengthVector(VT);
3311       MVT SrcContainerVT =
3312           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3313       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3314     }
3315 
3316     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3317         SrcVT.getVectorElementType() != MVT::f16) {
3318       // For scalable vectors, we only need to close the gap between
3319       // vXf16->vXf64.
3320       if (!VT.isFixedLengthVector())
3321         return Op;
3322       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3323       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3324       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3325     }
3326 
3327     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3328     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3329     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3330         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3331 
3332     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3333                                            DL, DAG, Subtarget);
3334     if (VT.isFixedLengthVector())
3335       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3336     return Extend;
3337   }
3338   case ISD::FP_ROUND: {
3339     // RVV can only do fp_round to types half the size as the source. We
3340     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3341     // conversion instruction.
3342     SDLoc DL(Op);
3343     MVT VT = Op.getSimpleValueType();
3344     SDValue Src = Op.getOperand(0);
3345     MVT SrcVT = Src.getSimpleValueType();
3346 
3347     // Prepare any fixed-length vector operands.
3348     MVT ContainerVT = VT;
3349     if (VT.isFixedLengthVector()) {
3350       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3351       ContainerVT =
3352           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3353       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3354     }
3355 
3356     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3357         SrcVT.getVectorElementType() != MVT::f64) {
3358       // For scalable vectors, we only need to close the gap between
3359       // vXf64<->vXf16.
3360       if (!VT.isFixedLengthVector())
3361         return Op;
3362       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3363       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3364       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3365     }
3366 
3367     SDValue Mask, VL;
3368     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3369 
3370     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3371     SDValue IntermediateRound =
3372         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3373     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3374                                           DL, DAG, Subtarget);
3375 
3376     if (VT.isFixedLengthVector())
3377       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3378     return Round;
3379   }
3380   case ISD::FP_TO_SINT:
3381   case ISD::FP_TO_UINT:
3382   case ISD::SINT_TO_FP:
3383   case ISD::UINT_TO_FP: {
3384     // RVV can only do fp<->int conversions to types half/double the size as
3385     // the source. We custom-lower any conversions that do two hops into
3386     // sequences.
3387     MVT VT = Op.getSimpleValueType();
3388     if (!VT.isVector())
3389       return Op;
3390     SDLoc DL(Op);
3391     SDValue Src = Op.getOperand(0);
3392     MVT EltVT = VT.getVectorElementType();
3393     MVT SrcVT = Src.getSimpleValueType();
3394     MVT SrcEltVT = SrcVT.getVectorElementType();
3395     unsigned EltSize = EltVT.getSizeInBits();
3396     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3397     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3398            "Unexpected vector element types");
3399 
3400     bool IsInt2FP = SrcEltVT.isInteger();
3401     // Widening conversions
3402     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
3403       if (IsInt2FP) {
3404         // Do a regular integer sign/zero extension then convert to float.
3405         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
3406                                       VT.getVectorElementCount());
3407         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3408                                  ? ISD::ZERO_EXTEND
3409                                  : ISD::SIGN_EXTEND;
3410         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3411         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3412       }
3413       // FP2Int
3414       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3415       // Do one doubling fp_extend then complete the operation by converting
3416       // to int.
3417       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3418       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3419       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3420     }
3421 
3422     // Narrowing conversions
3423     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
3424       if (IsInt2FP) {
3425         // One narrowing int_to_fp, then an fp_round.
3426         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3427         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3428         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3429         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3430       }
3431       // FP2Int
3432       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3433       // representable by the integer, the result is poison.
3434       MVT IVecVT =
3435           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
3436                            VT.getVectorElementCount());
3437       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3438       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3439     }
3440 
3441     // Scalable vectors can exit here. Patterns will handle equally-sized
3442     // conversions halving/doubling ones.
3443     if (!VT.isFixedLengthVector())
3444       return Op;
3445 
3446     // For fixed-length vectors we lower to a custom "VL" node.
3447     unsigned RVVOpc = 0;
3448     switch (Op.getOpcode()) {
3449     default:
3450       llvm_unreachable("Impossible opcode");
3451     case ISD::FP_TO_SINT:
3452       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3453       break;
3454     case ISD::FP_TO_UINT:
3455       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3456       break;
3457     case ISD::SINT_TO_FP:
3458       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3459       break;
3460     case ISD::UINT_TO_FP:
3461       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3462       break;
3463     }
3464 
3465     MVT ContainerVT, SrcContainerVT;
3466     // Derive the reference container type from the larger vector type.
3467     if (SrcEltSize > EltSize) {
3468       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3469       ContainerVT =
3470           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3471     } else {
3472       ContainerVT = getContainerForFixedLengthVector(VT);
3473       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3474     }
3475 
3476     SDValue Mask, VL;
3477     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3478 
3479     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3480     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3481     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3482   }
3483   case ISD::FP_TO_SINT_SAT:
3484   case ISD::FP_TO_UINT_SAT:
3485     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3486   case ISD::FTRUNC:
3487   case ISD::FCEIL:
3488   case ISD::FFLOOR:
3489     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3490   case ISD::FROUND:
3491     return lowerFROUND(Op, DAG);
3492   case ISD::VECREDUCE_ADD:
3493   case ISD::VECREDUCE_UMAX:
3494   case ISD::VECREDUCE_SMAX:
3495   case ISD::VECREDUCE_UMIN:
3496   case ISD::VECREDUCE_SMIN:
3497     return lowerVECREDUCE(Op, DAG);
3498   case ISD::VECREDUCE_AND:
3499   case ISD::VECREDUCE_OR:
3500   case ISD::VECREDUCE_XOR:
3501     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3502       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3503     return lowerVECREDUCE(Op, DAG);
3504   case ISD::VECREDUCE_FADD:
3505   case ISD::VECREDUCE_SEQ_FADD:
3506   case ISD::VECREDUCE_FMIN:
3507   case ISD::VECREDUCE_FMAX:
3508     return lowerFPVECREDUCE(Op, DAG);
3509   case ISD::VP_REDUCE_ADD:
3510   case ISD::VP_REDUCE_UMAX:
3511   case ISD::VP_REDUCE_SMAX:
3512   case ISD::VP_REDUCE_UMIN:
3513   case ISD::VP_REDUCE_SMIN:
3514   case ISD::VP_REDUCE_FADD:
3515   case ISD::VP_REDUCE_SEQ_FADD:
3516   case ISD::VP_REDUCE_FMIN:
3517   case ISD::VP_REDUCE_FMAX:
3518     return lowerVPREDUCE(Op, DAG);
3519   case ISD::VP_REDUCE_AND:
3520   case ISD::VP_REDUCE_OR:
3521   case ISD::VP_REDUCE_XOR:
3522     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3523       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3524     return lowerVPREDUCE(Op, DAG);
3525   case ISD::INSERT_SUBVECTOR:
3526     return lowerINSERT_SUBVECTOR(Op, DAG);
3527   case ISD::EXTRACT_SUBVECTOR:
3528     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3529   case ISD::STEP_VECTOR:
3530     return lowerSTEP_VECTOR(Op, DAG);
3531   case ISD::VECTOR_REVERSE:
3532     return lowerVECTOR_REVERSE(Op, DAG);
3533   case ISD::VECTOR_SPLICE:
3534     return lowerVECTOR_SPLICE(Op, DAG);
3535   case ISD::BUILD_VECTOR:
3536     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3537   case ISD::SPLAT_VECTOR:
3538     if (Op.getValueType().getVectorElementType() == MVT::i1)
3539       return lowerVectorMaskSplat(Op, DAG);
3540     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3541   case ISD::VECTOR_SHUFFLE:
3542     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3543   case ISD::CONCAT_VECTORS: {
3544     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3545     // better than going through the stack, as the default expansion does.
3546     SDLoc DL(Op);
3547     MVT VT = Op.getSimpleValueType();
3548     unsigned NumOpElts =
3549         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3550     SDValue Vec = DAG.getUNDEF(VT);
3551     for (const auto &OpIdx : enumerate(Op->ops())) {
3552       SDValue SubVec = OpIdx.value();
3553       // Don't insert undef subvectors.
3554       if (SubVec.isUndef())
3555         continue;
3556       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3557                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3558     }
3559     return Vec;
3560   }
3561   case ISD::LOAD:
3562     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3563       return V;
3564     if (Op.getValueType().isFixedLengthVector())
3565       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3566     return Op;
3567   case ISD::STORE:
3568     if (auto V = expandUnalignedRVVStore(Op, DAG))
3569       return V;
3570     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3571       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3572     return Op;
3573   case ISD::MLOAD:
3574   case ISD::VP_LOAD:
3575     return lowerMaskedLoad(Op, DAG);
3576   case ISD::MSTORE:
3577   case ISD::VP_STORE:
3578     return lowerMaskedStore(Op, DAG);
3579   case ISD::SETCC:
3580     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3581   case ISD::ADD:
3582     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3583   case ISD::SUB:
3584     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3585   case ISD::MUL:
3586     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3587   case ISD::MULHS:
3588     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3589   case ISD::MULHU:
3590     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3591   case ISD::AND:
3592     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3593                                               RISCVISD::AND_VL);
3594   case ISD::OR:
3595     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3596                                               RISCVISD::OR_VL);
3597   case ISD::XOR:
3598     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3599                                               RISCVISD::XOR_VL);
3600   case ISD::SDIV:
3601     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3602   case ISD::SREM:
3603     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3604   case ISD::UDIV:
3605     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3606   case ISD::UREM:
3607     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3608   case ISD::SHL:
3609   case ISD::SRA:
3610   case ISD::SRL:
3611     if (Op.getSimpleValueType().isFixedLengthVector())
3612       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3613     // This can be called for an i32 shift amount that needs to be promoted.
3614     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3615            "Unexpected custom legalisation");
3616     return SDValue();
3617   case ISD::SADDSAT:
3618     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3619   case ISD::UADDSAT:
3620     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3621   case ISD::SSUBSAT:
3622     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3623   case ISD::USUBSAT:
3624     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3625   case ISD::FADD:
3626     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3627   case ISD::FSUB:
3628     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3629   case ISD::FMUL:
3630     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3631   case ISD::FDIV:
3632     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3633   case ISD::FNEG:
3634     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3635   case ISD::FABS:
3636     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3637   case ISD::FSQRT:
3638     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3639   case ISD::FMA:
3640     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3641   case ISD::SMIN:
3642     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3643   case ISD::SMAX:
3644     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3645   case ISD::UMIN:
3646     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3647   case ISD::UMAX:
3648     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3649   case ISD::FMINNUM:
3650     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3651   case ISD::FMAXNUM:
3652     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3653   case ISD::ABS:
3654     return lowerABS(Op, DAG);
3655   case ISD::CTLZ_ZERO_UNDEF:
3656   case ISD::CTTZ_ZERO_UNDEF:
3657     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3658   case ISD::VSELECT:
3659     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3660   case ISD::FCOPYSIGN:
3661     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3662   case ISD::MGATHER:
3663   case ISD::VP_GATHER:
3664     return lowerMaskedGather(Op, DAG);
3665   case ISD::MSCATTER:
3666   case ISD::VP_SCATTER:
3667     return lowerMaskedScatter(Op, DAG);
3668   case ISD::FLT_ROUNDS_:
3669     return lowerGET_ROUNDING(Op, DAG);
3670   case ISD::SET_ROUNDING:
3671     return lowerSET_ROUNDING(Op, DAG);
3672   case ISD::VP_SELECT:
3673     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3674   case ISD::VP_MERGE:
3675     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3676   case ISD::VP_ADD:
3677     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3678   case ISD::VP_SUB:
3679     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3680   case ISD::VP_MUL:
3681     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3682   case ISD::VP_SDIV:
3683     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3684   case ISD::VP_UDIV:
3685     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3686   case ISD::VP_SREM:
3687     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3688   case ISD::VP_UREM:
3689     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3690   case ISD::VP_AND:
3691     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3692   case ISD::VP_OR:
3693     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3694   case ISD::VP_XOR:
3695     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3696   case ISD::VP_ASHR:
3697     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3698   case ISD::VP_LSHR:
3699     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3700   case ISD::VP_SHL:
3701     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3702   case ISD::VP_FADD:
3703     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3704   case ISD::VP_FSUB:
3705     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3706   case ISD::VP_FMUL:
3707     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3708   case ISD::VP_FDIV:
3709     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3710   case ISD::VP_FNEG:
3711     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3712   case ISD::VP_FMA:
3713     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3714   }
3715 }
3716 
3717 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3718                              SelectionDAG &DAG, unsigned Flags) {
3719   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3720 }
3721 
3722 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3723                              SelectionDAG &DAG, unsigned Flags) {
3724   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3725                                    Flags);
3726 }
3727 
3728 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3729                              SelectionDAG &DAG, unsigned Flags) {
3730   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3731                                    N->getOffset(), Flags);
3732 }
3733 
3734 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3735                              SelectionDAG &DAG, unsigned Flags) {
3736   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3737 }
3738 
3739 template <class NodeTy>
3740 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3741                                      bool IsLocal) const {
3742   SDLoc DL(N);
3743   EVT Ty = getPointerTy(DAG.getDataLayout());
3744 
3745   if (isPositionIndependent()) {
3746     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3747     if (IsLocal)
3748       // Use PC-relative addressing to access the symbol. This generates the
3749       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3750       // %pcrel_lo(auipc)).
3751       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3752 
3753     // Use PC-relative addressing to access the GOT for this symbol, then load
3754     // the address from the GOT. This generates the pattern (PseudoLA sym),
3755     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3756     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3757   }
3758 
3759   switch (getTargetMachine().getCodeModel()) {
3760   default:
3761     report_fatal_error("Unsupported code model for lowering");
3762   case CodeModel::Small: {
3763     // Generate a sequence for accessing addresses within the first 2 GiB of
3764     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3765     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3766     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3767     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3768     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3769   }
3770   case CodeModel::Medium: {
3771     // Generate a sequence for accessing addresses within any 2GiB range within
3772     // the address space. This generates the pattern (PseudoLLA sym), which
3773     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3774     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3775     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3776   }
3777   }
3778 }
3779 
3780 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3781                                                 SelectionDAG &DAG) const {
3782   SDLoc DL(Op);
3783   EVT Ty = Op.getValueType();
3784   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3785   int64_t Offset = N->getOffset();
3786   MVT XLenVT = Subtarget.getXLenVT();
3787 
3788   const GlobalValue *GV = N->getGlobal();
3789   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3790   SDValue Addr = getAddr(N, DAG, IsLocal);
3791 
3792   // In order to maximise the opportunity for common subexpression elimination,
3793   // emit a separate ADD node for the global address offset instead of folding
3794   // it in the global address node. Later peephole optimisations may choose to
3795   // fold it back in when profitable.
3796   if (Offset != 0)
3797     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3798                        DAG.getConstant(Offset, DL, XLenVT));
3799   return Addr;
3800 }
3801 
3802 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3803                                                SelectionDAG &DAG) const {
3804   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3805 
3806   return getAddr(N, DAG);
3807 }
3808 
3809 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3810                                                SelectionDAG &DAG) const {
3811   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3812 
3813   return getAddr(N, DAG);
3814 }
3815 
3816 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3817                                             SelectionDAG &DAG) const {
3818   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3819 
3820   return getAddr(N, DAG);
3821 }
3822 
3823 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3824                                               SelectionDAG &DAG,
3825                                               bool UseGOT) const {
3826   SDLoc DL(N);
3827   EVT Ty = getPointerTy(DAG.getDataLayout());
3828   const GlobalValue *GV = N->getGlobal();
3829   MVT XLenVT = Subtarget.getXLenVT();
3830 
3831   if (UseGOT) {
3832     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3833     // load the address from the GOT and add the thread pointer. This generates
3834     // the pattern (PseudoLA_TLS_IE sym), which expands to
3835     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3836     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3837     SDValue Load =
3838         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3839 
3840     // Add the thread pointer.
3841     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3842     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3843   }
3844 
3845   // Generate a sequence for accessing the address relative to the thread
3846   // pointer, with the appropriate adjustment for the thread pointer offset.
3847   // This generates the pattern
3848   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3849   SDValue AddrHi =
3850       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3851   SDValue AddrAdd =
3852       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3853   SDValue AddrLo =
3854       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3855 
3856   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3857   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3858   SDValue MNAdd = SDValue(
3859       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3860       0);
3861   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3862 }
3863 
3864 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3865                                                SelectionDAG &DAG) const {
3866   SDLoc DL(N);
3867   EVT Ty = getPointerTy(DAG.getDataLayout());
3868   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3869   const GlobalValue *GV = N->getGlobal();
3870 
3871   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3872   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3873   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3874   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3875   SDValue Load =
3876       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3877 
3878   // Prepare argument list to generate call.
3879   ArgListTy Args;
3880   ArgListEntry Entry;
3881   Entry.Node = Load;
3882   Entry.Ty = CallTy;
3883   Args.push_back(Entry);
3884 
3885   // Setup call to __tls_get_addr.
3886   TargetLowering::CallLoweringInfo CLI(DAG);
3887   CLI.setDebugLoc(DL)
3888       .setChain(DAG.getEntryNode())
3889       .setLibCallee(CallingConv::C, CallTy,
3890                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3891                     std::move(Args));
3892 
3893   return LowerCallTo(CLI).first;
3894 }
3895 
3896 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3897                                                    SelectionDAG &DAG) const {
3898   SDLoc DL(Op);
3899   EVT Ty = Op.getValueType();
3900   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3901   int64_t Offset = N->getOffset();
3902   MVT XLenVT = Subtarget.getXLenVT();
3903 
3904   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3905 
3906   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3907       CallingConv::GHC)
3908     report_fatal_error("In GHC calling convention TLS is not supported");
3909 
3910   SDValue Addr;
3911   switch (Model) {
3912   case TLSModel::LocalExec:
3913     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3914     break;
3915   case TLSModel::InitialExec:
3916     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3917     break;
3918   case TLSModel::LocalDynamic:
3919   case TLSModel::GeneralDynamic:
3920     Addr = getDynamicTLSAddr(N, DAG);
3921     break;
3922   }
3923 
3924   // In order to maximise the opportunity for common subexpression elimination,
3925   // emit a separate ADD node for the global address offset instead of folding
3926   // it in the global address node. Later peephole optimisations may choose to
3927   // fold it back in when profitable.
3928   if (Offset != 0)
3929     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3930                        DAG.getConstant(Offset, DL, XLenVT));
3931   return Addr;
3932 }
3933 
3934 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3935   SDValue CondV = Op.getOperand(0);
3936   SDValue TrueV = Op.getOperand(1);
3937   SDValue FalseV = Op.getOperand(2);
3938   SDLoc DL(Op);
3939   MVT VT = Op.getSimpleValueType();
3940   MVT XLenVT = Subtarget.getXLenVT();
3941 
3942   // Lower vector SELECTs to VSELECTs by splatting the condition.
3943   if (VT.isVector()) {
3944     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3945     SDValue CondSplat = VT.isScalableVector()
3946                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3947                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3948     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3949   }
3950 
3951   // If the result type is XLenVT and CondV is the output of a SETCC node
3952   // which also operated on XLenVT inputs, then merge the SETCC node into the
3953   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3954   // compare+branch instructions. i.e.:
3955   // (select (setcc lhs, rhs, cc), truev, falsev)
3956   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3957   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3958       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3959     SDValue LHS = CondV.getOperand(0);
3960     SDValue RHS = CondV.getOperand(1);
3961     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3962     ISD::CondCode CCVal = CC->get();
3963 
3964     // Special case for a select of 2 constants that have a diffence of 1.
3965     // Normally this is done by DAGCombine, but if the select is introduced by
3966     // type legalization or op legalization, we miss it. Restricting to SETLT
3967     // case for now because that is what signed saturating add/sub need.
3968     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3969     // but we would probably want to swap the true/false values if the condition
3970     // is SETGE/SETLE to avoid an XORI.
3971     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3972         CCVal == ISD::SETLT) {
3973       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3974       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3975       if (TrueVal - 1 == FalseVal)
3976         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3977       if (TrueVal + 1 == FalseVal)
3978         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3979     }
3980 
3981     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3982 
3983     SDValue TargetCC = DAG.getCondCode(CCVal);
3984     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3985     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3986   }
3987 
3988   // Otherwise:
3989   // (select condv, truev, falsev)
3990   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3991   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3992   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3993 
3994   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3995 
3996   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3997 }
3998 
3999 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4000   SDValue CondV = Op.getOperand(1);
4001   SDLoc DL(Op);
4002   MVT XLenVT = Subtarget.getXLenVT();
4003 
4004   if (CondV.getOpcode() == ISD::SETCC &&
4005       CondV.getOperand(0).getValueType() == XLenVT) {
4006     SDValue LHS = CondV.getOperand(0);
4007     SDValue RHS = CondV.getOperand(1);
4008     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
4009 
4010     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
4011 
4012     SDValue TargetCC = DAG.getCondCode(CCVal);
4013     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4014                        LHS, RHS, TargetCC, Op.getOperand(2));
4015   }
4016 
4017   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4018                      CondV, DAG.getConstant(0, DL, XLenVT),
4019                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
4020 }
4021 
4022 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
4023   MachineFunction &MF = DAG.getMachineFunction();
4024   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
4025 
4026   SDLoc DL(Op);
4027   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
4028                                  getPointerTy(MF.getDataLayout()));
4029 
4030   // vastart just stores the address of the VarArgsFrameIndex slot into the
4031   // memory location argument.
4032   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4033   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
4034                       MachinePointerInfo(SV));
4035 }
4036 
4037 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
4038                                             SelectionDAG &DAG) const {
4039   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4040   MachineFunction &MF = DAG.getMachineFunction();
4041   MachineFrameInfo &MFI = MF.getFrameInfo();
4042   MFI.setFrameAddressIsTaken(true);
4043   Register FrameReg = RI.getFrameRegister(MF);
4044   int XLenInBytes = Subtarget.getXLen() / 8;
4045 
4046   EVT VT = Op.getValueType();
4047   SDLoc DL(Op);
4048   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
4049   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4050   while (Depth--) {
4051     int Offset = -(XLenInBytes * 2);
4052     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
4053                               DAG.getIntPtrConstant(Offset, DL));
4054     FrameAddr =
4055         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
4056   }
4057   return FrameAddr;
4058 }
4059 
4060 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
4061                                              SelectionDAG &DAG) const {
4062   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4063   MachineFunction &MF = DAG.getMachineFunction();
4064   MachineFrameInfo &MFI = MF.getFrameInfo();
4065   MFI.setReturnAddressIsTaken(true);
4066   MVT XLenVT = Subtarget.getXLenVT();
4067   int XLenInBytes = Subtarget.getXLen() / 8;
4068 
4069   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4070     return SDValue();
4071 
4072   EVT VT = Op.getValueType();
4073   SDLoc DL(Op);
4074   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4075   if (Depth) {
4076     int Off = -XLenInBytes;
4077     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4078     SDValue Offset = DAG.getConstant(Off, DL, VT);
4079     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4080                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4081                        MachinePointerInfo());
4082   }
4083 
4084   // Return the value of the return address register, marking it an implicit
4085   // live-in.
4086   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
4087   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
4088 }
4089 
4090 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
4091                                                  SelectionDAG &DAG) const {
4092   SDLoc DL(Op);
4093   SDValue Lo = Op.getOperand(0);
4094   SDValue Hi = Op.getOperand(1);
4095   SDValue Shamt = Op.getOperand(2);
4096   EVT VT = Lo.getValueType();
4097 
4098   // if Shamt-XLEN < 0: // Shamt < XLEN
4099   //   Lo = Lo << Shamt
4100   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
4101   // else:
4102   //   Lo = 0
4103   //   Hi = Lo << (Shamt-XLEN)
4104 
4105   SDValue Zero = DAG.getConstant(0, DL, VT);
4106   SDValue One = DAG.getConstant(1, DL, VT);
4107   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4108   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4109   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4110   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4111 
4112   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
4113   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
4114   SDValue ShiftRightLo =
4115       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
4116   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
4117   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
4118   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
4119 
4120   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4121 
4122   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
4123   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4124 
4125   SDValue Parts[2] = {Lo, Hi};
4126   return DAG.getMergeValues(Parts, DL);
4127 }
4128 
4129 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
4130                                                   bool IsSRA) const {
4131   SDLoc DL(Op);
4132   SDValue Lo = Op.getOperand(0);
4133   SDValue Hi = Op.getOperand(1);
4134   SDValue Shamt = Op.getOperand(2);
4135   EVT VT = Lo.getValueType();
4136 
4137   // SRA expansion:
4138   //   if Shamt-XLEN < 0: // Shamt < XLEN
4139   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4140   //     Hi = Hi >>s Shamt
4141   //   else:
4142   //     Lo = Hi >>s (Shamt-XLEN);
4143   //     Hi = Hi >>s (XLEN-1)
4144   //
4145   // SRL expansion:
4146   //   if Shamt-XLEN < 0: // Shamt < XLEN
4147   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4148   //     Hi = Hi >>u Shamt
4149   //   else:
4150   //     Lo = Hi >>u (Shamt-XLEN);
4151   //     Hi = 0;
4152 
4153   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4154 
4155   SDValue Zero = DAG.getConstant(0, DL, VT);
4156   SDValue One = DAG.getConstant(1, DL, VT);
4157   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4158   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4159   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4160   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4161 
4162   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4163   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4164   SDValue ShiftLeftHi =
4165       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4166   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4167   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4168   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4169   SDValue HiFalse =
4170       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4171 
4172   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4173 
4174   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4175   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4176 
4177   SDValue Parts[2] = {Lo, Hi};
4178   return DAG.getMergeValues(Parts, DL);
4179 }
4180 
4181 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4182 // legal equivalently-sized i8 type, so we can use that as a go-between.
4183 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4184                                                   SelectionDAG &DAG) const {
4185   SDLoc DL(Op);
4186   MVT VT = Op.getSimpleValueType();
4187   SDValue SplatVal = Op.getOperand(0);
4188   // All-zeros or all-ones splats are handled specially.
4189   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4190     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4191     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4192   }
4193   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4194     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4195     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4196   }
4197   MVT XLenVT = Subtarget.getXLenVT();
4198   assert(SplatVal.getValueType() == XLenVT &&
4199          "Unexpected type for i1 splat value");
4200   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4201   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4202                          DAG.getConstant(1, DL, XLenVT));
4203   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4204   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4205   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4206 }
4207 
4208 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4209 // illegal (currently only vXi64 RV32).
4210 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4211 // them to VMV_V_X_VL.
4212 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4213                                                      SelectionDAG &DAG) const {
4214   SDLoc DL(Op);
4215   MVT VecVT = Op.getSimpleValueType();
4216   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4217          "Unexpected SPLAT_VECTOR_PARTS lowering");
4218 
4219   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4220   SDValue Lo = Op.getOperand(0);
4221   SDValue Hi = Op.getOperand(1);
4222 
4223   if (VecVT.isFixedLengthVector()) {
4224     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4225     SDLoc DL(Op);
4226     SDValue Mask, VL;
4227     std::tie(Mask, VL) =
4228         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4229 
4230     SDValue Res =
4231         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4232     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4233   }
4234 
4235   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4236     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4237     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4238     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4239     // node in order to try and match RVV vector/scalar instructions.
4240     if ((LoC >> 31) == HiC)
4241       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4242                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4243   }
4244 
4245   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4246   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4247       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4248       Hi.getConstantOperandVal(1) == 31)
4249     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4250                        DAG.getRegister(RISCV::X0, MVT::i32));
4251 
4252   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4253   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4254                      DAG.getUNDEF(VecVT), Lo, Hi,
4255                      DAG.getRegister(RISCV::X0, MVT::i32));
4256 }
4257 
4258 // Custom-lower extensions from mask vectors by using a vselect either with 1
4259 // for zero/any-extension or -1 for sign-extension:
4260 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4261 // Note that any-extension is lowered identically to zero-extension.
4262 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4263                                                 int64_t ExtTrueVal) const {
4264   SDLoc DL(Op);
4265   MVT VecVT = Op.getSimpleValueType();
4266   SDValue Src = Op.getOperand(0);
4267   // Only custom-lower extensions from mask types
4268   assert(Src.getValueType().isVector() &&
4269          Src.getValueType().getVectorElementType() == MVT::i1);
4270 
4271   MVT XLenVT = Subtarget.getXLenVT();
4272   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4273   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4274 
4275   if (VecVT.isScalableVector()) {
4276     // Be careful not to introduce illegal scalar types at this stage, and be
4277     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
4278     // illegal and must be expanded. Since we know that the constants are
4279     // sign-extended 32-bit values, we use VMV_V_X_VL directly.
4280     bool IsRV32E64 =
4281         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
4282 
4283     if (!IsRV32E64) {
4284       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
4285       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
4286     } else {
4287       SplatZero =
4288           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4289                       SplatZero, DAG.getRegister(RISCV::X0, XLenVT));
4290       SplatTrueVal =
4291           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4292                       SplatTrueVal, DAG.getRegister(RISCV::X0, XLenVT));
4293     }
4294 
4295     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4296   }
4297 
4298   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4299   MVT I1ContainerVT =
4300       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4301 
4302   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4303 
4304   SDValue Mask, VL;
4305   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4306 
4307   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4308                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4309   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4310                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4311   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4312                                SplatTrueVal, SplatZero, VL);
4313 
4314   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4315 }
4316 
4317 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4318     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4319   MVT ExtVT = Op.getSimpleValueType();
4320   // Only custom-lower extensions from fixed-length vector types.
4321   if (!ExtVT.isFixedLengthVector())
4322     return Op;
4323   MVT VT = Op.getOperand(0).getSimpleValueType();
4324   // Grab the canonical container type for the extended type. Infer the smaller
4325   // type from that to ensure the same number of vector elements, as we know
4326   // the LMUL will be sufficient to hold the smaller type.
4327   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4328   // Get the extended container type manually to ensure the same number of
4329   // vector elements between source and dest.
4330   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4331                                      ContainerExtVT.getVectorElementCount());
4332 
4333   SDValue Op1 =
4334       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4335 
4336   SDLoc DL(Op);
4337   SDValue Mask, VL;
4338   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4339 
4340   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4341 
4342   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4343 }
4344 
4345 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4346 // setcc operation:
4347 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4348 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
4349                                                   SelectionDAG &DAG) const {
4350   SDLoc DL(Op);
4351   EVT MaskVT = Op.getValueType();
4352   // Only expect to custom-lower truncations to mask types
4353   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4354          "Unexpected type for vector mask lowering");
4355   SDValue Src = Op.getOperand(0);
4356   MVT VecVT = Src.getSimpleValueType();
4357 
4358   // If this is a fixed vector, we need to convert it to a scalable vector.
4359   MVT ContainerVT = VecVT;
4360   if (VecVT.isFixedLengthVector()) {
4361     ContainerVT = getContainerForFixedLengthVector(VecVT);
4362     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4363   }
4364 
4365   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4366   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4367 
4368   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4369                          DAG.getUNDEF(ContainerVT), SplatOne);
4370   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4371                           DAG.getUNDEF(ContainerVT), SplatZero);
4372 
4373   if (VecVT.isScalableVector()) {
4374     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
4375     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
4376   }
4377 
4378   SDValue Mask, VL;
4379   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4380 
4381   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4382   SDValue Trunc =
4383       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4384   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4385                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4386   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4387 }
4388 
4389 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4390 // first position of a vector, and that vector is slid up to the insert index.
4391 // By limiting the active vector length to index+1 and merging with the
4392 // original vector (with an undisturbed tail policy for elements >= VL), we
4393 // achieve the desired result of leaving all elements untouched except the one
4394 // at VL-1, which is replaced with the desired value.
4395 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4396                                                     SelectionDAG &DAG) const {
4397   SDLoc DL(Op);
4398   MVT VecVT = Op.getSimpleValueType();
4399   SDValue Vec = Op.getOperand(0);
4400   SDValue Val = Op.getOperand(1);
4401   SDValue Idx = Op.getOperand(2);
4402 
4403   if (VecVT.getVectorElementType() == MVT::i1) {
4404     // FIXME: For now we just promote to an i8 vector and insert into that,
4405     // but this is probably not optimal.
4406     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4407     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4408     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4409     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4410   }
4411 
4412   MVT ContainerVT = VecVT;
4413   // If the operand is a fixed-length vector, convert to a scalable one.
4414   if (VecVT.isFixedLengthVector()) {
4415     ContainerVT = getContainerForFixedLengthVector(VecVT);
4416     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4417   }
4418 
4419   MVT XLenVT = Subtarget.getXLenVT();
4420 
4421   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4422   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4423   // Even i64-element vectors on RV32 can be lowered without scalar
4424   // legalization if the most-significant 32 bits of the value are not affected
4425   // by the sign-extension of the lower 32 bits.
4426   // TODO: We could also catch sign extensions of a 32-bit value.
4427   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4428     const auto *CVal = cast<ConstantSDNode>(Val);
4429     if (isInt<32>(CVal->getSExtValue())) {
4430       IsLegalInsert = true;
4431       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4432     }
4433   }
4434 
4435   SDValue Mask, VL;
4436   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4437 
4438   SDValue ValInVec;
4439 
4440   if (IsLegalInsert) {
4441     unsigned Opc =
4442         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4443     if (isNullConstant(Idx)) {
4444       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4445       if (!VecVT.isFixedLengthVector())
4446         return Vec;
4447       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4448     }
4449     ValInVec =
4450         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4451   } else {
4452     // On RV32, i64-element vectors must be specially handled to place the
4453     // value at element 0, by using two vslide1up instructions in sequence on
4454     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4455     // this.
4456     SDValue One = DAG.getConstant(1, DL, XLenVT);
4457     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4458     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4459     MVT I32ContainerVT =
4460         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4461     SDValue I32Mask =
4462         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4463     // Limit the active VL to two.
4464     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4465     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4466     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4467     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4468                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4469     // First slide in the hi value, then the lo in underneath it.
4470     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4471                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4472                            I32Mask, InsertI64VL);
4473     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4474                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4475                            I32Mask, InsertI64VL);
4476     // Bitcast back to the right container type.
4477     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4478   }
4479 
4480   // Now that the value is in a vector, slide it into position.
4481   SDValue InsertVL =
4482       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4483   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4484                                 ValInVec, Idx, Mask, InsertVL);
4485   if (!VecVT.isFixedLengthVector())
4486     return Slideup;
4487   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4488 }
4489 
4490 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4491 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4492 // types this is done using VMV_X_S to allow us to glean information about the
4493 // sign bits of the result.
4494 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4495                                                      SelectionDAG &DAG) const {
4496   SDLoc DL(Op);
4497   SDValue Idx = Op.getOperand(1);
4498   SDValue Vec = Op.getOperand(0);
4499   EVT EltVT = Op.getValueType();
4500   MVT VecVT = Vec.getSimpleValueType();
4501   MVT XLenVT = Subtarget.getXLenVT();
4502 
4503   if (VecVT.getVectorElementType() == MVT::i1) {
4504     if (VecVT.isFixedLengthVector()) {
4505       unsigned NumElts = VecVT.getVectorNumElements();
4506       if (NumElts >= 8) {
4507         MVT WideEltVT;
4508         unsigned WidenVecLen;
4509         SDValue ExtractElementIdx;
4510         SDValue ExtractBitIdx;
4511         unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors();
4512         MVT LargestEltVT = MVT::getIntegerVT(
4513             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4514         if (NumElts <= LargestEltVT.getSizeInBits()) {
4515           assert(isPowerOf2_32(NumElts) &&
4516                  "the number of elements should be power of 2");
4517           WideEltVT = MVT::getIntegerVT(NumElts);
4518           WidenVecLen = 1;
4519           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4520           ExtractBitIdx = Idx;
4521         } else {
4522           WideEltVT = LargestEltVT;
4523           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4524           // extract element index = index / element width
4525           ExtractElementIdx = DAG.getNode(
4526               ISD::SRL, DL, XLenVT, Idx,
4527               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4528           // mask bit index = index % element width
4529           ExtractBitIdx = DAG.getNode(
4530               ISD::AND, DL, XLenVT, Idx,
4531               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4532         }
4533         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4534         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4535         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4536                                          Vec, ExtractElementIdx);
4537         // Extract the bit from GPR.
4538         SDValue ShiftRight =
4539             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4540         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4541                            DAG.getConstant(1, DL, XLenVT));
4542       }
4543     }
4544     // Otherwise, promote to an i8 vector and extract from that.
4545     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4546     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4547     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4548   }
4549 
4550   // If this is a fixed vector, we need to convert it to a scalable vector.
4551   MVT ContainerVT = VecVT;
4552   if (VecVT.isFixedLengthVector()) {
4553     ContainerVT = getContainerForFixedLengthVector(VecVT);
4554     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4555   }
4556 
4557   // If the index is 0, the vector is already in the right position.
4558   if (!isNullConstant(Idx)) {
4559     // Use a VL of 1 to avoid processing more elements than we need.
4560     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4561     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4562     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4563     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4564                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4565   }
4566 
4567   if (!EltVT.isInteger()) {
4568     // Floating-point extracts are handled in TableGen.
4569     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4570                        DAG.getConstant(0, DL, XLenVT));
4571   }
4572 
4573   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4574   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4575 }
4576 
4577 // Some RVV intrinsics may claim that they want an integer operand to be
4578 // promoted or expanded.
4579 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4580                                            const RISCVSubtarget &Subtarget) {
4581   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4582           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4583          "Unexpected opcode");
4584 
4585   if (!Subtarget.hasVInstructions())
4586     return SDValue();
4587 
4588   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4589   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4590   SDLoc DL(Op);
4591 
4592   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4593       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4594   if (!II || !II->hasScalarOperand())
4595     return SDValue();
4596 
4597   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4598   assert(SplatOp < Op.getNumOperands());
4599 
4600   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4601   SDValue &ScalarOp = Operands[SplatOp];
4602   MVT OpVT = ScalarOp.getSimpleValueType();
4603   MVT XLenVT = Subtarget.getXLenVT();
4604 
4605   // If this isn't a scalar, or its type is XLenVT we're done.
4606   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4607     return SDValue();
4608 
4609   // Simplest case is that the operand needs to be promoted to XLenVT.
4610   if (OpVT.bitsLT(XLenVT)) {
4611     // If the operand is a constant, sign extend to increase our chances
4612     // of being able to use a .vi instruction. ANY_EXTEND would become a
4613     // a zero extend and the simm5 check in isel would fail.
4614     // FIXME: Should we ignore the upper bits in isel instead?
4615     unsigned ExtOpc =
4616         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4617     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4618     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4619   }
4620 
4621   // Use the previous operand to get the vXi64 VT. The result might be a mask
4622   // VT for compares. Using the previous operand assumes that the previous
4623   // operand will never have a smaller element size than a scalar operand and
4624   // that a widening operation never uses SEW=64.
4625   // NOTE: If this fails the below assert, we can probably just find the
4626   // element count from any operand or result and use it to construct the VT.
4627   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4628   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4629 
4630   // The more complex case is when the scalar is larger than XLenVT.
4631   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4632          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4633 
4634   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4635   // on the instruction to sign-extend since SEW>XLEN.
4636   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4637     if (isInt<32>(CVal->getSExtValue())) {
4638       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4639       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4640     }
4641   }
4642 
4643   switch (IntNo) {
4644   case Intrinsic::riscv_vslide1up:
4645   case Intrinsic::riscv_vslide1down:
4646   case Intrinsic::riscv_vslide1up_mask:
4647   case Intrinsic::riscv_vslide1down_mask: {
4648     // We need to special case these when the scalar is larger than XLen.
4649     unsigned NumOps = Op.getNumOperands();
4650     bool IsMasked = NumOps == 7;
4651 
4652     // Convert the vector source to the equivalent nxvXi32 vector.
4653     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4654     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4655 
4656     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4657                                    DAG.getConstant(0, DL, XLenVT));
4658     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4659                                    DAG.getConstant(1, DL, XLenVT));
4660 
4661     // Double the VL since we halved SEW.
4662     SDValue AVL = getVLOperand(Op);
4663     SDValue I32VL;
4664 
4665     // Optimize for constant AVL
4666     if (isa<ConstantSDNode>(AVL)) {
4667       unsigned EltSize = VT.getScalarSizeInBits();
4668       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4669 
4670       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4671       unsigned MaxVLMAX =
4672           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4673 
4674       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4675       unsigned MinVLMAX =
4676           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4677 
4678       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4679       if (AVLInt <= MinVLMAX) {
4680         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4681       } else if (AVLInt >= 2 * MaxVLMAX) {
4682         // Just set vl to VLMAX in this situation
4683         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4684         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4685         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4686         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4687         SDValue SETVLMAX = DAG.getTargetConstant(
4688             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4689         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4690                             LMUL);
4691       } else {
4692         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4693         // is related to the hardware implementation.
4694         // So let the following code handle
4695       }
4696     }
4697     if (!I32VL) {
4698       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4699       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4700       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4701       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4702       SDValue SETVL =
4703           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4704       // Using vsetvli instruction to get actually used length which related to
4705       // the hardware implementation
4706       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4707                                SEW, LMUL);
4708       I32VL =
4709           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4710     }
4711 
4712     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4713     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, I32VL);
4714 
4715     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4716     // instructions.
4717     SDValue Passthru;
4718     if (IsMasked)
4719       Passthru = DAG.getUNDEF(I32VT);
4720     else
4721       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4722 
4723     if (IntNo == Intrinsic::riscv_vslide1up ||
4724         IntNo == Intrinsic::riscv_vslide1up_mask) {
4725       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4726                         ScalarHi, I32Mask, I32VL);
4727       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4728                         ScalarLo, I32Mask, I32VL);
4729     } else {
4730       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4731                         ScalarLo, I32Mask, I32VL);
4732       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4733                         ScalarHi, I32Mask, I32VL);
4734     }
4735 
4736     // Convert back to nxvXi64.
4737     Vec = DAG.getBitcast(VT, Vec);
4738 
4739     if (!IsMasked)
4740       return Vec;
4741     // Apply mask after the operation.
4742     SDValue Mask = Operands[NumOps - 3];
4743     SDValue MaskedOff = Operands[1];
4744     // Assume Policy operand is the last operand.
4745     uint64_t Policy =
4746         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4747     // We don't need to select maskedoff if it's undef.
4748     if (MaskedOff.isUndef())
4749       return Vec;
4750     // TAMU
4751     if (Policy == RISCVII::TAIL_AGNOSTIC)
4752       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4753                          AVL);
4754     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4755     // It's fine because vmerge does not care mask policy.
4756     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4757                        AVL);
4758   }
4759   }
4760 
4761   // We need to convert the scalar to a splat vector.
4762   // FIXME: Can we implicitly truncate the scalar if it is known to
4763   // be sign extended?
4764   SDValue VL = getVLOperand(Op);
4765   assert(VL.getValueType() == XLenVT);
4766   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4767   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4768 }
4769 
4770 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4771                                                      SelectionDAG &DAG) const {
4772   unsigned IntNo = Op.getConstantOperandVal(0);
4773   SDLoc DL(Op);
4774   MVT XLenVT = Subtarget.getXLenVT();
4775 
4776   switch (IntNo) {
4777   default:
4778     break; // Don't custom lower most intrinsics.
4779   case Intrinsic::thread_pointer: {
4780     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4781     return DAG.getRegister(RISCV::X4, PtrVT);
4782   }
4783   case Intrinsic::riscv_orc_b:
4784   case Intrinsic::riscv_brev8: {
4785     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4786     unsigned Opc =
4787         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4788     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4789                        DAG.getConstant(7, DL, XLenVT));
4790   }
4791   case Intrinsic::riscv_grev:
4792   case Intrinsic::riscv_gorc: {
4793     unsigned Opc =
4794         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4795     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4796   }
4797   case Intrinsic::riscv_zip:
4798   case Intrinsic::riscv_unzip: {
4799     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4800     // For i32 the immediate is 15. For i64 the immediate is 31.
4801     unsigned Opc =
4802         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4803     unsigned BitWidth = Op.getValueSizeInBits();
4804     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4805     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4806                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4807   }
4808   case Intrinsic::riscv_shfl:
4809   case Intrinsic::riscv_unshfl: {
4810     unsigned Opc =
4811         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4812     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4813   }
4814   case Intrinsic::riscv_bcompress:
4815   case Intrinsic::riscv_bdecompress: {
4816     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4817                                                        : RISCVISD::BDECOMPRESS;
4818     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4819   }
4820   case Intrinsic::riscv_bfp:
4821     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4822                        Op.getOperand(2));
4823   case Intrinsic::riscv_fsl:
4824     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4825                        Op.getOperand(2), Op.getOperand(3));
4826   case Intrinsic::riscv_fsr:
4827     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4828                        Op.getOperand(2), Op.getOperand(3));
4829   case Intrinsic::riscv_vmv_x_s:
4830     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4831     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4832                        Op.getOperand(1));
4833   case Intrinsic::riscv_vmv_v_x:
4834     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4835                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4836                             Subtarget);
4837   case Intrinsic::riscv_vfmv_v_f:
4838     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4839                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4840   case Intrinsic::riscv_vmv_s_x: {
4841     SDValue Scalar = Op.getOperand(2);
4842 
4843     if (Scalar.getValueType().bitsLE(XLenVT)) {
4844       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4845       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4846                          Op.getOperand(1), Scalar, Op.getOperand(3));
4847     }
4848 
4849     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4850 
4851     // This is an i64 value that lives in two scalar registers. We have to
4852     // insert this in a convoluted way. First we build vXi64 splat containing
4853     // the/ two values that we assemble using some bit math. Next we'll use
4854     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4855     // to merge element 0 from our splat into the source vector.
4856     // FIXME: This is probably not the best way to do this, but it is
4857     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4858     // point.
4859     //   sw lo, (a0)
4860     //   sw hi, 4(a0)
4861     //   vlse vX, (a0)
4862     //
4863     //   vid.v      vVid
4864     //   vmseq.vx   mMask, vVid, 0
4865     //   vmerge.vvm vDest, vSrc, vVal, mMask
4866     MVT VT = Op.getSimpleValueType();
4867     SDValue Vec = Op.getOperand(1);
4868     SDValue VL = getVLOperand(Op);
4869 
4870     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4871     if (Op.getOperand(1).isUndef())
4872       return SplattedVal;
4873     SDValue SplattedIdx =
4874         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4875                     DAG.getConstant(0, DL, MVT::i32), VL);
4876 
4877     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4878     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4879     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4880     SDValue SelectCond =
4881         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4882                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4883     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4884                        Vec, VL);
4885   }
4886   }
4887 
4888   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4889 }
4890 
4891 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4892                                                     SelectionDAG &DAG) const {
4893   unsigned IntNo = Op.getConstantOperandVal(1);
4894   switch (IntNo) {
4895   default:
4896     break;
4897   case Intrinsic::riscv_masked_strided_load: {
4898     SDLoc DL(Op);
4899     MVT XLenVT = Subtarget.getXLenVT();
4900 
4901     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4902     // the selection of the masked intrinsics doesn't do this for us.
4903     SDValue Mask = Op.getOperand(5);
4904     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4905 
4906     MVT VT = Op->getSimpleValueType(0);
4907     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4908 
4909     SDValue PassThru = Op.getOperand(2);
4910     if (!IsUnmasked) {
4911       MVT MaskVT =
4912           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4913       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4914       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4915     }
4916 
4917     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4918 
4919     SDValue IntID = DAG.getTargetConstant(
4920         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4921         XLenVT);
4922 
4923     auto *Load = cast<MemIntrinsicSDNode>(Op);
4924     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4925     if (IsUnmasked)
4926       Ops.push_back(DAG.getUNDEF(ContainerVT));
4927     else
4928       Ops.push_back(PassThru);
4929     Ops.push_back(Op.getOperand(3)); // Ptr
4930     Ops.push_back(Op.getOperand(4)); // Stride
4931     if (!IsUnmasked)
4932       Ops.push_back(Mask);
4933     Ops.push_back(VL);
4934     if (!IsUnmasked) {
4935       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4936       Ops.push_back(Policy);
4937     }
4938 
4939     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4940     SDValue Result =
4941         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4942                                 Load->getMemoryVT(), Load->getMemOperand());
4943     SDValue Chain = Result.getValue(1);
4944     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4945     return DAG.getMergeValues({Result, Chain}, DL);
4946   }
4947   case Intrinsic::riscv_seg2_load:
4948   case Intrinsic::riscv_seg3_load:
4949   case Intrinsic::riscv_seg4_load:
4950   case Intrinsic::riscv_seg5_load:
4951   case Intrinsic::riscv_seg6_load:
4952   case Intrinsic::riscv_seg7_load:
4953   case Intrinsic::riscv_seg8_load: {
4954     SDLoc DL(Op);
4955     static const Intrinsic::ID VlsegInts[7] = {
4956         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
4957         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
4958         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
4959         Intrinsic::riscv_vlseg8};
4960     unsigned NF = Op->getNumValues() - 1;
4961     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
4962     MVT XLenVT = Subtarget.getXLenVT();
4963     MVT VT = Op->getSimpleValueType(0);
4964     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4965 
4966     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4967     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
4968     auto *Load = cast<MemIntrinsicSDNode>(Op);
4969     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
4970     ContainerVTs.push_back(MVT::Other);
4971     SDVTList VTs = DAG.getVTList(ContainerVTs);
4972     SDValue Result =
4973         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs,
4974                                 {Load->getChain(), IntID, Op.getOperand(2), VL},
4975                                 Load->getMemoryVT(), Load->getMemOperand());
4976     SmallVector<SDValue, 9> Results;
4977     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
4978       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
4979                                                   DAG, Subtarget));
4980     Results.push_back(Result.getValue(NF));
4981     return DAG.getMergeValues(Results, DL);
4982   }
4983   }
4984 
4985   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4986 }
4987 
4988 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4989                                                  SelectionDAG &DAG) const {
4990   unsigned IntNo = Op.getConstantOperandVal(1);
4991   switch (IntNo) {
4992   default:
4993     break;
4994   case Intrinsic::riscv_masked_strided_store: {
4995     SDLoc DL(Op);
4996     MVT XLenVT = Subtarget.getXLenVT();
4997 
4998     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4999     // the selection of the masked intrinsics doesn't do this for us.
5000     SDValue Mask = Op.getOperand(5);
5001     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5002 
5003     SDValue Val = Op.getOperand(2);
5004     MVT VT = Val.getSimpleValueType();
5005     MVT ContainerVT = getContainerForFixedLengthVector(VT);
5006 
5007     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5008     if (!IsUnmasked) {
5009       MVT MaskVT =
5010           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5011       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5012     }
5013 
5014     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5015 
5016     SDValue IntID = DAG.getTargetConstant(
5017         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
5018         XLenVT);
5019 
5020     auto *Store = cast<MemIntrinsicSDNode>(Op);
5021     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
5022     Ops.push_back(Val);
5023     Ops.push_back(Op.getOperand(3)); // Ptr
5024     Ops.push_back(Op.getOperand(4)); // Stride
5025     if (!IsUnmasked)
5026       Ops.push_back(Mask);
5027     Ops.push_back(VL);
5028 
5029     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
5030                                    Ops, Store->getMemoryVT(),
5031                                    Store->getMemOperand());
5032   }
5033   }
5034 
5035   return SDValue();
5036 }
5037 
5038 static MVT getLMUL1VT(MVT VT) {
5039   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
5040          "Unexpected vector MVT");
5041   return MVT::getScalableVectorVT(
5042       VT.getVectorElementType(),
5043       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
5044 }
5045 
5046 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
5047   switch (ISDOpcode) {
5048   default:
5049     llvm_unreachable("Unhandled reduction");
5050   case ISD::VECREDUCE_ADD:
5051     return RISCVISD::VECREDUCE_ADD_VL;
5052   case ISD::VECREDUCE_UMAX:
5053     return RISCVISD::VECREDUCE_UMAX_VL;
5054   case ISD::VECREDUCE_SMAX:
5055     return RISCVISD::VECREDUCE_SMAX_VL;
5056   case ISD::VECREDUCE_UMIN:
5057     return RISCVISD::VECREDUCE_UMIN_VL;
5058   case ISD::VECREDUCE_SMIN:
5059     return RISCVISD::VECREDUCE_SMIN_VL;
5060   case ISD::VECREDUCE_AND:
5061     return RISCVISD::VECREDUCE_AND_VL;
5062   case ISD::VECREDUCE_OR:
5063     return RISCVISD::VECREDUCE_OR_VL;
5064   case ISD::VECREDUCE_XOR:
5065     return RISCVISD::VECREDUCE_XOR_VL;
5066   }
5067 }
5068 
5069 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
5070                                                          SelectionDAG &DAG,
5071                                                          bool IsVP) const {
5072   SDLoc DL(Op);
5073   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5074   MVT VecVT = Vec.getSimpleValueType();
5075   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5076           Op.getOpcode() == ISD::VECREDUCE_OR ||
5077           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5078           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5079           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5080           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5081          "Unexpected reduction lowering");
5082 
5083   MVT XLenVT = Subtarget.getXLenVT();
5084   assert(Op.getValueType() == XLenVT &&
5085          "Expected reduction output to be legalized to XLenVT");
5086 
5087   MVT ContainerVT = VecVT;
5088   if (VecVT.isFixedLengthVector()) {
5089     ContainerVT = getContainerForFixedLengthVector(VecVT);
5090     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5091   }
5092 
5093   SDValue Mask, VL;
5094   if (IsVP) {
5095     Mask = Op.getOperand(2);
5096     VL = Op.getOperand(3);
5097   } else {
5098     std::tie(Mask, VL) =
5099         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5100   }
5101 
5102   unsigned BaseOpc;
5103   ISD::CondCode CC;
5104   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5105 
5106   switch (Op.getOpcode()) {
5107   default:
5108     llvm_unreachable("Unhandled reduction");
5109   case ISD::VECREDUCE_AND:
5110   case ISD::VP_REDUCE_AND: {
5111     // vcpop ~x == 0
5112     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5113     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5114     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5115     CC = ISD::SETEQ;
5116     BaseOpc = ISD::AND;
5117     break;
5118   }
5119   case ISD::VECREDUCE_OR:
5120   case ISD::VP_REDUCE_OR:
5121     // vcpop x != 0
5122     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5123     CC = ISD::SETNE;
5124     BaseOpc = ISD::OR;
5125     break;
5126   case ISD::VECREDUCE_XOR:
5127   case ISD::VP_REDUCE_XOR: {
5128     // ((vcpop x) & 1) != 0
5129     SDValue One = DAG.getConstant(1, DL, XLenVT);
5130     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5131     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5132     CC = ISD::SETNE;
5133     BaseOpc = ISD::XOR;
5134     break;
5135   }
5136   }
5137 
5138   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5139 
5140   if (!IsVP)
5141     return SetCC;
5142 
5143   // Now include the start value in the operation.
5144   // Note that we must return the start value when no elements are operated
5145   // upon. The vcpop instructions we've emitted in each case above will return
5146   // 0 for an inactive vector, and so we've already received the neutral value:
5147   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5148   // can simply include the start value.
5149   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5150 }
5151 
5152 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5153                                             SelectionDAG &DAG) const {
5154   SDLoc DL(Op);
5155   SDValue Vec = Op.getOperand(0);
5156   EVT VecEVT = Vec.getValueType();
5157 
5158   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5159 
5160   // Due to ordering in legalize types we may have a vector type that needs to
5161   // be split. Do that manually so we can get down to a legal type.
5162   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5163          TargetLowering::TypeSplitVector) {
5164     SDValue Lo, Hi;
5165     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5166     VecEVT = Lo.getValueType();
5167     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5168   }
5169 
5170   // TODO: The type may need to be widened rather than split. Or widened before
5171   // it can be split.
5172   if (!isTypeLegal(VecEVT))
5173     return SDValue();
5174 
5175   MVT VecVT = VecEVT.getSimpleVT();
5176   MVT VecEltVT = VecVT.getVectorElementType();
5177   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5178 
5179   MVT ContainerVT = VecVT;
5180   if (VecVT.isFixedLengthVector()) {
5181     ContainerVT = getContainerForFixedLengthVector(VecVT);
5182     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5183   }
5184 
5185   MVT M1VT = getLMUL1VT(ContainerVT);
5186   MVT XLenVT = Subtarget.getXLenVT();
5187 
5188   SDValue Mask, VL;
5189   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5190 
5191   SDValue NeutralElem =
5192       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5193   SDValue IdentitySplat =
5194       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5195                        M1VT, DL, DAG, Subtarget);
5196   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5197                                   IdentitySplat, Mask, VL);
5198   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5199                              DAG.getConstant(0, DL, XLenVT));
5200   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5201 }
5202 
5203 // Given a reduction op, this function returns the matching reduction opcode,
5204 // the vector SDValue and the scalar SDValue required to lower this to a
5205 // RISCVISD node.
5206 static std::tuple<unsigned, SDValue, SDValue>
5207 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5208   SDLoc DL(Op);
5209   auto Flags = Op->getFlags();
5210   unsigned Opcode = Op.getOpcode();
5211   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5212   switch (Opcode) {
5213   default:
5214     llvm_unreachable("Unhandled reduction");
5215   case ISD::VECREDUCE_FADD: {
5216     // Use positive zero if we can. It is cheaper to materialize.
5217     SDValue Zero =
5218         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5219     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5220   }
5221   case ISD::VECREDUCE_SEQ_FADD:
5222     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5223                            Op.getOperand(0));
5224   case ISD::VECREDUCE_FMIN:
5225     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5226                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5227   case ISD::VECREDUCE_FMAX:
5228     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5229                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5230   }
5231 }
5232 
5233 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5234                                               SelectionDAG &DAG) const {
5235   SDLoc DL(Op);
5236   MVT VecEltVT = Op.getSimpleValueType();
5237 
5238   unsigned RVVOpcode;
5239   SDValue VectorVal, ScalarVal;
5240   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5241       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5242   MVT VecVT = VectorVal.getSimpleValueType();
5243 
5244   MVT ContainerVT = VecVT;
5245   if (VecVT.isFixedLengthVector()) {
5246     ContainerVT = getContainerForFixedLengthVector(VecVT);
5247     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5248   }
5249 
5250   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5251   MVT XLenVT = Subtarget.getXLenVT();
5252 
5253   SDValue Mask, VL;
5254   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5255 
5256   SDValue ScalarSplat =
5257       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5258                        M1VT, DL, DAG, Subtarget);
5259   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5260                                   VectorVal, ScalarSplat, Mask, VL);
5261   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5262                      DAG.getConstant(0, DL, XLenVT));
5263 }
5264 
5265 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5266   switch (ISDOpcode) {
5267   default:
5268     llvm_unreachable("Unhandled reduction");
5269   case ISD::VP_REDUCE_ADD:
5270     return RISCVISD::VECREDUCE_ADD_VL;
5271   case ISD::VP_REDUCE_UMAX:
5272     return RISCVISD::VECREDUCE_UMAX_VL;
5273   case ISD::VP_REDUCE_SMAX:
5274     return RISCVISD::VECREDUCE_SMAX_VL;
5275   case ISD::VP_REDUCE_UMIN:
5276     return RISCVISD::VECREDUCE_UMIN_VL;
5277   case ISD::VP_REDUCE_SMIN:
5278     return RISCVISD::VECREDUCE_SMIN_VL;
5279   case ISD::VP_REDUCE_AND:
5280     return RISCVISD::VECREDUCE_AND_VL;
5281   case ISD::VP_REDUCE_OR:
5282     return RISCVISD::VECREDUCE_OR_VL;
5283   case ISD::VP_REDUCE_XOR:
5284     return RISCVISD::VECREDUCE_XOR_VL;
5285   case ISD::VP_REDUCE_FADD:
5286     return RISCVISD::VECREDUCE_FADD_VL;
5287   case ISD::VP_REDUCE_SEQ_FADD:
5288     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5289   case ISD::VP_REDUCE_FMAX:
5290     return RISCVISD::VECREDUCE_FMAX_VL;
5291   case ISD::VP_REDUCE_FMIN:
5292     return RISCVISD::VECREDUCE_FMIN_VL;
5293   }
5294 }
5295 
5296 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5297                                            SelectionDAG &DAG) const {
5298   SDLoc DL(Op);
5299   SDValue Vec = Op.getOperand(1);
5300   EVT VecEVT = Vec.getValueType();
5301 
5302   // TODO: The type may need to be widened rather than split. Or widened before
5303   // it can be split.
5304   if (!isTypeLegal(VecEVT))
5305     return SDValue();
5306 
5307   MVT VecVT = VecEVT.getSimpleVT();
5308   MVT VecEltVT = VecVT.getVectorElementType();
5309   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5310 
5311   MVT ContainerVT = VecVT;
5312   if (VecVT.isFixedLengthVector()) {
5313     ContainerVT = getContainerForFixedLengthVector(VecVT);
5314     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5315   }
5316 
5317   SDValue VL = Op.getOperand(3);
5318   SDValue Mask = Op.getOperand(2);
5319 
5320   MVT M1VT = getLMUL1VT(ContainerVT);
5321   MVT XLenVT = Subtarget.getXLenVT();
5322   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5323 
5324   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5325                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5326                                         DL, DAG, Subtarget);
5327   SDValue Reduction =
5328       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5329   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5330                              DAG.getConstant(0, DL, XLenVT));
5331   if (!VecVT.isInteger())
5332     return Elt0;
5333   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5334 }
5335 
5336 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5337                                                    SelectionDAG &DAG) const {
5338   SDValue Vec = Op.getOperand(0);
5339   SDValue SubVec = Op.getOperand(1);
5340   MVT VecVT = Vec.getSimpleValueType();
5341   MVT SubVecVT = SubVec.getSimpleValueType();
5342 
5343   SDLoc DL(Op);
5344   MVT XLenVT = Subtarget.getXLenVT();
5345   unsigned OrigIdx = Op.getConstantOperandVal(2);
5346   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5347 
5348   // We don't have the ability to slide mask vectors up indexed by their i1
5349   // elements; the smallest we can do is i8. Often we are able to bitcast to
5350   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5351   // into a scalable one, we might not necessarily have enough scalable
5352   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5353   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5354       (OrigIdx != 0 || !Vec.isUndef())) {
5355     if (VecVT.getVectorMinNumElements() >= 8 &&
5356         SubVecVT.getVectorMinNumElements() >= 8) {
5357       assert(OrigIdx % 8 == 0 && "Invalid index");
5358       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5359              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5360              "Unexpected mask vector lowering");
5361       OrigIdx /= 8;
5362       SubVecVT =
5363           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5364                            SubVecVT.isScalableVector());
5365       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5366                                VecVT.isScalableVector());
5367       Vec = DAG.getBitcast(VecVT, Vec);
5368       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5369     } else {
5370       // We can't slide this mask vector up indexed by its i1 elements.
5371       // This poses a problem when we wish to insert a scalable vector which
5372       // can't be re-expressed as a larger type. Just choose the slow path and
5373       // extend to a larger type, then truncate back down.
5374       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5375       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5376       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5377       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5378       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5379                         Op.getOperand(2));
5380       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5381       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5382     }
5383   }
5384 
5385   // If the subvector vector is a fixed-length type, we cannot use subregister
5386   // manipulation to simplify the codegen; we don't know which register of a
5387   // LMUL group contains the specific subvector as we only know the minimum
5388   // register size. Therefore we must slide the vector group up the full
5389   // amount.
5390   if (SubVecVT.isFixedLengthVector()) {
5391     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5392       return Op;
5393     MVT ContainerVT = VecVT;
5394     if (VecVT.isFixedLengthVector()) {
5395       ContainerVT = getContainerForFixedLengthVector(VecVT);
5396       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5397     }
5398     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5399                          DAG.getUNDEF(ContainerVT), SubVec,
5400                          DAG.getConstant(0, DL, XLenVT));
5401     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5402       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5403       return DAG.getBitcast(Op.getValueType(), SubVec);
5404     }
5405     SDValue Mask =
5406         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5407     // Set the vector length to only the number of elements we care about. Note
5408     // that for slideup this includes the offset.
5409     SDValue VL =
5410         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5411     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5412     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5413                                   SubVec, SlideupAmt, Mask, VL);
5414     if (VecVT.isFixedLengthVector())
5415       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5416     return DAG.getBitcast(Op.getValueType(), Slideup);
5417   }
5418 
5419   unsigned SubRegIdx, RemIdx;
5420   std::tie(SubRegIdx, RemIdx) =
5421       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5422           VecVT, SubVecVT, OrigIdx, TRI);
5423 
5424   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5425   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5426                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5427                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5428 
5429   // 1. If the Idx has been completely eliminated and this subvector's size is
5430   // a vector register or a multiple thereof, or the surrounding elements are
5431   // undef, then this is a subvector insert which naturally aligns to a vector
5432   // register. These can easily be handled using subregister manipulation.
5433   // 2. If the subvector is smaller than a vector register, then the insertion
5434   // must preserve the undisturbed elements of the register. We do this by
5435   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5436   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5437   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5438   // LMUL=1 type back into the larger vector (resolving to another subregister
5439   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5440   // to avoid allocating a large register group to hold our subvector.
5441   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5442     return Op;
5443 
5444   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5445   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5446   // (in our case undisturbed). This means we can set up a subvector insertion
5447   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5448   // size of the subvector.
5449   MVT InterSubVT = VecVT;
5450   SDValue AlignedExtract = Vec;
5451   unsigned AlignedIdx = OrigIdx - RemIdx;
5452   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5453     InterSubVT = getLMUL1VT(VecVT);
5454     // Extract a subvector equal to the nearest full vector register type. This
5455     // should resolve to a EXTRACT_SUBREG instruction.
5456     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5457                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5458   }
5459 
5460   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5461   // For scalable vectors this must be further multiplied by vscale.
5462   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5463 
5464   SDValue Mask, VL;
5465   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5466 
5467   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5468   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5469   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5470   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5471 
5472   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5473                        DAG.getUNDEF(InterSubVT), SubVec,
5474                        DAG.getConstant(0, DL, XLenVT));
5475 
5476   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5477                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5478 
5479   // If required, insert this subvector back into the correct vector register.
5480   // This should resolve to an INSERT_SUBREG instruction.
5481   if (VecVT.bitsGT(InterSubVT))
5482     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5483                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5484 
5485   // We might have bitcast from a mask type: cast back to the original type if
5486   // required.
5487   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5488 }
5489 
5490 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5491                                                     SelectionDAG &DAG) const {
5492   SDValue Vec = Op.getOperand(0);
5493   MVT SubVecVT = Op.getSimpleValueType();
5494   MVT VecVT = Vec.getSimpleValueType();
5495 
5496   SDLoc DL(Op);
5497   MVT XLenVT = Subtarget.getXLenVT();
5498   unsigned OrigIdx = Op.getConstantOperandVal(1);
5499   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5500 
5501   // We don't have the ability to slide mask vectors down indexed by their i1
5502   // elements; the smallest we can do is i8. Often we are able to bitcast to
5503   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5504   // from a scalable one, we might not necessarily have enough scalable
5505   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5506   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5507     if (VecVT.getVectorMinNumElements() >= 8 &&
5508         SubVecVT.getVectorMinNumElements() >= 8) {
5509       assert(OrigIdx % 8 == 0 && "Invalid index");
5510       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5511              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5512              "Unexpected mask vector lowering");
5513       OrigIdx /= 8;
5514       SubVecVT =
5515           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5516                            SubVecVT.isScalableVector());
5517       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5518                                VecVT.isScalableVector());
5519       Vec = DAG.getBitcast(VecVT, Vec);
5520     } else {
5521       // We can't slide this mask vector down, indexed by its i1 elements.
5522       // This poses a problem when we wish to extract a scalable vector which
5523       // can't be re-expressed as a larger type. Just choose the slow path and
5524       // extend to a larger type, then truncate back down.
5525       // TODO: We could probably improve this when extracting certain fixed
5526       // from fixed, where we can extract as i8 and shift the correct element
5527       // right to reach the desired subvector?
5528       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5529       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5530       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5531       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5532                         Op.getOperand(1));
5533       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5534       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5535     }
5536   }
5537 
5538   // If the subvector vector is a fixed-length type, we cannot use subregister
5539   // manipulation to simplify the codegen; we don't know which register of a
5540   // LMUL group contains the specific subvector as we only know the minimum
5541   // register size. Therefore we must slide the vector group down the full
5542   // amount.
5543   if (SubVecVT.isFixedLengthVector()) {
5544     // With an index of 0 this is a cast-like subvector, which can be performed
5545     // with subregister operations.
5546     if (OrigIdx == 0)
5547       return Op;
5548     MVT ContainerVT = VecVT;
5549     if (VecVT.isFixedLengthVector()) {
5550       ContainerVT = getContainerForFixedLengthVector(VecVT);
5551       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5552     }
5553     SDValue Mask =
5554         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5555     // Set the vector length to only the number of elements we care about. This
5556     // avoids sliding down elements we're going to discard straight away.
5557     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5558     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5559     SDValue Slidedown =
5560         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5561                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5562     // Now we can use a cast-like subvector extract to get the result.
5563     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5564                             DAG.getConstant(0, DL, XLenVT));
5565     return DAG.getBitcast(Op.getValueType(), Slidedown);
5566   }
5567 
5568   unsigned SubRegIdx, RemIdx;
5569   std::tie(SubRegIdx, RemIdx) =
5570       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5571           VecVT, SubVecVT, OrigIdx, TRI);
5572 
5573   // If the Idx has been completely eliminated then this is a subvector extract
5574   // which naturally aligns to a vector register. These can easily be handled
5575   // using subregister manipulation.
5576   if (RemIdx == 0)
5577     return Op;
5578 
5579   // Else we must shift our vector register directly to extract the subvector.
5580   // Do this using VSLIDEDOWN.
5581 
5582   // If the vector type is an LMUL-group type, extract a subvector equal to the
5583   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5584   // instruction.
5585   MVT InterSubVT = VecVT;
5586   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5587     InterSubVT = getLMUL1VT(VecVT);
5588     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5589                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5590   }
5591 
5592   // Slide this vector register down by the desired number of elements in order
5593   // to place the desired subvector starting at element 0.
5594   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5595   // For scalable vectors this must be further multiplied by vscale.
5596   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5597 
5598   SDValue Mask, VL;
5599   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5600   SDValue Slidedown =
5601       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5602                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5603 
5604   // Now the vector is in the right position, extract our final subvector. This
5605   // should resolve to a COPY.
5606   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5607                           DAG.getConstant(0, DL, XLenVT));
5608 
5609   // We might have bitcast from a mask type: cast back to the original type if
5610   // required.
5611   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5612 }
5613 
5614 // Lower step_vector to the vid instruction. Any non-identity step value must
5615 // be accounted for my manual expansion.
5616 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5617                                               SelectionDAG &DAG) const {
5618   SDLoc DL(Op);
5619   MVT VT = Op.getSimpleValueType();
5620   MVT XLenVT = Subtarget.getXLenVT();
5621   SDValue Mask, VL;
5622   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5623   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5624   uint64_t StepValImm = Op.getConstantOperandVal(0);
5625   if (StepValImm != 1) {
5626     if (isPowerOf2_64(StepValImm)) {
5627       SDValue StepVal =
5628           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5629                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5630       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5631     } else {
5632       SDValue StepVal = lowerScalarSplat(
5633           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5634           VL, VT, DL, DAG, Subtarget);
5635       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5636     }
5637   }
5638   return StepVec;
5639 }
5640 
5641 // Implement vector_reverse using vrgather.vv with indices determined by
5642 // subtracting the id of each element from (VLMAX-1). This will convert
5643 // the indices like so:
5644 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5645 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5646 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5647                                                  SelectionDAG &DAG) const {
5648   SDLoc DL(Op);
5649   MVT VecVT = Op.getSimpleValueType();
5650   unsigned EltSize = VecVT.getScalarSizeInBits();
5651   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5652 
5653   unsigned MaxVLMAX = 0;
5654   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5655   if (VectorBitsMax != 0)
5656     MaxVLMAX =
5657         RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5658 
5659   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5660   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5661 
5662   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5663   // to use vrgatherei16.vv.
5664   // TODO: It's also possible to use vrgatherei16.vv for other types to
5665   // decrease register width for the index calculation.
5666   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5667     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5668     // Reverse each half, then reassemble them in reverse order.
5669     // NOTE: It's also possible that after splitting that VLMAX no longer
5670     // requires vrgatherei16.vv.
5671     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5672       SDValue Lo, Hi;
5673       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5674       EVT LoVT, HiVT;
5675       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5676       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5677       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5678       // Reassemble the low and high pieces reversed.
5679       // FIXME: This is a CONCAT_VECTORS.
5680       SDValue Res =
5681           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5682                       DAG.getIntPtrConstant(0, DL));
5683       return DAG.getNode(
5684           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5685           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5686     }
5687 
5688     // Just promote the int type to i16 which will double the LMUL.
5689     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5690     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5691   }
5692 
5693   MVT XLenVT = Subtarget.getXLenVT();
5694   SDValue Mask, VL;
5695   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5696 
5697   // Calculate VLMAX-1 for the desired SEW.
5698   unsigned MinElts = VecVT.getVectorMinNumElements();
5699   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5700                               DAG.getConstant(MinElts, DL, XLenVT));
5701   SDValue VLMinus1 =
5702       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5703 
5704   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5705   bool IsRV32E64 =
5706       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5707   SDValue SplatVL;
5708   if (!IsRV32E64)
5709     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5710   else
5711     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5712                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5713 
5714   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5715   SDValue Indices =
5716       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5717 
5718   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5719 }
5720 
5721 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5722                                                 SelectionDAG &DAG) const {
5723   SDLoc DL(Op);
5724   SDValue V1 = Op.getOperand(0);
5725   SDValue V2 = Op.getOperand(1);
5726   MVT XLenVT = Subtarget.getXLenVT();
5727   MVT VecVT = Op.getSimpleValueType();
5728 
5729   unsigned MinElts = VecVT.getVectorMinNumElements();
5730   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5731                               DAG.getConstant(MinElts, DL, XLenVT));
5732 
5733   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5734   SDValue DownOffset, UpOffset;
5735   if (ImmValue >= 0) {
5736     // The operand is a TargetConstant, we need to rebuild it as a regular
5737     // constant.
5738     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5739     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5740   } else {
5741     // The operand is a TargetConstant, we need to rebuild it as a regular
5742     // constant rather than negating the original operand.
5743     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5744     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5745   }
5746 
5747   MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5748   SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax);
5749 
5750   SDValue SlideDown =
5751       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5752                   DownOffset, TrueMask, UpOffset);
5753   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5754                      TrueMask,
5755                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5756 }
5757 
5758 SDValue
5759 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5760                                                      SelectionDAG &DAG) const {
5761   SDLoc DL(Op);
5762   auto *Load = cast<LoadSDNode>(Op);
5763 
5764   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5765                                         Load->getMemoryVT(),
5766                                         *Load->getMemOperand()) &&
5767          "Expecting a correctly-aligned load");
5768 
5769   MVT VT = Op.getSimpleValueType();
5770   MVT XLenVT = Subtarget.getXLenVT();
5771   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5772 
5773   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5774 
5775   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5776   SDValue IntID = DAG.getTargetConstant(
5777       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5778   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5779   if (!IsMaskOp)
5780     Ops.push_back(DAG.getUNDEF(ContainerVT));
5781   Ops.push_back(Load->getBasePtr());
5782   Ops.push_back(VL);
5783   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5784   SDValue NewLoad =
5785       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5786                               Load->getMemoryVT(), Load->getMemOperand());
5787 
5788   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5789   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5790 }
5791 
5792 SDValue
5793 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5794                                                       SelectionDAG &DAG) const {
5795   SDLoc DL(Op);
5796   auto *Store = cast<StoreSDNode>(Op);
5797 
5798   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5799                                         Store->getMemoryVT(),
5800                                         *Store->getMemOperand()) &&
5801          "Expecting a correctly-aligned store");
5802 
5803   SDValue StoreVal = Store->getValue();
5804   MVT VT = StoreVal.getSimpleValueType();
5805   MVT XLenVT = Subtarget.getXLenVT();
5806 
5807   // If the size less than a byte, we need to pad with zeros to make a byte.
5808   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5809     VT = MVT::v8i1;
5810     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5811                            DAG.getConstant(0, DL, VT), StoreVal,
5812                            DAG.getIntPtrConstant(0, DL));
5813   }
5814 
5815   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5816 
5817   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5818 
5819   SDValue NewValue =
5820       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5821 
5822   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5823   SDValue IntID = DAG.getTargetConstant(
5824       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5825   return DAG.getMemIntrinsicNode(
5826       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5827       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5828       Store->getMemoryVT(), Store->getMemOperand());
5829 }
5830 
5831 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5832                                              SelectionDAG &DAG) const {
5833   SDLoc DL(Op);
5834   MVT VT = Op.getSimpleValueType();
5835 
5836   const auto *MemSD = cast<MemSDNode>(Op);
5837   EVT MemVT = MemSD->getMemoryVT();
5838   MachineMemOperand *MMO = MemSD->getMemOperand();
5839   SDValue Chain = MemSD->getChain();
5840   SDValue BasePtr = MemSD->getBasePtr();
5841 
5842   SDValue Mask, PassThru, VL;
5843   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5844     Mask = VPLoad->getMask();
5845     PassThru = DAG.getUNDEF(VT);
5846     VL = VPLoad->getVectorLength();
5847   } else {
5848     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5849     Mask = MLoad->getMask();
5850     PassThru = MLoad->getPassThru();
5851   }
5852 
5853   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5854 
5855   MVT XLenVT = Subtarget.getXLenVT();
5856 
5857   MVT ContainerVT = VT;
5858   if (VT.isFixedLengthVector()) {
5859     ContainerVT = getContainerForFixedLengthVector(VT);
5860     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5861     if (!IsUnmasked) {
5862       MVT MaskVT =
5863           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5864       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5865     }
5866   }
5867 
5868   if (!VL)
5869     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5870 
5871   unsigned IntID =
5872       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5873   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5874   if (IsUnmasked)
5875     Ops.push_back(DAG.getUNDEF(ContainerVT));
5876   else
5877     Ops.push_back(PassThru);
5878   Ops.push_back(BasePtr);
5879   if (!IsUnmasked)
5880     Ops.push_back(Mask);
5881   Ops.push_back(VL);
5882   if (!IsUnmasked)
5883     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5884 
5885   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5886 
5887   SDValue Result =
5888       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5889   Chain = Result.getValue(1);
5890 
5891   if (VT.isFixedLengthVector())
5892     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5893 
5894   return DAG.getMergeValues({Result, Chain}, DL);
5895 }
5896 
5897 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5898                                               SelectionDAG &DAG) const {
5899   SDLoc DL(Op);
5900 
5901   const auto *MemSD = cast<MemSDNode>(Op);
5902   EVT MemVT = MemSD->getMemoryVT();
5903   MachineMemOperand *MMO = MemSD->getMemOperand();
5904   SDValue Chain = MemSD->getChain();
5905   SDValue BasePtr = MemSD->getBasePtr();
5906   SDValue Val, Mask, VL;
5907 
5908   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5909     Val = VPStore->getValue();
5910     Mask = VPStore->getMask();
5911     VL = VPStore->getVectorLength();
5912   } else {
5913     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5914     Val = MStore->getValue();
5915     Mask = MStore->getMask();
5916   }
5917 
5918   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5919 
5920   MVT VT = Val.getSimpleValueType();
5921   MVT XLenVT = Subtarget.getXLenVT();
5922 
5923   MVT ContainerVT = VT;
5924   if (VT.isFixedLengthVector()) {
5925     ContainerVT = getContainerForFixedLengthVector(VT);
5926 
5927     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5928     if (!IsUnmasked) {
5929       MVT MaskVT =
5930           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5931       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5932     }
5933   }
5934 
5935   if (!VL)
5936     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5937 
5938   unsigned IntID =
5939       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5940   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5941   Ops.push_back(Val);
5942   Ops.push_back(BasePtr);
5943   if (!IsUnmasked)
5944     Ops.push_back(Mask);
5945   Ops.push_back(VL);
5946 
5947   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5948                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5949 }
5950 
5951 SDValue
5952 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5953                                                       SelectionDAG &DAG) const {
5954   MVT InVT = Op.getOperand(0).getSimpleValueType();
5955   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5956 
5957   MVT VT = Op.getSimpleValueType();
5958 
5959   SDValue Op1 =
5960       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5961   SDValue Op2 =
5962       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5963 
5964   SDLoc DL(Op);
5965   SDValue VL =
5966       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5967 
5968   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5969   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5970 
5971   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5972                             Op.getOperand(2), Mask, VL);
5973 
5974   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5975 }
5976 
5977 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5978     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5979   MVT VT = Op.getSimpleValueType();
5980 
5981   if (VT.getVectorElementType() == MVT::i1)
5982     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5983 
5984   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5985 }
5986 
5987 SDValue
5988 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5989                                                       SelectionDAG &DAG) const {
5990   unsigned Opc;
5991   switch (Op.getOpcode()) {
5992   default: llvm_unreachable("Unexpected opcode!");
5993   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5994   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5995   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5996   }
5997 
5998   return lowerToScalableOp(Op, DAG, Opc);
5999 }
6000 
6001 // Lower vector ABS to smax(X, sub(0, X)).
6002 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
6003   SDLoc DL(Op);
6004   MVT VT = Op.getSimpleValueType();
6005   SDValue X = Op.getOperand(0);
6006 
6007   assert(VT.isFixedLengthVector() && "Unexpected type");
6008 
6009   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6010   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
6011 
6012   SDValue Mask, VL;
6013   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6014 
6015   SDValue SplatZero = DAG.getNode(
6016       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
6017       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
6018   SDValue NegX =
6019       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
6020   SDValue Max =
6021       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
6022 
6023   return convertFromScalableVector(VT, Max, DAG, Subtarget);
6024 }
6025 
6026 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
6027     SDValue Op, SelectionDAG &DAG) const {
6028   SDLoc DL(Op);
6029   MVT VT = Op.getSimpleValueType();
6030   SDValue Mag = Op.getOperand(0);
6031   SDValue Sign = Op.getOperand(1);
6032   assert(Mag.getValueType() == Sign.getValueType() &&
6033          "Can only handle COPYSIGN with matching types.");
6034 
6035   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6036   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
6037   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
6038 
6039   SDValue Mask, VL;
6040   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6041 
6042   SDValue CopySign =
6043       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
6044 
6045   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
6046 }
6047 
6048 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
6049     SDValue Op, SelectionDAG &DAG) const {
6050   MVT VT = Op.getSimpleValueType();
6051   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6052 
6053   MVT I1ContainerVT =
6054       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6055 
6056   SDValue CC =
6057       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
6058   SDValue Op1 =
6059       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6060   SDValue Op2 =
6061       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
6062 
6063   SDLoc DL(Op);
6064   SDValue Mask, VL;
6065   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6066 
6067   SDValue Select =
6068       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
6069 
6070   return convertFromScalableVector(VT, Select, DAG, Subtarget);
6071 }
6072 
6073 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
6074                                                unsigned NewOpc,
6075                                                bool HasMask) const {
6076   MVT VT = Op.getSimpleValueType();
6077   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6078 
6079   // Create list of operands by converting existing ones to scalable types.
6080   SmallVector<SDValue, 6> Ops;
6081   for (const SDValue &V : Op->op_values()) {
6082     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6083 
6084     // Pass through non-vector operands.
6085     if (!V.getValueType().isVector()) {
6086       Ops.push_back(V);
6087       continue;
6088     }
6089 
6090     // "cast" fixed length vector to a scalable vector.
6091     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6092            "Only fixed length vectors are supported!");
6093     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6094   }
6095 
6096   SDLoc DL(Op);
6097   SDValue Mask, VL;
6098   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6099   if (HasMask)
6100     Ops.push_back(Mask);
6101   Ops.push_back(VL);
6102 
6103   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6104   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6105 }
6106 
6107 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6108 // * Operands of each node are assumed to be in the same order.
6109 // * The EVL operand is promoted from i32 to i64 on RV64.
6110 // * Fixed-length vectors are converted to their scalable-vector container
6111 //   types.
6112 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6113                                        unsigned RISCVISDOpc) const {
6114   SDLoc DL(Op);
6115   MVT VT = Op.getSimpleValueType();
6116   SmallVector<SDValue, 4> Ops;
6117 
6118   for (const auto &OpIdx : enumerate(Op->ops())) {
6119     SDValue V = OpIdx.value();
6120     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6121     // Pass through operands which aren't fixed-length vectors.
6122     if (!V.getValueType().isFixedLengthVector()) {
6123       Ops.push_back(V);
6124       continue;
6125     }
6126     // "cast" fixed length vector to a scalable vector.
6127     MVT OpVT = V.getSimpleValueType();
6128     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6129     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6130            "Only fixed length vectors are supported!");
6131     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6132   }
6133 
6134   if (!VT.isFixedLengthVector())
6135     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
6136 
6137   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6138 
6139   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
6140 
6141   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6142 }
6143 
6144 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6145                                             unsigned MaskOpc,
6146                                             unsigned VecOpc) const {
6147   MVT VT = Op.getSimpleValueType();
6148   if (VT.getVectorElementType() != MVT::i1)
6149     return lowerVPOp(Op, DAG, VecOpc);
6150 
6151   // It is safe to drop mask parameter as masked-off elements are undef.
6152   SDValue Op1 = Op->getOperand(0);
6153   SDValue Op2 = Op->getOperand(1);
6154   SDValue VL = Op->getOperand(3);
6155 
6156   MVT ContainerVT = VT;
6157   const bool IsFixed = VT.isFixedLengthVector();
6158   if (IsFixed) {
6159     ContainerVT = getContainerForFixedLengthVector(VT);
6160     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6161     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6162   }
6163 
6164   SDLoc DL(Op);
6165   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6166   if (!IsFixed)
6167     return Val;
6168   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6169 }
6170 
6171 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6172 // matched to a RVV indexed load. The RVV indexed load instructions only
6173 // support the "unsigned unscaled" addressing mode; indices are implicitly
6174 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6175 // signed or scaled indexing is extended to the XLEN value type and scaled
6176 // accordingly.
6177 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6178                                                SelectionDAG &DAG) const {
6179   SDLoc DL(Op);
6180   MVT VT = Op.getSimpleValueType();
6181 
6182   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6183   EVT MemVT = MemSD->getMemoryVT();
6184   MachineMemOperand *MMO = MemSD->getMemOperand();
6185   SDValue Chain = MemSD->getChain();
6186   SDValue BasePtr = MemSD->getBasePtr();
6187 
6188   ISD::LoadExtType LoadExtType;
6189   SDValue Index, Mask, PassThru, VL;
6190 
6191   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6192     Index = VPGN->getIndex();
6193     Mask = VPGN->getMask();
6194     PassThru = DAG.getUNDEF(VT);
6195     VL = VPGN->getVectorLength();
6196     // VP doesn't support extending loads.
6197     LoadExtType = ISD::NON_EXTLOAD;
6198   } else {
6199     // Else it must be a MGATHER.
6200     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6201     Index = MGN->getIndex();
6202     Mask = MGN->getMask();
6203     PassThru = MGN->getPassThru();
6204     LoadExtType = MGN->getExtensionType();
6205   }
6206 
6207   MVT IndexVT = Index.getSimpleValueType();
6208   MVT XLenVT = Subtarget.getXLenVT();
6209 
6210   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6211          "Unexpected VTs!");
6212   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6213   // Targets have to explicitly opt-in for extending vector loads.
6214   assert(LoadExtType == ISD::NON_EXTLOAD &&
6215          "Unexpected extending MGATHER/VP_GATHER");
6216   (void)LoadExtType;
6217 
6218   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6219   // the selection of the masked intrinsics doesn't do this for us.
6220   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6221 
6222   MVT ContainerVT = VT;
6223   if (VT.isFixedLengthVector()) {
6224     // We need to use the larger of the result and index type to determine the
6225     // scalable type to use so we don't increase LMUL for any operand/result.
6226     if (VT.bitsGE(IndexVT)) {
6227       ContainerVT = getContainerForFixedLengthVector(VT);
6228       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6229                                  ContainerVT.getVectorElementCount());
6230     } else {
6231       IndexVT = getContainerForFixedLengthVector(IndexVT);
6232       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
6233                                      IndexVT.getVectorElementCount());
6234     }
6235 
6236     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6237 
6238     if (!IsUnmasked) {
6239       MVT MaskVT =
6240           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6241       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6242       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6243     }
6244   }
6245 
6246   if (!VL)
6247     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6248 
6249   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6250     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6251     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6252                                    VL);
6253     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6254                         TrueMask, VL);
6255   }
6256 
6257   unsigned IntID =
6258       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6259   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6260   if (IsUnmasked)
6261     Ops.push_back(DAG.getUNDEF(ContainerVT));
6262   else
6263     Ops.push_back(PassThru);
6264   Ops.push_back(BasePtr);
6265   Ops.push_back(Index);
6266   if (!IsUnmasked)
6267     Ops.push_back(Mask);
6268   Ops.push_back(VL);
6269   if (!IsUnmasked)
6270     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6271 
6272   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6273   SDValue Result =
6274       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6275   Chain = Result.getValue(1);
6276 
6277   if (VT.isFixedLengthVector())
6278     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6279 
6280   return DAG.getMergeValues({Result, Chain}, DL);
6281 }
6282 
6283 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6284 // matched to a RVV indexed store. The RVV indexed store instructions only
6285 // support the "unsigned unscaled" addressing mode; indices are implicitly
6286 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6287 // signed or scaled indexing is extended to the XLEN value type and scaled
6288 // accordingly.
6289 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6290                                                 SelectionDAG &DAG) const {
6291   SDLoc DL(Op);
6292   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6293   EVT MemVT = MemSD->getMemoryVT();
6294   MachineMemOperand *MMO = MemSD->getMemOperand();
6295   SDValue Chain = MemSD->getChain();
6296   SDValue BasePtr = MemSD->getBasePtr();
6297 
6298   bool IsTruncatingStore = false;
6299   SDValue Index, Mask, Val, VL;
6300 
6301   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6302     Index = VPSN->getIndex();
6303     Mask = VPSN->getMask();
6304     Val = VPSN->getValue();
6305     VL = VPSN->getVectorLength();
6306     // VP doesn't support truncating stores.
6307     IsTruncatingStore = false;
6308   } else {
6309     // Else it must be a MSCATTER.
6310     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6311     Index = MSN->getIndex();
6312     Mask = MSN->getMask();
6313     Val = MSN->getValue();
6314     IsTruncatingStore = MSN->isTruncatingStore();
6315   }
6316 
6317   MVT VT = Val.getSimpleValueType();
6318   MVT IndexVT = Index.getSimpleValueType();
6319   MVT XLenVT = Subtarget.getXLenVT();
6320 
6321   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6322          "Unexpected VTs!");
6323   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6324   // Targets have to explicitly opt-in for extending vector loads and
6325   // truncating vector stores.
6326   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6327   (void)IsTruncatingStore;
6328 
6329   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6330   // the selection of the masked intrinsics doesn't do this for us.
6331   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6332 
6333   MVT ContainerVT = VT;
6334   if (VT.isFixedLengthVector()) {
6335     // We need to use the larger of the value and index type to determine the
6336     // scalable type to use so we don't increase LMUL for any operand/result.
6337     if (VT.bitsGE(IndexVT)) {
6338       ContainerVT = getContainerForFixedLengthVector(VT);
6339       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6340                                  ContainerVT.getVectorElementCount());
6341     } else {
6342       IndexVT = getContainerForFixedLengthVector(IndexVT);
6343       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
6344                                      IndexVT.getVectorElementCount());
6345     }
6346 
6347     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6348     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6349 
6350     if (!IsUnmasked) {
6351       MVT MaskVT =
6352           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6353       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6354     }
6355   }
6356 
6357   if (!VL)
6358     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6359 
6360   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6361     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6362     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6363                                    VL);
6364     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6365                         TrueMask, VL);
6366   }
6367 
6368   unsigned IntID =
6369       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6370   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6371   Ops.push_back(Val);
6372   Ops.push_back(BasePtr);
6373   Ops.push_back(Index);
6374   if (!IsUnmasked)
6375     Ops.push_back(Mask);
6376   Ops.push_back(VL);
6377 
6378   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6379                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6380 }
6381 
6382 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6383                                                SelectionDAG &DAG) const {
6384   const MVT XLenVT = Subtarget.getXLenVT();
6385   SDLoc DL(Op);
6386   SDValue Chain = Op->getOperand(0);
6387   SDValue SysRegNo = DAG.getTargetConstant(
6388       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6389   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6390   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6391 
6392   // Encoding used for rounding mode in RISCV differs from that used in
6393   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6394   // table, which consists of a sequence of 4-bit fields, each representing
6395   // corresponding FLT_ROUNDS mode.
6396   static const int Table =
6397       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6398       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6399       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6400       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6401       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6402 
6403   SDValue Shift =
6404       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6405   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6406                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6407   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6408                                DAG.getConstant(7, DL, XLenVT));
6409 
6410   return DAG.getMergeValues({Masked, Chain}, DL);
6411 }
6412 
6413 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6414                                                SelectionDAG &DAG) const {
6415   const MVT XLenVT = Subtarget.getXLenVT();
6416   SDLoc DL(Op);
6417   SDValue Chain = Op->getOperand(0);
6418   SDValue RMValue = Op->getOperand(1);
6419   SDValue SysRegNo = DAG.getTargetConstant(
6420       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6421 
6422   // Encoding used for rounding mode in RISCV differs from that used in
6423   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6424   // a table, which consists of a sequence of 4-bit fields, each representing
6425   // corresponding RISCV mode.
6426   static const unsigned Table =
6427       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6428       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6429       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6430       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6431       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6432 
6433   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6434                               DAG.getConstant(2, DL, XLenVT));
6435   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6436                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6437   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6438                         DAG.getConstant(0x7, DL, XLenVT));
6439   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6440                      RMValue);
6441 }
6442 
6443 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6444   switch (IntNo) {
6445   default:
6446     llvm_unreachable("Unexpected Intrinsic");
6447   case Intrinsic::riscv_bcompress:
6448     return RISCVISD::BCOMPRESSW;
6449   case Intrinsic::riscv_bdecompress:
6450     return RISCVISD::BDECOMPRESSW;
6451   case Intrinsic::riscv_bfp:
6452     return RISCVISD::BFPW;
6453   case Intrinsic::riscv_fsl:
6454     return RISCVISD::FSLW;
6455   case Intrinsic::riscv_fsr:
6456     return RISCVISD::FSRW;
6457   }
6458 }
6459 
6460 // Converts the given intrinsic to a i64 operation with any extension.
6461 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6462                                          unsigned IntNo) {
6463   SDLoc DL(N);
6464   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6465   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6466   SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6467   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2);
6468   // ReplaceNodeResults requires we maintain the same type for the return value.
6469   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6470 }
6471 
6472 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6473 // form of the given Opcode.
6474 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6475   switch (Opcode) {
6476   default:
6477     llvm_unreachable("Unexpected opcode");
6478   case ISD::SHL:
6479     return RISCVISD::SLLW;
6480   case ISD::SRA:
6481     return RISCVISD::SRAW;
6482   case ISD::SRL:
6483     return RISCVISD::SRLW;
6484   case ISD::SDIV:
6485     return RISCVISD::DIVW;
6486   case ISD::UDIV:
6487     return RISCVISD::DIVUW;
6488   case ISD::UREM:
6489     return RISCVISD::REMUW;
6490   case ISD::ROTL:
6491     return RISCVISD::ROLW;
6492   case ISD::ROTR:
6493     return RISCVISD::RORW;
6494   }
6495 }
6496 
6497 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6498 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6499 // otherwise be promoted to i64, making it difficult to select the
6500 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6501 // type i8/i16/i32 is lost.
6502 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6503                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6504   SDLoc DL(N);
6505   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6506   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6507   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6508   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6509   // ReplaceNodeResults requires we maintain the same type for the return value.
6510   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6511 }
6512 
6513 // Converts the given 32-bit operation to a i64 operation with signed extension
6514 // semantic to reduce the signed extension instructions.
6515 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6516   SDLoc DL(N);
6517   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6518   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6519   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6520   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6521                                DAG.getValueType(MVT::i32));
6522   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6523 }
6524 
6525 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6526                                              SmallVectorImpl<SDValue> &Results,
6527                                              SelectionDAG &DAG) const {
6528   SDLoc DL(N);
6529   switch (N->getOpcode()) {
6530   default:
6531     llvm_unreachable("Don't know how to custom type legalize this operation!");
6532   case ISD::STRICT_FP_TO_SINT:
6533   case ISD::STRICT_FP_TO_UINT:
6534   case ISD::FP_TO_SINT:
6535   case ISD::FP_TO_UINT: {
6536     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6537            "Unexpected custom legalisation");
6538     bool IsStrict = N->isStrictFPOpcode();
6539     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6540                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6541     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6542     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6543         TargetLowering::TypeSoftenFloat) {
6544       if (!isTypeLegal(Op0.getValueType()))
6545         return;
6546       if (IsStrict) {
6547         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6548                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6549         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6550         SDValue Res = DAG.getNode(
6551             Opc, DL, VTs, N->getOperand(0), Op0,
6552             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6553         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6554         Results.push_back(Res.getValue(1));
6555         return;
6556       }
6557       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6558       SDValue Res =
6559           DAG.getNode(Opc, DL, MVT::i64, Op0,
6560                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6561       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6562       return;
6563     }
6564     // If the FP type needs to be softened, emit a library call using the 'si'
6565     // version. If we left it to default legalization we'd end up with 'di'. If
6566     // the FP type doesn't need to be softened just let generic type
6567     // legalization promote the result type.
6568     RTLIB::Libcall LC;
6569     if (IsSigned)
6570       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6571     else
6572       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6573     MakeLibCallOptions CallOptions;
6574     EVT OpVT = Op0.getValueType();
6575     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6576     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6577     SDValue Result;
6578     std::tie(Result, Chain) =
6579         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6580     Results.push_back(Result);
6581     if (IsStrict)
6582       Results.push_back(Chain);
6583     break;
6584   }
6585   case ISD::READCYCLECOUNTER: {
6586     assert(!Subtarget.is64Bit() &&
6587            "READCYCLECOUNTER only has custom type legalization on riscv32");
6588 
6589     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6590     SDValue RCW =
6591         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6592 
6593     Results.push_back(
6594         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6595     Results.push_back(RCW.getValue(2));
6596     break;
6597   }
6598   case ISD::MUL: {
6599     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6600     unsigned XLen = Subtarget.getXLen();
6601     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6602     if (Size > XLen) {
6603       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6604       SDValue LHS = N->getOperand(0);
6605       SDValue RHS = N->getOperand(1);
6606       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6607 
6608       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6609       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6610       // We need exactly one side to be unsigned.
6611       if (LHSIsU == RHSIsU)
6612         return;
6613 
6614       auto MakeMULPair = [&](SDValue S, SDValue U) {
6615         MVT XLenVT = Subtarget.getXLenVT();
6616         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6617         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6618         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6619         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6620         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6621       };
6622 
6623       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6624       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6625 
6626       // The other operand should be signed, but still prefer MULH when
6627       // possible.
6628       if (RHSIsU && LHSIsS && !RHSIsS)
6629         Results.push_back(MakeMULPair(LHS, RHS));
6630       else if (LHSIsU && RHSIsS && !LHSIsS)
6631         Results.push_back(MakeMULPair(RHS, LHS));
6632 
6633       return;
6634     }
6635     LLVM_FALLTHROUGH;
6636   }
6637   case ISD::ADD:
6638   case ISD::SUB:
6639     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6640            "Unexpected custom legalisation");
6641     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6642     break;
6643   case ISD::SHL:
6644   case ISD::SRA:
6645   case ISD::SRL:
6646     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6647            "Unexpected custom legalisation");
6648     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6649       Results.push_back(customLegalizeToWOp(N, DAG));
6650       break;
6651     }
6652 
6653     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6654     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6655     // shift amount.
6656     if (N->getOpcode() == ISD::SHL) {
6657       SDLoc DL(N);
6658       SDValue NewOp0 =
6659           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6660       SDValue NewOp1 =
6661           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6662       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6663       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6664                                    DAG.getValueType(MVT::i32));
6665       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6666     }
6667 
6668     break;
6669   case ISD::ROTL:
6670   case ISD::ROTR:
6671     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6672            "Unexpected custom legalisation");
6673     Results.push_back(customLegalizeToWOp(N, DAG));
6674     break;
6675   case ISD::CTTZ:
6676   case ISD::CTTZ_ZERO_UNDEF:
6677   case ISD::CTLZ:
6678   case ISD::CTLZ_ZERO_UNDEF: {
6679     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6680            "Unexpected custom legalisation");
6681 
6682     SDValue NewOp0 =
6683         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6684     bool IsCTZ =
6685         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6686     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6687     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6688     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6689     return;
6690   }
6691   case ISD::SDIV:
6692   case ISD::UDIV:
6693   case ISD::UREM: {
6694     MVT VT = N->getSimpleValueType(0);
6695     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6696            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6697            "Unexpected custom legalisation");
6698     // Don't promote division/remainder by constant since we should expand those
6699     // to multiply by magic constant.
6700     // FIXME: What if the expansion is disabled for minsize.
6701     if (N->getOperand(1).getOpcode() == ISD::Constant)
6702       return;
6703 
6704     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6705     // the upper 32 bits. For other types we need to sign or zero extend
6706     // based on the opcode.
6707     unsigned ExtOpc = ISD::ANY_EXTEND;
6708     if (VT != MVT::i32)
6709       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6710                                            : ISD::ZERO_EXTEND;
6711 
6712     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6713     break;
6714   }
6715   case ISD::UADDO:
6716   case ISD::USUBO: {
6717     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6718            "Unexpected custom legalisation");
6719     bool IsAdd = N->getOpcode() == ISD::UADDO;
6720     // Create an ADDW or SUBW.
6721     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6722     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6723     SDValue Res =
6724         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6725     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6726                       DAG.getValueType(MVT::i32));
6727 
6728     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
6729     // Since the inputs are sign extended from i32, this is equivalent to
6730     // comparing the lower 32 bits.
6731     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6732     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6733                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
6734 
6735     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6736     Results.push_back(Overflow);
6737     return;
6738   }
6739   case ISD::UADDSAT:
6740   case ISD::USUBSAT: {
6741     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6742            "Unexpected custom legalisation");
6743     if (Subtarget.hasStdExtZbb()) {
6744       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6745       // sign extend allows overflow of the lower 32 bits to be detected on
6746       // the promoted size.
6747       SDValue LHS =
6748           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6749       SDValue RHS =
6750           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6751       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6752       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6753       return;
6754     }
6755 
6756     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6757     // promotion for UADDO/USUBO.
6758     Results.push_back(expandAddSubSat(N, DAG));
6759     return;
6760   }
6761   case ISD::ABS: {
6762     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6763            "Unexpected custom legalisation");
6764           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6765 
6766     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
6767 
6768     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6769 
6770     // Freeze the source so we can increase it's use count.
6771     Src = DAG.getFreeze(Src);
6772 
6773     // Copy sign bit to all bits using the sraiw pattern.
6774     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
6775                                    DAG.getValueType(MVT::i32));
6776     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
6777                            DAG.getConstant(31, DL, MVT::i64));
6778 
6779     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
6780     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
6781 
6782     // NOTE: The result is only required to be anyextended, but sext is
6783     // consistent with type legalization of sub.
6784     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
6785                          DAG.getValueType(MVT::i32));
6786     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6787     return;
6788   }
6789   case ISD::BITCAST: {
6790     EVT VT = N->getValueType(0);
6791     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6792     SDValue Op0 = N->getOperand(0);
6793     EVT Op0VT = Op0.getValueType();
6794     MVT XLenVT = Subtarget.getXLenVT();
6795     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6796       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6797       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6798     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6799                Subtarget.hasStdExtF()) {
6800       SDValue FPConv =
6801           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6802       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6803     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6804                isTypeLegal(Op0VT)) {
6805       // Custom-legalize bitcasts from fixed-length vector types to illegal
6806       // scalar types in order to improve codegen. Bitcast the vector to a
6807       // one-element vector type whose element type is the same as the result
6808       // type, and extract the first element.
6809       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6810       if (isTypeLegal(BVT)) {
6811         SDValue BVec = DAG.getBitcast(BVT, Op0);
6812         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6813                                       DAG.getConstant(0, DL, XLenVT)));
6814       }
6815     }
6816     break;
6817   }
6818   case RISCVISD::GREV:
6819   case RISCVISD::GORC: {
6820     MVT VT = N->getSimpleValueType(0);
6821     MVT XLenVT = Subtarget.getXLenVT();
6822     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
6823            "Unexpected custom legalisation");
6824     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6825     assert((Subtarget.hasStdExtZbp() ||
6826             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
6827              N->getConstantOperandVal(1) == 7)) &&
6828            "Unexpected extension");
6829     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6830     SDValue NewOp1 =
6831         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
6832     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
6833     // ReplaceNodeResults requires we maintain the same type for the return
6834     // value.
6835     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
6836     break;
6837   }
6838   case RISCVISD::SHFL: {
6839     // There is no SHFLIW instruction, but we can just promote the operation.
6840     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6841            "Unexpected custom legalisation");
6842     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6843     SDValue NewOp0 =
6844         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6845     SDValue NewOp1 =
6846         DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6847     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
6848     // ReplaceNodeResults requires we maintain the same type for the return
6849     // value.
6850     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6851     break;
6852   }
6853   case ISD::BSWAP:
6854   case ISD::BITREVERSE: {
6855     MVT VT = N->getSimpleValueType(0);
6856     MVT XLenVT = Subtarget.getXLenVT();
6857     assert((VT == MVT::i8 || VT == MVT::i16 ||
6858             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6859            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6860     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6861     unsigned Imm = VT.getSizeInBits() - 1;
6862     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6863     if (N->getOpcode() == ISD::BSWAP)
6864       Imm &= ~0x7U;
6865     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
6866                                 DAG.getConstant(Imm, DL, XLenVT));
6867     // ReplaceNodeResults requires we maintain the same type for the return
6868     // value.
6869     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6870     break;
6871   }
6872   case ISD::FSHL:
6873   case ISD::FSHR: {
6874     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6875            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6876     SDValue NewOp0 =
6877         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6878     SDValue NewOp1 =
6879         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6880     SDValue NewShAmt =
6881         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6882     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6883     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
6884     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
6885                            DAG.getConstant(0x1f, DL, MVT::i64));
6886     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
6887     // instruction use different orders. fshl will return its first operand for
6888     // shift of zero, fshr will return its second operand. fsl and fsr both
6889     // return rs1 so the ISD nodes need to have different operand orders.
6890     // Shift amount is in rs2.
6891     unsigned Opc = RISCVISD::FSLW;
6892     if (N->getOpcode() == ISD::FSHR) {
6893       std::swap(NewOp0, NewOp1);
6894       Opc = RISCVISD::FSRW;
6895     }
6896     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
6897     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6898     break;
6899   }
6900   case ISD::EXTRACT_VECTOR_ELT: {
6901     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6902     // type is illegal (currently only vXi64 RV32).
6903     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6904     // transferred to the destination register. We issue two of these from the
6905     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6906     // first element.
6907     SDValue Vec = N->getOperand(0);
6908     SDValue Idx = N->getOperand(1);
6909 
6910     // The vector type hasn't been legalized yet so we can't issue target
6911     // specific nodes if it needs legalization.
6912     // FIXME: We would manually legalize if it's important.
6913     if (!isTypeLegal(Vec.getValueType()))
6914       return;
6915 
6916     MVT VecVT = Vec.getSimpleValueType();
6917 
6918     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6919            VecVT.getVectorElementType() == MVT::i64 &&
6920            "Unexpected EXTRACT_VECTOR_ELT legalization");
6921 
6922     // If this is a fixed vector, we need to convert it to a scalable vector.
6923     MVT ContainerVT = VecVT;
6924     if (VecVT.isFixedLengthVector()) {
6925       ContainerVT = getContainerForFixedLengthVector(VecVT);
6926       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6927     }
6928 
6929     MVT XLenVT = Subtarget.getXLenVT();
6930 
6931     // Use a VL of 1 to avoid processing more elements than we need.
6932     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6933     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6934     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6935 
6936     // Unless the index is known to be 0, we must slide the vector down to get
6937     // the desired element into index 0.
6938     if (!isNullConstant(Idx)) {
6939       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6940                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6941     }
6942 
6943     // Extract the lower XLEN bits of the correct vector element.
6944     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6945 
6946     // To extract the upper XLEN bits of the vector element, shift the first
6947     // element right by 32 bits and re-extract the lower XLEN bits.
6948     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6949                                      DAG.getUNDEF(ContainerVT),
6950                                      DAG.getConstant(32, DL, XLenVT), VL);
6951     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6952                                  ThirtyTwoV, Mask, VL);
6953 
6954     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6955 
6956     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6957     break;
6958   }
6959   case ISD::INTRINSIC_WO_CHAIN: {
6960     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6961     switch (IntNo) {
6962     default:
6963       llvm_unreachable(
6964           "Don't know how to custom type legalize this intrinsic!");
6965     case Intrinsic::riscv_grev:
6966     case Intrinsic::riscv_gorc: {
6967       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6968              "Unexpected custom legalisation");
6969       SDValue NewOp1 =
6970           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6971       SDValue NewOp2 =
6972           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6973       unsigned Opc =
6974           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
6975       // If the control is a constant, promote the node by clearing any extra
6976       // bits bits in the control. isel will form greviw/gorciw if the result is
6977       // sign extended.
6978       if (isa<ConstantSDNode>(NewOp2)) {
6979         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6980                              DAG.getConstant(0x1f, DL, MVT::i64));
6981         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
6982       }
6983       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6984       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6985       break;
6986     }
6987     case Intrinsic::riscv_bcompress:
6988     case Intrinsic::riscv_bdecompress:
6989     case Intrinsic::riscv_bfp: {
6990       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6991              "Unexpected custom legalisation");
6992       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
6993       break;
6994     }
6995     case Intrinsic::riscv_fsl:
6996     case Intrinsic::riscv_fsr: {
6997       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6998              "Unexpected custom legalisation");
6999       SDValue NewOp1 =
7000           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7001       SDValue NewOp2 =
7002           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7003       SDValue NewOp3 =
7004           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3));
7005       unsigned Opc = getRISCVWOpcodeByIntr(IntNo);
7006       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3);
7007       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7008       break;
7009     }
7010     case Intrinsic::riscv_orc_b: {
7011       // Lower to the GORCI encoding for orc.b with the operand extended.
7012       SDValue NewOp =
7013           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7014       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7015                                 DAG.getConstant(7, DL, MVT::i64));
7016       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7017       return;
7018     }
7019     case Intrinsic::riscv_shfl:
7020     case Intrinsic::riscv_unshfl: {
7021       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7022              "Unexpected custom legalisation");
7023       SDValue NewOp1 =
7024           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7025       SDValue NewOp2 =
7026           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7027       unsigned Opc =
7028           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7029       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7030       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7031       // will be shuffled the same way as the lower 32 bit half, but the two
7032       // halves won't cross.
7033       if (isa<ConstantSDNode>(NewOp2)) {
7034         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7035                              DAG.getConstant(0xf, DL, MVT::i64));
7036         Opc =
7037             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7038       }
7039       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7040       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7041       break;
7042     }
7043     case Intrinsic::riscv_vmv_x_s: {
7044       EVT VT = N->getValueType(0);
7045       MVT XLenVT = Subtarget.getXLenVT();
7046       if (VT.bitsLT(XLenVT)) {
7047         // Simple case just extract using vmv.x.s and truncate.
7048         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7049                                       Subtarget.getXLenVT(), N->getOperand(1));
7050         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7051         return;
7052       }
7053 
7054       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7055              "Unexpected custom legalization");
7056 
7057       // We need to do the move in two steps.
7058       SDValue Vec = N->getOperand(1);
7059       MVT VecVT = Vec.getSimpleValueType();
7060 
7061       // First extract the lower XLEN bits of the element.
7062       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7063 
7064       // To extract the upper XLEN bits of the vector element, shift the first
7065       // element right by 32 bits and re-extract the lower XLEN bits.
7066       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7067       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7068       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7069       SDValue ThirtyTwoV =
7070           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7071                       DAG.getConstant(32, DL, XLenVT), VL);
7072       SDValue LShr32 =
7073           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7074       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7075 
7076       Results.push_back(
7077           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7078       break;
7079     }
7080     }
7081     break;
7082   }
7083   case ISD::VECREDUCE_ADD:
7084   case ISD::VECREDUCE_AND:
7085   case ISD::VECREDUCE_OR:
7086   case ISD::VECREDUCE_XOR:
7087   case ISD::VECREDUCE_SMAX:
7088   case ISD::VECREDUCE_UMAX:
7089   case ISD::VECREDUCE_SMIN:
7090   case ISD::VECREDUCE_UMIN:
7091     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7092       Results.push_back(V);
7093     break;
7094   case ISD::VP_REDUCE_ADD:
7095   case ISD::VP_REDUCE_AND:
7096   case ISD::VP_REDUCE_OR:
7097   case ISD::VP_REDUCE_XOR:
7098   case ISD::VP_REDUCE_SMAX:
7099   case ISD::VP_REDUCE_UMAX:
7100   case ISD::VP_REDUCE_SMIN:
7101   case ISD::VP_REDUCE_UMIN:
7102     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7103       Results.push_back(V);
7104     break;
7105   case ISD::FLT_ROUNDS_: {
7106     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7107     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7108     Results.push_back(Res.getValue(0));
7109     Results.push_back(Res.getValue(1));
7110     break;
7111   }
7112   }
7113 }
7114 
7115 // A structure to hold one of the bit-manipulation patterns below. Together, a
7116 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7117 //   (or (and (shl x, 1), 0xAAAAAAAA),
7118 //       (and (srl x, 1), 0x55555555))
7119 struct RISCVBitmanipPat {
7120   SDValue Op;
7121   unsigned ShAmt;
7122   bool IsSHL;
7123 
7124   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7125     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7126   }
7127 };
7128 
7129 // Matches patterns of the form
7130 //   (and (shl x, C2), (C1 << C2))
7131 //   (and (srl x, C2), C1)
7132 //   (shl (and x, C1), C2)
7133 //   (srl (and x, (C1 << C2)), C2)
7134 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7135 // The expected masks for each shift amount are specified in BitmanipMasks where
7136 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7137 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7138 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7139 // XLen is 64.
7140 static Optional<RISCVBitmanipPat>
7141 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7142   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7143          "Unexpected number of masks");
7144   Optional<uint64_t> Mask;
7145   // Optionally consume a mask around the shift operation.
7146   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7147     Mask = Op.getConstantOperandVal(1);
7148     Op = Op.getOperand(0);
7149   }
7150   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7151     return None;
7152   bool IsSHL = Op.getOpcode() == ISD::SHL;
7153 
7154   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7155     return None;
7156   uint64_t ShAmt = Op.getConstantOperandVal(1);
7157 
7158   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7159   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7160     return None;
7161   // If we don't have enough masks for 64 bit, then we must be trying to
7162   // match SHFL so we're only allowed to shift 1/4 of the width.
7163   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7164     return None;
7165 
7166   SDValue Src = Op.getOperand(0);
7167 
7168   // The expected mask is shifted left when the AND is found around SHL
7169   // patterns.
7170   //   ((x >> 1) & 0x55555555)
7171   //   ((x << 1) & 0xAAAAAAAA)
7172   bool SHLExpMask = IsSHL;
7173 
7174   if (!Mask) {
7175     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7176     // the mask is all ones: consume that now.
7177     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7178       Mask = Src.getConstantOperandVal(1);
7179       Src = Src.getOperand(0);
7180       // The expected mask is now in fact shifted left for SRL, so reverse the
7181       // decision.
7182       //   ((x & 0xAAAAAAAA) >> 1)
7183       //   ((x & 0x55555555) << 1)
7184       SHLExpMask = !SHLExpMask;
7185     } else {
7186       // Use a default shifted mask of all-ones if there's no AND, truncated
7187       // down to the expected width. This simplifies the logic later on.
7188       Mask = maskTrailingOnes<uint64_t>(Width);
7189       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7190     }
7191   }
7192 
7193   unsigned MaskIdx = Log2_32(ShAmt);
7194   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7195 
7196   if (SHLExpMask)
7197     ExpMask <<= ShAmt;
7198 
7199   if (Mask != ExpMask)
7200     return None;
7201 
7202   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7203 }
7204 
7205 // Matches any of the following bit-manipulation patterns:
7206 //   (and (shl x, 1), (0x55555555 << 1))
7207 //   (and (srl x, 1), 0x55555555)
7208 //   (shl (and x, 0x55555555), 1)
7209 //   (srl (and x, (0x55555555 << 1)), 1)
7210 // where the shift amount and mask may vary thus:
7211 //   [1]  = 0x55555555 / 0xAAAAAAAA
7212 //   [2]  = 0x33333333 / 0xCCCCCCCC
7213 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7214 //   [8]  = 0x00FF00FF / 0xFF00FF00
7215 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7216 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7217 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7218   // These are the unshifted masks which we use to match bit-manipulation
7219   // patterns. They may be shifted left in certain circumstances.
7220   static const uint64_t BitmanipMasks[] = {
7221       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7222       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7223 
7224   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7225 }
7226 
7227 // Match the following pattern as a GREVI(W) operation
7228 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7229 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7230                                const RISCVSubtarget &Subtarget) {
7231   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7232   EVT VT = Op.getValueType();
7233 
7234   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7235     auto LHS = matchGREVIPat(Op.getOperand(0));
7236     auto RHS = matchGREVIPat(Op.getOperand(1));
7237     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7238       SDLoc DL(Op);
7239       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7240                          DAG.getConstant(LHS->ShAmt, DL, VT));
7241     }
7242   }
7243   return SDValue();
7244 }
7245 
7246 // Matches any the following pattern as a GORCI(W) operation
7247 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7248 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7249 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7250 // Note that with the variant of 3.,
7251 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7252 // the inner pattern will first be matched as GREVI and then the outer
7253 // pattern will be matched to GORC via the first rule above.
7254 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7255 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7256                                const RISCVSubtarget &Subtarget) {
7257   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7258   EVT VT = Op.getValueType();
7259 
7260   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7261     SDLoc DL(Op);
7262     SDValue Op0 = Op.getOperand(0);
7263     SDValue Op1 = Op.getOperand(1);
7264 
7265     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7266       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7267           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7268           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7269         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7270       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7271       if ((Reverse.getOpcode() == ISD::ROTL ||
7272            Reverse.getOpcode() == ISD::ROTR) &&
7273           Reverse.getOperand(0) == X &&
7274           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7275         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7276         if (RotAmt == (VT.getSizeInBits() / 2))
7277           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7278                              DAG.getConstant(RotAmt, DL, VT));
7279       }
7280       return SDValue();
7281     };
7282 
7283     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7284     if (SDValue V = MatchOROfReverse(Op0, Op1))
7285       return V;
7286     if (SDValue V = MatchOROfReverse(Op1, Op0))
7287       return V;
7288 
7289     // OR is commutable so canonicalize its OR operand to the left
7290     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7291       std::swap(Op0, Op1);
7292     if (Op0.getOpcode() != ISD::OR)
7293       return SDValue();
7294     SDValue OrOp0 = Op0.getOperand(0);
7295     SDValue OrOp1 = Op0.getOperand(1);
7296     auto LHS = matchGREVIPat(OrOp0);
7297     // OR is commutable so swap the operands and try again: x might have been
7298     // on the left
7299     if (!LHS) {
7300       std::swap(OrOp0, OrOp1);
7301       LHS = matchGREVIPat(OrOp0);
7302     }
7303     auto RHS = matchGREVIPat(Op1);
7304     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7305       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7306                          DAG.getConstant(LHS->ShAmt, DL, VT));
7307     }
7308   }
7309   return SDValue();
7310 }
7311 
7312 // Matches any of the following bit-manipulation patterns:
7313 //   (and (shl x, 1), (0x22222222 << 1))
7314 //   (and (srl x, 1), 0x22222222)
7315 //   (shl (and x, 0x22222222), 1)
7316 //   (srl (and x, (0x22222222 << 1)), 1)
7317 // where the shift amount and mask may vary thus:
7318 //   [1]  = 0x22222222 / 0x44444444
7319 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7320 //   [4]  = 0x00F000F0 / 0x0F000F00
7321 //   [8]  = 0x0000FF00 / 0x00FF0000
7322 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7323 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7324   // These are the unshifted masks which we use to match bit-manipulation
7325   // patterns. They may be shifted left in certain circumstances.
7326   static const uint64_t BitmanipMasks[] = {
7327       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7328       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7329 
7330   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7331 }
7332 
7333 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7334 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7335                                const RISCVSubtarget &Subtarget) {
7336   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7337   EVT VT = Op.getValueType();
7338 
7339   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7340     return SDValue();
7341 
7342   SDValue Op0 = Op.getOperand(0);
7343   SDValue Op1 = Op.getOperand(1);
7344 
7345   // Or is commutable so canonicalize the second OR to the LHS.
7346   if (Op0.getOpcode() != ISD::OR)
7347     std::swap(Op0, Op1);
7348   if (Op0.getOpcode() != ISD::OR)
7349     return SDValue();
7350 
7351   // We found an inner OR, so our operands are the operands of the inner OR
7352   // and the other operand of the outer OR.
7353   SDValue A = Op0.getOperand(0);
7354   SDValue B = Op0.getOperand(1);
7355   SDValue C = Op1;
7356 
7357   auto Match1 = matchSHFLPat(A);
7358   auto Match2 = matchSHFLPat(B);
7359 
7360   // If neither matched, we failed.
7361   if (!Match1 && !Match2)
7362     return SDValue();
7363 
7364   // We had at least one match. if one failed, try the remaining C operand.
7365   if (!Match1) {
7366     std::swap(A, C);
7367     Match1 = matchSHFLPat(A);
7368     if (!Match1)
7369       return SDValue();
7370   } else if (!Match2) {
7371     std::swap(B, C);
7372     Match2 = matchSHFLPat(B);
7373     if (!Match2)
7374       return SDValue();
7375   }
7376   assert(Match1 && Match2);
7377 
7378   // Make sure our matches pair up.
7379   if (!Match1->formsPairWith(*Match2))
7380     return SDValue();
7381 
7382   // All the remains is to make sure C is an AND with the same input, that masks
7383   // out the bits that are being shuffled.
7384   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7385       C.getOperand(0) != Match1->Op)
7386     return SDValue();
7387 
7388   uint64_t Mask = C.getConstantOperandVal(1);
7389 
7390   static const uint64_t BitmanipMasks[] = {
7391       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7392       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7393   };
7394 
7395   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7396   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7397   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7398 
7399   if (Mask != ExpMask)
7400     return SDValue();
7401 
7402   SDLoc DL(Op);
7403   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7404                      DAG.getConstant(Match1->ShAmt, DL, VT));
7405 }
7406 
7407 // Optimize (add (shl x, c0), (shl y, c1)) ->
7408 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7409 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7410                                   const RISCVSubtarget &Subtarget) {
7411   // Perform this optimization only in the zba extension.
7412   if (!Subtarget.hasStdExtZba())
7413     return SDValue();
7414 
7415   // Skip for vector types and larger types.
7416   EVT VT = N->getValueType(0);
7417   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7418     return SDValue();
7419 
7420   // The two operand nodes must be SHL and have no other use.
7421   SDValue N0 = N->getOperand(0);
7422   SDValue N1 = N->getOperand(1);
7423   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7424       !N0->hasOneUse() || !N1->hasOneUse())
7425     return SDValue();
7426 
7427   // Check c0 and c1.
7428   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7429   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7430   if (!N0C || !N1C)
7431     return SDValue();
7432   int64_t C0 = N0C->getSExtValue();
7433   int64_t C1 = N1C->getSExtValue();
7434   if (C0 <= 0 || C1 <= 0)
7435     return SDValue();
7436 
7437   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7438   int64_t Bits = std::min(C0, C1);
7439   int64_t Diff = std::abs(C0 - C1);
7440   if (Diff != 1 && Diff != 2 && Diff != 3)
7441     return SDValue();
7442 
7443   // Build nodes.
7444   SDLoc DL(N);
7445   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7446   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7447   SDValue NA0 =
7448       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7449   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7450   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7451 }
7452 
7453 // Combine
7454 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7455 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7456 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7457 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7458 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7459 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7460 // The grev patterns represents BSWAP.
7461 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7462 // off the grev.
7463 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7464                                           const RISCVSubtarget &Subtarget) {
7465   bool IsWInstruction =
7466       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7467   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7468           IsWInstruction) &&
7469          "Unexpected opcode!");
7470   SDValue Src = N->getOperand(0);
7471   EVT VT = N->getValueType(0);
7472   SDLoc DL(N);
7473 
7474   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7475     return SDValue();
7476 
7477   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7478       !isa<ConstantSDNode>(Src.getOperand(1)))
7479     return SDValue();
7480 
7481   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7482   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7483 
7484   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7485   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7486   unsigned ShAmt1 = N->getConstantOperandVal(1);
7487   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7488   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7489     return SDValue();
7490 
7491   Src = Src.getOperand(0);
7492 
7493   // Toggle bit the MSB of the shift.
7494   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7495   if (CombinedShAmt == 0)
7496     return Src;
7497 
7498   SDValue Res = DAG.getNode(
7499       RISCVISD::GREV, DL, VT, Src,
7500       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7501   if (!IsWInstruction)
7502     return Res;
7503 
7504   // Sign extend the result to match the behavior of the rotate. This will be
7505   // selected to GREVIW in isel.
7506   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7507                      DAG.getValueType(MVT::i32));
7508 }
7509 
7510 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7511 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7512 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7513 // not undo itself, but they are redundant.
7514 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7515   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7516   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7517   SDValue Src = N->getOperand(0);
7518 
7519   if (Src.getOpcode() != N->getOpcode())
7520     return SDValue();
7521 
7522   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7523       !isa<ConstantSDNode>(Src.getOperand(1)))
7524     return SDValue();
7525 
7526   unsigned ShAmt1 = N->getConstantOperandVal(1);
7527   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7528   Src = Src.getOperand(0);
7529 
7530   unsigned CombinedShAmt;
7531   if (IsGORC)
7532     CombinedShAmt = ShAmt1 | ShAmt2;
7533   else
7534     CombinedShAmt = ShAmt1 ^ ShAmt2;
7535 
7536   if (CombinedShAmt == 0)
7537     return Src;
7538 
7539   SDLoc DL(N);
7540   return DAG.getNode(
7541       N->getOpcode(), DL, N->getValueType(0), Src,
7542       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7543 }
7544 
7545 // Combine a constant select operand into its use:
7546 //
7547 // (and (select cond, -1, c), x)
7548 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7549 // (or  (select cond, 0, c), x)
7550 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7551 // (xor (select cond, 0, c), x)
7552 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7553 // (add (select cond, 0, c), x)
7554 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7555 // (sub x, (select cond, 0, c))
7556 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7557 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7558                                    SelectionDAG &DAG, bool AllOnes) {
7559   EVT VT = N->getValueType(0);
7560 
7561   // Skip vectors.
7562   if (VT.isVector())
7563     return SDValue();
7564 
7565   if ((Slct.getOpcode() != ISD::SELECT &&
7566        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7567       !Slct.hasOneUse())
7568     return SDValue();
7569 
7570   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7571     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7572   };
7573 
7574   bool SwapSelectOps;
7575   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7576   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7577   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7578   SDValue NonConstantVal;
7579   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7580     SwapSelectOps = false;
7581     NonConstantVal = FalseVal;
7582   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7583     SwapSelectOps = true;
7584     NonConstantVal = TrueVal;
7585   } else
7586     return SDValue();
7587 
7588   // Slct is now know to be the desired identity constant when CC is true.
7589   TrueVal = OtherOp;
7590   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7591   // Unless SwapSelectOps says the condition should be false.
7592   if (SwapSelectOps)
7593     std::swap(TrueVal, FalseVal);
7594 
7595   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7596     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7597                        {Slct.getOperand(0), Slct.getOperand(1),
7598                         Slct.getOperand(2), TrueVal, FalseVal});
7599 
7600   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7601                      {Slct.getOperand(0), TrueVal, FalseVal});
7602 }
7603 
7604 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7605 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7606                                               bool AllOnes) {
7607   SDValue N0 = N->getOperand(0);
7608   SDValue N1 = N->getOperand(1);
7609   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7610     return Result;
7611   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7612     return Result;
7613   return SDValue();
7614 }
7615 
7616 // Transform (add (mul x, c0), c1) ->
7617 //           (add (mul (add x, c1/c0), c0), c1%c0).
7618 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7619 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7620 // to an infinite loop in DAGCombine if transformed.
7621 // Or transform (add (mul x, c0), c1) ->
7622 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7623 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7624 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7625 // lead to an infinite loop in DAGCombine if transformed.
7626 // Or transform (add (mul x, c0), c1) ->
7627 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7628 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7629 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7630 // lead to an infinite loop in DAGCombine if transformed.
7631 // Or transform (add (mul x, c0), c1) ->
7632 //              (mul (add x, c1/c0), c0).
7633 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7634 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7635                                      const RISCVSubtarget &Subtarget) {
7636   // Skip for vector types and larger types.
7637   EVT VT = N->getValueType(0);
7638   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7639     return SDValue();
7640   // The first operand node must be a MUL and has no other use.
7641   SDValue N0 = N->getOperand(0);
7642   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7643     return SDValue();
7644   // Check if c0 and c1 match above conditions.
7645   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7646   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7647   if (!N0C || !N1C)
7648     return SDValue();
7649   // If N0C has multiple uses it's possible one of the cases in
7650   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7651   // in an infinite loop.
7652   if (!N0C->hasOneUse())
7653     return SDValue();
7654   int64_t C0 = N0C->getSExtValue();
7655   int64_t C1 = N1C->getSExtValue();
7656   int64_t CA, CB;
7657   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7658     return SDValue();
7659   // Search for proper CA (non-zero) and CB that both are simm12.
7660   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7661       !isInt<12>(C0 * (C1 / C0))) {
7662     CA = C1 / C0;
7663     CB = C1 % C0;
7664   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7665              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7666     CA = C1 / C0 + 1;
7667     CB = C1 % C0 - C0;
7668   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7669              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7670     CA = C1 / C0 - 1;
7671     CB = C1 % C0 + C0;
7672   } else
7673     return SDValue();
7674   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7675   SDLoc DL(N);
7676   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7677                              DAG.getConstant(CA, DL, VT));
7678   SDValue New1 =
7679       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7680   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7681 }
7682 
7683 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7684                                  const RISCVSubtarget &Subtarget) {
7685   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7686     return V;
7687   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7688     return V;
7689   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7690   //      (select lhs, rhs, cc, x, (add x, y))
7691   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7692 }
7693 
7694 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7695   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7696   //      (select lhs, rhs, cc, x, (sub x, y))
7697   SDValue N0 = N->getOperand(0);
7698   SDValue N1 = N->getOperand(1);
7699   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7700 }
7701 
7702 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7703   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7704   //      (select lhs, rhs, cc, x, (and x, y))
7705   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7706 }
7707 
7708 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7709                                 const RISCVSubtarget &Subtarget) {
7710   if (Subtarget.hasStdExtZbp()) {
7711     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7712       return GREV;
7713     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7714       return GORC;
7715     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7716       return SHFL;
7717   }
7718 
7719   // fold (or (select cond, 0, y), x) ->
7720   //      (select cond, x, (or x, y))
7721   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7722 }
7723 
7724 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7725   // fold (xor (select cond, 0, y), x) ->
7726   //      (select cond, x, (xor x, y))
7727   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7728 }
7729 
7730 static SDValue
7731 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
7732                                 const RISCVSubtarget &Subtarget) {
7733   SDValue Src = N->getOperand(0);
7734   EVT VT = N->getValueType(0);
7735 
7736   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
7737   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7738       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
7739     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
7740                        Src.getOperand(0));
7741 
7742   // Fold (i64 (sext_inreg (abs X), i32)) ->
7743   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
7744   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
7745   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
7746   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
7747   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
7748   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
7749   // may get combined into an earlier operation so we need to use
7750   // ComputeNumSignBits.
7751   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
7752   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
7753   // we can't assume that X has 33 sign bits. We must check.
7754   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
7755       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
7756       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
7757       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
7758     SDLoc DL(N);
7759     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
7760     SDValue Neg =
7761         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
7762     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
7763                       DAG.getValueType(MVT::i32));
7764     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
7765   }
7766 
7767   return SDValue();
7768 }
7769 
7770 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
7771 // vwadd(u).vv/vx or vwsub(u).vv/vx.
7772 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
7773                                              bool Commute = false) {
7774   assert((N->getOpcode() == RISCVISD::ADD_VL ||
7775           N->getOpcode() == RISCVISD::SUB_VL) &&
7776          "Unexpected opcode");
7777   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
7778   SDValue Op0 = N->getOperand(0);
7779   SDValue Op1 = N->getOperand(1);
7780   if (Commute)
7781     std::swap(Op0, Op1);
7782 
7783   MVT VT = N->getSimpleValueType(0);
7784 
7785   // Determine the narrow size for a widening add/sub.
7786   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7787   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7788                                   VT.getVectorElementCount());
7789 
7790   SDValue Mask = N->getOperand(2);
7791   SDValue VL = N->getOperand(3);
7792 
7793   SDLoc DL(N);
7794 
7795   // If the RHS is a sext or zext, we can form a widening op.
7796   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
7797        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
7798       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
7799     unsigned ExtOpc = Op1.getOpcode();
7800     Op1 = Op1.getOperand(0);
7801     // Re-introduce narrower extends if needed.
7802     if (Op1.getValueType() != NarrowVT)
7803       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7804 
7805     unsigned WOpc;
7806     if (ExtOpc == RISCVISD::VSEXT_VL)
7807       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
7808     else
7809       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
7810 
7811     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
7812   }
7813 
7814   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
7815   // sext/zext?
7816 
7817   return SDValue();
7818 }
7819 
7820 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
7821 // vwsub(u).vv/vx.
7822 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
7823   SDValue Op0 = N->getOperand(0);
7824   SDValue Op1 = N->getOperand(1);
7825   SDValue Mask = N->getOperand(2);
7826   SDValue VL = N->getOperand(3);
7827 
7828   MVT VT = N->getSimpleValueType(0);
7829   MVT NarrowVT = Op1.getSimpleValueType();
7830   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
7831 
7832   unsigned VOpc;
7833   switch (N->getOpcode()) {
7834   default: llvm_unreachable("Unexpected opcode");
7835   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
7836   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
7837   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
7838   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
7839   }
7840 
7841   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7842                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
7843 
7844   SDLoc DL(N);
7845 
7846   // If the LHS is a sext or zext, we can narrow this op to the same size as
7847   // the RHS.
7848   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
7849        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
7850       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
7851     unsigned ExtOpc = Op0.getOpcode();
7852     Op0 = Op0.getOperand(0);
7853     // Re-introduce narrower extends if needed.
7854     if (Op0.getValueType() != NarrowVT)
7855       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7856     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
7857   }
7858 
7859   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7860                N->getOpcode() == RISCVISD::VWADDU_W_VL;
7861 
7862   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
7863   // to commute and use a vwadd(u).vx instead.
7864   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
7865       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
7866     Op0 = Op0.getOperand(1);
7867 
7868     // See if have enough sign bits or zero bits in the scalar to use a
7869     // widening add/sub by splatting to smaller element size.
7870     unsigned EltBits = VT.getScalarSizeInBits();
7871     unsigned ScalarBits = Op0.getValueSizeInBits();
7872     // Make sure we're getting all element bits from the scalar register.
7873     // FIXME: Support implicit sign extension of vmv.v.x?
7874     if (ScalarBits < EltBits)
7875       return SDValue();
7876 
7877     if (IsSigned) {
7878       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
7879         return SDValue();
7880     } else {
7881       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7882       if (!DAG.MaskedValueIsZero(Op0, Mask))
7883         return SDValue();
7884     }
7885 
7886     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
7887                       DAG.getUNDEF(NarrowVT), Op0, VL);
7888     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
7889   }
7890 
7891   return SDValue();
7892 }
7893 
7894 // Try to form VWMUL, VWMULU or VWMULSU.
7895 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
7896 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
7897                                        bool Commute) {
7898   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
7899   SDValue Op0 = N->getOperand(0);
7900   SDValue Op1 = N->getOperand(1);
7901   if (Commute)
7902     std::swap(Op0, Op1);
7903 
7904   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
7905   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
7906   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
7907   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
7908     return SDValue();
7909 
7910   SDValue Mask = N->getOperand(2);
7911   SDValue VL = N->getOperand(3);
7912 
7913   // Make sure the mask and VL match.
7914   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
7915     return SDValue();
7916 
7917   MVT VT = N->getSimpleValueType(0);
7918 
7919   // Determine the narrow size for a widening multiply.
7920   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7921   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7922                                   VT.getVectorElementCount());
7923 
7924   SDLoc DL(N);
7925 
7926   // See if the other operand is the same opcode.
7927   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
7928     if (!Op1.hasOneUse())
7929       return SDValue();
7930 
7931     // Make sure the mask and VL match.
7932     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
7933       return SDValue();
7934 
7935     Op1 = Op1.getOperand(0);
7936   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
7937     // The operand is a splat of a scalar.
7938 
7939     // The pasthru must be undef for tail agnostic
7940     if (!Op1.getOperand(0).isUndef())
7941       return SDValue();
7942     // The VL must be the same.
7943     if (Op1.getOperand(2) != VL)
7944       return SDValue();
7945 
7946     // Get the scalar value.
7947     Op1 = Op1.getOperand(1);
7948 
7949     // See if have enough sign bits or zero bits in the scalar to use a
7950     // widening multiply by splatting to smaller element size.
7951     unsigned EltBits = VT.getScalarSizeInBits();
7952     unsigned ScalarBits = Op1.getValueSizeInBits();
7953     // Make sure we're getting all element bits from the scalar register.
7954     // FIXME: Support implicit sign extension of vmv.v.x?
7955     if (ScalarBits < EltBits)
7956       return SDValue();
7957 
7958     // If the LHS is a sign extend, try to use vwmul.
7959     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
7960       // Can use vwmul.
7961     } else {
7962       // Otherwise try to use vwmulu or vwmulsu.
7963       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7964       if (DAG.MaskedValueIsZero(Op1, Mask))
7965         IsVWMULSU = IsSignExt;
7966       else
7967         return SDValue();
7968     }
7969 
7970     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
7971                       DAG.getUNDEF(NarrowVT), Op1, VL);
7972   } else
7973     return SDValue();
7974 
7975   Op0 = Op0.getOperand(0);
7976 
7977   // Re-introduce narrower extends if needed.
7978   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
7979   if (Op0.getValueType() != NarrowVT)
7980     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7981   // vwmulsu requires second operand to be zero extended.
7982   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
7983   if (Op1.getValueType() != NarrowVT)
7984     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7985 
7986   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
7987   if (!IsVWMULSU)
7988     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
7989   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
7990 }
7991 
7992 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
7993   switch (Op.getOpcode()) {
7994   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
7995   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
7996   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
7997   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
7998   case ISD::FROUND:     return RISCVFPRndMode::RMM;
7999   }
8000 
8001   return RISCVFPRndMode::Invalid;
8002 }
8003 
8004 // Fold
8005 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8006 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8007 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8008 //   (fp_to_int (fceil X))      -> fcvt X, rup
8009 //   (fp_to_int (fround X))     -> fcvt X, rmm
8010 static SDValue performFP_TO_INTCombine(SDNode *N,
8011                                        TargetLowering::DAGCombinerInfo &DCI,
8012                                        const RISCVSubtarget &Subtarget) {
8013   SelectionDAG &DAG = DCI.DAG;
8014   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8015   MVT XLenVT = Subtarget.getXLenVT();
8016 
8017   // Only handle XLen or i32 types. Other types narrower than XLen will
8018   // eventually be legalized to XLenVT.
8019   EVT VT = N->getValueType(0);
8020   if (VT != MVT::i32 && VT != XLenVT)
8021     return SDValue();
8022 
8023   SDValue Src = N->getOperand(0);
8024 
8025   // Ensure the FP type is also legal.
8026   if (!TLI.isTypeLegal(Src.getValueType()))
8027     return SDValue();
8028 
8029   // Don't do this for f16 with Zfhmin and not Zfh.
8030   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8031     return SDValue();
8032 
8033   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8034   if (FRM == RISCVFPRndMode::Invalid)
8035     return SDValue();
8036 
8037   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8038 
8039   unsigned Opc;
8040   if (VT == XLenVT)
8041     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8042   else
8043     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8044 
8045   SDLoc DL(N);
8046   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8047                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8048   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8049 }
8050 
8051 // Fold
8052 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8053 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8054 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8055 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8056 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8057 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8058                                        TargetLowering::DAGCombinerInfo &DCI,
8059                                        const RISCVSubtarget &Subtarget) {
8060   SelectionDAG &DAG = DCI.DAG;
8061   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8062   MVT XLenVT = Subtarget.getXLenVT();
8063 
8064   // Only handle XLen types. Other types narrower than XLen will eventually be
8065   // legalized to XLenVT.
8066   EVT DstVT = N->getValueType(0);
8067   if (DstVT != XLenVT)
8068     return SDValue();
8069 
8070   SDValue Src = N->getOperand(0);
8071 
8072   // Ensure the FP type is also legal.
8073   if (!TLI.isTypeLegal(Src.getValueType()))
8074     return SDValue();
8075 
8076   // Don't do this for f16 with Zfhmin and not Zfh.
8077   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8078     return SDValue();
8079 
8080   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8081 
8082   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8083   if (FRM == RISCVFPRndMode::Invalid)
8084     return SDValue();
8085 
8086   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8087 
8088   unsigned Opc;
8089   if (SatVT == DstVT)
8090     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8091   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8092     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8093   else
8094     return SDValue();
8095   // FIXME: Support other SatVTs by clamping before or after the conversion.
8096 
8097   Src = Src.getOperand(0);
8098 
8099   SDLoc DL(N);
8100   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8101                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8102 
8103   // RISCV FP-to-int conversions saturate to the destination register size, but
8104   // don't produce 0 for nan.
8105   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8106   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8107 }
8108 
8109 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8110 // smaller than XLenVT.
8111 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8112                                         const RISCVSubtarget &Subtarget) {
8113   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8114 
8115   SDValue Src = N->getOperand(0);
8116   if (Src.getOpcode() != ISD::BSWAP)
8117     return SDValue();
8118 
8119   EVT VT = N->getValueType(0);
8120   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8121       !isPowerOf2_32(VT.getSizeInBits()))
8122     return SDValue();
8123 
8124   SDLoc DL(N);
8125   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8126                      DAG.getConstant(7, DL, VT));
8127 }
8128 
8129 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8130                                                DAGCombinerInfo &DCI) const {
8131   SelectionDAG &DAG = DCI.DAG;
8132 
8133   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8134   // bits are demanded. N will be added to the Worklist if it was not deleted.
8135   // Caller should return SDValue(N, 0) if this returns true.
8136   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8137     SDValue Op = N->getOperand(OpNo);
8138     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8139     if (!SimplifyDemandedBits(Op, Mask, DCI))
8140       return false;
8141 
8142     if (N->getOpcode() != ISD::DELETED_NODE)
8143       DCI.AddToWorklist(N);
8144     return true;
8145   };
8146 
8147   switch (N->getOpcode()) {
8148   default:
8149     break;
8150   case RISCVISD::SplitF64: {
8151     SDValue Op0 = N->getOperand(0);
8152     // If the input to SplitF64 is just BuildPairF64 then the operation is
8153     // redundant. Instead, use BuildPairF64's operands directly.
8154     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8155       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8156 
8157     if (Op0->isUndef()) {
8158       SDValue Lo = DAG.getUNDEF(MVT::i32);
8159       SDValue Hi = DAG.getUNDEF(MVT::i32);
8160       return DCI.CombineTo(N, Lo, Hi);
8161     }
8162 
8163     SDLoc DL(N);
8164 
8165     // It's cheaper to materialise two 32-bit integers than to load a double
8166     // from the constant pool and transfer it to integer registers through the
8167     // stack.
8168     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8169       APInt V = C->getValueAPF().bitcastToAPInt();
8170       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8171       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8172       return DCI.CombineTo(N, Lo, Hi);
8173     }
8174 
8175     // This is a target-specific version of a DAGCombine performed in
8176     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8177     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8178     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8179     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8180         !Op0.getNode()->hasOneUse())
8181       break;
8182     SDValue NewSplitF64 =
8183         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8184                     Op0.getOperand(0));
8185     SDValue Lo = NewSplitF64.getValue(0);
8186     SDValue Hi = NewSplitF64.getValue(1);
8187     APInt SignBit = APInt::getSignMask(32);
8188     if (Op0.getOpcode() == ISD::FNEG) {
8189       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8190                                   DAG.getConstant(SignBit, DL, MVT::i32));
8191       return DCI.CombineTo(N, Lo, NewHi);
8192     }
8193     assert(Op0.getOpcode() == ISD::FABS);
8194     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8195                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8196     return DCI.CombineTo(N, Lo, NewHi);
8197   }
8198   case RISCVISD::SLLW:
8199   case RISCVISD::SRAW:
8200   case RISCVISD::SRLW: {
8201     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8202     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8203         SimplifyDemandedLowBitsHelper(1, 5))
8204       return SDValue(N, 0);
8205 
8206     break;
8207   }
8208   case ISD::ROTR:
8209   case ISD::ROTL:
8210   case RISCVISD::RORW:
8211   case RISCVISD::ROLW: {
8212     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8213       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8214       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8215           SimplifyDemandedLowBitsHelper(1, 5))
8216         return SDValue(N, 0);
8217     }
8218 
8219     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8220   }
8221   case RISCVISD::CLZW:
8222   case RISCVISD::CTZW: {
8223     // Only the lower 32 bits of the first operand are read
8224     if (SimplifyDemandedLowBitsHelper(0, 32))
8225       return SDValue(N, 0);
8226     break;
8227   }
8228   case RISCVISD::GREV:
8229   case RISCVISD::GORC: {
8230     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8231     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8232     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8233     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8234       return SDValue(N, 0);
8235 
8236     return combineGREVI_GORCI(N, DAG);
8237   }
8238   case RISCVISD::GREVW:
8239   case RISCVISD::GORCW: {
8240     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8241     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8242         SimplifyDemandedLowBitsHelper(1, 5))
8243       return SDValue(N, 0);
8244 
8245     break;
8246   }
8247   case RISCVISD::SHFL:
8248   case RISCVISD::UNSHFL: {
8249     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8250     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8251     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8252     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8253       return SDValue(N, 0);
8254 
8255     break;
8256   }
8257   case RISCVISD::SHFLW:
8258   case RISCVISD::UNSHFLW: {
8259     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8260     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8261         SimplifyDemandedLowBitsHelper(1, 4))
8262       return SDValue(N, 0);
8263 
8264     break;
8265   }
8266   case RISCVISD::BCOMPRESSW:
8267   case RISCVISD::BDECOMPRESSW: {
8268     // Only the lower 32 bits of LHS and RHS are read.
8269     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8270         SimplifyDemandedLowBitsHelper(1, 32))
8271       return SDValue(N, 0);
8272 
8273     break;
8274   }
8275   case RISCVISD::FSR:
8276   case RISCVISD::FSL:
8277   case RISCVISD::FSRW:
8278   case RISCVISD::FSLW: {
8279     bool IsWInstruction =
8280         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8281     unsigned BitWidth =
8282         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8283     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8284     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8285     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8286       return SDValue(N, 0);
8287 
8288     break;
8289   }
8290   case RISCVISD::FMV_X_ANYEXTH:
8291   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8292     SDLoc DL(N);
8293     SDValue Op0 = N->getOperand(0);
8294     MVT VT = N->getSimpleValueType(0);
8295     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8296     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8297     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8298     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8299          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8300         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8301          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8302       assert(Op0.getOperand(0).getValueType() == VT &&
8303              "Unexpected value type!");
8304       return Op0.getOperand(0);
8305     }
8306 
8307     // This is a target-specific version of a DAGCombine performed in
8308     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8309     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8310     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8311     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8312         !Op0.getNode()->hasOneUse())
8313       break;
8314     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8315     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8316     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
8317     if (Op0.getOpcode() == ISD::FNEG)
8318       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8319                          DAG.getConstant(SignBit, DL, VT));
8320 
8321     assert(Op0.getOpcode() == ISD::FABS);
8322     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8323                        DAG.getConstant(~SignBit, DL, VT));
8324   }
8325   case ISD::ADD:
8326     return performADDCombine(N, DAG, Subtarget);
8327   case ISD::SUB:
8328     return performSUBCombine(N, DAG);
8329   case ISD::AND:
8330     return performANDCombine(N, DAG);
8331   case ISD::OR:
8332     return performORCombine(N, DAG, Subtarget);
8333   case ISD::XOR:
8334     return performXORCombine(N, DAG);
8335   case ISD::SIGN_EXTEND_INREG:
8336     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8337   case ISD::ZERO_EXTEND:
8338     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8339     // type legalization. This is safe because fp_to_uint produces poison if
8340     // it overflows.
8341     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8342       SDValue Src = N->getOperand(0);
8343       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8344           isTypeLegal(Src.getOperand(0).getValueType()))
8345         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8346                            Src.getOperand(0));
8347       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8348           isTypeLegal(Src.getOperand(1).getValueType())) {
8349         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8350         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8351                                   Src.getOperand(0), Src.getOperand(1));
8352         DCI.CombineTo(N, Res);
8353         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8354         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8355         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8356       }
8357     }
8358     return SDValue();
8359   case RISCVISD::SELECT_CC: {
8360     // Transform
8361     SDValue LHS = N->getOperand(0);
8362     SDValue RHS = N->getOperand(1);
8363     SDValue TrueV = N->getOperand(3);
8364     SDValue FalseV = N->getOperand(4);
8365 
8366     // If the True and False values are the same, we don't need a select_cc.
8367     if (TrueV == FalseV)
8368       return TrueV;
8369 
8370     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8371     if (!ISD::isIntEqualitySetCC(CCVal))
8372       break;
8373 
8374     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8375     //      (select_cc X, Y, lt, trueV, falseV)
8376     // Sometimes the setcc is introduced after select_cc has been formed.
8377     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8378         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8379       // If we're looking for eq 0 instead of ne 0, we need to invert the
8380       // condition.
8381       bool Invert = CCVal == ISD::SETEQ;
8382       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8383       if (Invert)
8384         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8385 
8386       SDLoc DL(N);
8387       RHS = LHS.getOperand(1);
8388       LHS = LHS.getOperand(0);
8389       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8390 
8391       SDValue TargetCC = DAG.getCondCode(CCVal);
8392       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8393                          {LHS, RHS, TargetCC, TrueV, FalseV});
8394     }
8395 
8396     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8397     //      (select_cc X, Y, eq/ne, trueV, falseV)
8398     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8399       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8400                          {LHS.getOperand(0), LHS.getOperand(1),
8401                           N->getOperand(2), TrueV, FalseV});
8402     // (select_cc X, 1, setne, trueV, falseV) ->
8403     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8404     // This can occur when legalizing some floating point comparisons.
8405     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8406     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8407       SDLoc DL(N);
8408       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8409       SDValue TargetCC = DAG.getCondCode(CCVal);
8410       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8411       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8412                          {LHS, RHS, TargetCC, TrueV, FalseV});
8413     }
8414 
8415     break;
8416   }
8417   case RISCVISD::BR_CC: {
8418     SDValue LHS = N->getOperand(1);
8419     SDValue RHS = N->getOperand(2);
8420     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8421     if (!ISD::isIntEqualitySetCC(CCVal))
8422       break;
8423 
8424     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8425     //      (br_cc X, Y, lt, dest)
8426     // Sometimes the setcc is introduced after br_cc has been formed.
8427     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8428         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8429       // If we're looking for eq 0 instead of ne 0, we need to invert the
8430       // condition.
8431       bool Invert = CCVal == ISD::SETEQ;
8432       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8433       if (Invert)
8434         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8435 
8436       SDLoc DL(N);
8437       RHS = LHS.getOperand(1);
8438       LHS = LHS.getOperand(0);
8439       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8440 
8441       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8442                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8443                          N->getOperand(4));
8444     }
8445 
8446     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8447     //      (br_cc X, Y, eq/ne, trueV, falseV)
8448     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8449       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8450                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8451                          N->getOperand(3), N->getOperand(4));
8452 
8453     // (br_cc X, 1, setne, br_cc) ->
8454     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8455     // This can occur when legalizing some floating point comparisons.
8456     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8457     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8458       SDLoc DL(N);
8459       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8460       SDValue TargetCC = DAG.getCondCode(CCVal);
8461       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8462       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8463                          N->getOperand(0), LHS, RHS, TargetCC,
8464                          N->getOperand(4));
8465     }
8466     break;
8467   }
8468   case ISD::BITREVERSE:
8469     return performBITREVERSECombine(N, DAG, Subtarget);
8470   case ISD::FP_TO_SINT:
8471   case ISD::FP_TO_UINT:
8472     return performFP_TO_INTCombine(N, DCI, Subtarget);
8473   case ISD::FP_TO_SINT_SAT:
8474   case ISD::FP_TO_UINT_SAT:
8475     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8476   case ISD::FCOPYSIGN: {
8477     EVT VT = N->getValueType(0);
8478     if (!VT.isVector())
8479       break;
8480     // There is a form of VFSGNJ which injects the negated sign of its second
8481     // operand. Try and bubble any FNEG up after the extend/round to produce
8482     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8483     // TRUNC=1.
8484     SDValue In2 = N->getOperand(1);
8485     // Avoid cases where the extend/round has multiple uses, as duplicating
8486     // those is typically more expensive than removing a fneg.
8487     if (!In2.hasOneUse())
8488       break;
8489     if (In2.getOpcode() != ISD::FP_EXTEND &&
8490         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8491       break;
8492     In2 = In2.getOperand(0);
8493     if (In2.getOpcode() != ISD::FNEG)
8494       break;
8495     SDLoc DL(N);
8496     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8497     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8498                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8499   }
8500   case ISD::MGATHER:
8501   case ISD::MSCATTER:
8502   case ISD::VP_GATHER:
8503   case ISD::VP_SCATTER: {
8504     if (!DCI.isBeforeLegalize())
8505       break;
8506     SDValue Index, ScaleOp;
8507     bool IsIndexScaled = false;
8508     bool IsIndexSigned = false;
8509     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8510       Index = VPGSN->getIndex();
8511       ScaleOp = VPGSN->getScale();
8512       IsIndexScaled = VPGSN->isIndexScaled();
8513       IsIndexSigned = VPGSN->isIndexSigned();
8514     } else {
8515       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8516       Index = MGSN->getIndex();
8517       ScaleOp = MGSN->getScale();
8518       IsIndexScaled = MGSN->isIndexScaled();
8519       IsIndexSigned = MGSN->isIndexSigned();
8520     }
8521     EVT IndexVT = Index.getValueType();
8522     MVT XLenVT = Subtarget.getXLenVT();
8523     // RISCV indexed loads only support the "unsigned unscaled" addressing
8524     // mode, so anything else must be manually legalized.
8525     bool NeedsIdxLegalization =
8526         IsIndexScaled ||
8527         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8528     if (!NeedsIdxLegalization)
8529       break;
8530 
8531     SDLoc DL(N);
8532 
8533     // Any index legalization should first promote to XLenVT, so we don't lose
8534     // bits when scaling. This may create an illegal index type so we let
8535     // LLVM's legalization take care of the splitting.
8536     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8537     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8538       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8539       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8540                           DL, IndexVT, Index);
8541     }
8542 
8543     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8544     if (IsIndexScaled && Scale != 1) {
8545       // Manually scale the indices by the element size.
8546       // TODO: Sanitize the scale operand here?
8547       // TODO: For VP nodes, should we use VP_SHL here?
8548       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8549       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8550       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8551     }
8552 
8553     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
8554     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8555       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8556                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8557                               VPGN->getScale(), VPGN->getMask(),
8558                               VPGN->getVectorLength()},
8559                              VPGN->getMemOperand(), NewIndexTy);
8560     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8561       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8562                               {VPSN->getChain(), VPSN->getValue(),
8563                                VPSN->getBasePtr(), Index, VPSN->getScale(),
8564                                VPSN->getMask(), VPSN->getVectorLength()},
8565                               VPSN->getMemOperand(), NewIndexTy);
8566     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8567       return DAG.getMaskedGather(
8568           N->getVTList(), MGN->getMemoryVT(), DL,
8569           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8570            MGN->getBasePtr(), Index, MGN->getScale()},
8571           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8572     const auto *MSN = cast<MaskedScatterSDNode>(N);
8573     return DAG.getMaskedScatter(
8574         N->getVTList(), MSN->getMemoryVT(), DL,
8575         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8576          Index, MSN->getScale()},
8577         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8578   }
8579   case RISCVISD::SRA_VL:
8580   case RISCVISD::SRL_VL:
8581   case RISCVISD::SHL_VL: {
8582     SDValue ShAmt = N->getOperand(1);
8583     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8584       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8585       SDLoc DL(N);
8586       SDValue VL = N->getOperand(3);
8587       EVT VT = N->getValueType(0);
8588       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8589                           ShAmt.getOperand(1), VL);
8590       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8591                          N->getOperand(2), N->getOperand(3));
8592     }
8593     break;
8594   }
8595   case ISD::SRA:
8596   case ISD::SRL:
8597   case ISD::SHL: {
8598     SDValue ShAmt = N->getOperand(1);
8599     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8600       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8601       SDLoc DL(N);
8602       EVT VT = N->getValueType(0);
8603       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8604                           ShAmt.getOperand(1),
8605                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8606       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8607     }
8608     break;
8609   }
8610   case RISCVISD::ADD_VL:
8611     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8612       return V;
8613     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8614   case RISCVISD::SUB_VL:
8615     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8616   case RISCVISD::VWADD_W_VL:
8617   case RISCVISD::VWADDU_W_VL:
8618   case RISCVISD::VWSUB_W_VL:
8619   case RISCVISD::VWSUBU_W_VL:
8620     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8621   case RISCVISD::MUL_VL:
8622     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8623       return V;
8624     // Mul is commutative.
8625     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8626   case ISD::STORE: {
8627     auto *Store = cast<StoreSDNode>(N);
8628     SDValue Val = Store->getValue();
8629     // Combine store of vmv.x.s to vse with VL of 1.
8630     // FIXME: Support FP.
8631     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8632       SDValue Src = Val.getOperand(0);
8633       EVT VecVT = Src.getValueType();
8634       EVT MemVT = Store->getMemoryVT();
8635       // The memory VT and the element type must match.
8636       if (VecVT.getVectorElementType() == MemVT) {
8637         SDLoc DL(N);
8638         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8639         return DAG.getStoreVP(
8640             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8641             DAG.getConstant(1, DL, MaskVT),
8642             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8643             Store->getMemOperand(), Store->getAddressingMode(),
8644             Store->isTruncatingStore(), /*IsCompress*/ false);
8645       }
8646     }
8647 
8648     break;
8649   }
8650   case ISD::SPLAT_VECTOR: {
8651     EVT VT = N->getValueType(0);
8652     // Only perform this combine on legal MVT types.
8653     if (!isTypeLegal(VT))
8654       break;
8655     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
8656                                          DAG, Subtarget))
8657       return Gather;
8658     break;
8659   }
8660   case RISCVISD::VMV_V_X_VL: {
8661     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
8662     // scalar input.
8663     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
8664     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
8665     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
8666       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
8667         return SDValue(N, 0);
8668 
8669     break;
8670   }
8671   case ISD::INTRINSIC_WO_CHAIN: {
8672     unsigned IntNo = N->getConstantOperandVal(0);
8673     switch (IntNo) {
8674       // By default we do not combine any intrinsic.
8675     default:
8676       return SDValue();
8677     case Intrinsic::riscv_vcpop:
8678     case Intrinsic::riscv_vcpop_mask:
8679     case Intrinsic::riscv_vfirst:
8680     case Intrinsic::riscv_vfirst_mask: {
8681       SDValue VL = N->getOperand(2);
8682       if (IntNo == Intrinsic::riscv_vcpop_mask ||
8683           IntNo == Intrinsic::riscv_vfirst_mask)
8684         VL = N->getOperand(3);
8685       if (!isNullConstant(VL))
8686         return SDValue();
8687       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
8688       SDLoc DL(N);
8689       EVT VT = N->getValueType(0);
8690       if (IntNo == Intrinsic::riscv_vfirst ||
8691           IntNo == Intrinsic::riscv_vfirst_mask)
8692         return DAG.getConstant(-1, DL, VT);
8693       return DAG.getConstant(0, DL, VT);
8694     }
8695     }
8696   }
8697   }
8698 
8699   return SDValue();
8700 }
8701 
8702 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8703     const SDNode *N, CombineLevel Level) const {
8704   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8705   // materialised in fewer instructions than `(OP _, c1)`:
8706   //
8707   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8708   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8709   SDValue N0 = N->getOperand(0);
8710   EVT Ty = N0.getValueType();
8711   if (Ty.isScalarInteger() &&
8712       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8713     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8714     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8715     if (C1 && C2) {
8716       const APInt &C1Int = C1->getAPIntValue();
8717       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8718 
8719       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8720       // and the combine should happen, to potentially allow further combines
8721       // later.
8722       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8723           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8724         return true;
8725 
8726       // We can materialise `c1` in an add immediate, so it's "free", and the
8727       // combine should be prevented.
8728       if (C1Int.getMinSignedBits() <= 64 &&
8729           isLegalAddImmediate(C1Int.getSExtValue()))
8730         return false;
8731 
8732       // Neither constant will fit into an immediate, so find materialisation
8733       // costs.
8734       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8735                                               Subtarget.getFeatureBits(),
8736                                               /*CompressionCost*/true);
8737       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8738           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8739           /*CompressionCost*/true);
8740 
8741       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8742       // combine should be prevented.
8743       if (C1Cost < ShiftedC1Cost)
8744         return false;
8745     }
8746   }
8747   return true;
8748 }
8749 
8750 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8751     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8752     TargetLoweringOpt &TLO) const {
8753   // Delay this optimization as late as possible.
8754   if (!TLO.LegalOps)
8755     return false;
8756 
8757   EVT VT = Op.getValueType();
8758   if (VT.isVector())
8759     return false;
8760 
8761   // Only handle AND for now.
8762   if (Op.getOpcode() != ISD::AND)
8763     return false;
8764 
8765   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8766   if (!C)
8767     return false;
8768 
8769   const APInt &Mask = C->getAPIntValue();
8770 
8771   // Clear all non-demanded bits initially.
8772   APInt ShrunkMask = Mask & DemandedBits;
8773 
8774   // Try to make a smaller immediate by setting undemanded bits.
8775 
8776   APInt ExpandedMask = Mask | ~DemandedBits;
8777 
8778   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8779     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8780   };
8781   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8782     if (NewMask == Mask)
8783       return true;
8784     SDLoc DL(Op);
8785     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8786     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8787     return TLO.CombineTo(Op, NewOp);
8788   };
8789 
8790   // If the shrunk mask fits in sign extended 12 bits, let the target
8791   // independent code apply it.
8792   if (ShrunkMask.isSignedIntN(12))
8793     return false;
8794 
8795   // Preserve (and X, 0xffff) when zext.h is supported.
8796   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8797     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8798     if (IsLegalMask(NewMask))
8799       return UseMask(NewMask);
8800   }
8801 
8802   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8803   if (VT == MVT::i64) {
8804     APInt NewMask = APInt(64, 0xffffffff);
8805     if (IsLegalMask(NewMask))
8806       return UseMask(NewMask);
8807   }
8808 
8809   // For the remaining optimizations, we need to be able to make a negative
8810   // number through a combination of mask and undemanded bits.
8811   if (!ExpandedMask.isNegative())
8812     return false;
8813 
8814   // What is the fewest number of bits we need to represent the negative number.
8815   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8816 
8817   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8818   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8819   APInt NewMask = ShrunkMask;
8820   if (MinSignedBits <= 12)
8821     NewMask.setBitsFrom(11);
8822   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8823     NewMask.setBitsFrom(31);
8824   else
8825     return false;
8826 
8827   // Check that our new mask is a subset of the demanded mask.
8828   assert(IsLegalMask(NewMask));
8829   return UseMask(NewMask);
8830 }
8831 
8832 static void computeGREV(APInt &Src, unsigned ShAmt) {
8833   ShAmt &= Src.getBitWidth() - 1;
8834   uint64_t x = Src.getZExtValue();
8835   if (ShAmt & 1)
8836     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
8837   if (ShAmt & 2)
8838     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
8839   if (ShAmt & 4)
8840     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
8841   if (ShAmt & 8)
8842     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
8843   if (ShAmt & 16)
8844     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
8845   if (ShAmt & 32)
8846     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
8847   Src = x;
8848 }
8849 
8850 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8851                                                         KnownBits &Known,
8852                                                         const APInt &DemandedElts,
8853                                                         const SelectionDAG &DAG,
8854                                                         unsigned Depth) const {
8855   unsigned BitWidth = Known.getBitWidth();
8856   unsigned Opc = Op.getOpcode();
8857   assert((Opc >= ISD::BUILTIN_OP_END ||
8858           Opc == ISD::INTRINSIC_WO_CHAIN ||
8859           Opc == ISD::INTRINSIC_W_CHAIN ||
8860           Opc == ISD::INTRINSIC_VOID) &&
8861          "Should use MaskedValueIsZero if you don't know whether Op"
8862          " is a target node!");
8863 
8864   Known.resetAll();
8865   switch (Opc) {
8866   default: break;
8867   case RISCVISD::SELECT_CC: {
8868     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
8869     // If we don't know any bits, early out.
8870     if (Known.isUnknown())
8871       break;
8872     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
8873 
8874     // Only known if known in both the LHS and RHS.
8875     Known = KnownBits::commonBits(Known, Known2);
8876     break;
8877   }
8878   case RISCVISD::REMUW: {
8879     KnownBits Known2;
8880     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8881     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8882     // We only care about the lower 32 bits.
8883     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
8884     // Restore the original width by sign extending.
8885     Known = Known.sext(BitWidth);
8886     break;
8887   }
8888   case RISCVISD::DIVUW: {
8889     KnownBits Known2;
8890     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8891     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8892     // We only care about the lower 32 bits.
8893     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
8894     // Restore the original width by sign extending.
8895     Known = Known.sext(BitWidth);
8896     break;
8897   }
8898   case RISCVISD::CTZW: {
8899     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8900     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
8901     unsigned LowBits = Log2_32(PossibleTZ) + 1;
8902     Known.Zero.setBitsFrom(LowBits);
8903     break;
8904   }
8905   case RISCVISD::CLZW: {
8906     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8907     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
8908     unsigned LowBits = Log2_32(PossibleLZ) + 1;
8909     Known.Zero.setBitsFrom(LowBits);
8910     break;
8911   }
8912   case RISCVISD::GREV: {
8913     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8914       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8915       unsigned ShAmt = C->getZExtValue();
8916       computeGREV(Known.Zero, ShAmt);
8917       computeGREV(Known.One, ShAmt);
8918     }
8919     break;
8920   }
8921   case RISCVISD::READ_VLENB: {
8922     // If we know the minimum VLen from Zvl extensions, we can use that to
8923     // determine the trailing zeros of VLENB.
8924     // FIXME: Limit to 128 bit vectors until we have more testing.
8925     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
8926     if (MinVLenB > 0)
8927       Known.Zero.setLowBits(Log2_32(MinVLenB));
8928     // We assume VLENB is no more than 65536 / 8 bytes.
8929     Known.Zero.setBitsFrom(14);
8930     break;
8931   }
8932   case ISD::INTRINSIC_W_CHAIN:
8933   case ISD::INTRINSIC_WO_CHAIN: {
8934     unsigned IntNo =
8935         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
8936     switch (IntNo) {
8937     default:
8938       // We can't do anything for most intrinsics.
8939       break;
8940     case Intrinsic::riscv_vsetvli:
8941     case Intrinsic::riscv_vsetvlimax:
8942     case Intrinsic::riscv_vsetvli_opt:
8943     case Intrinsic::riscv_vsetvlimax_opt:
8944       // Assume that VL output is positive and would fit in an int32_t.
8945       // TODO: VLEN might be capped at 16 bits in a future V spec update.
8946       if (BitWidth >= 32)
8947         Known.Zero.setBitsFrom(31);
8948       break;
8949     }
8950     break;
8951   }
8952   }
8953 }
8954 
8955 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
8956     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
8957     unsigned Depth) const {
8958   switch (Op.getOpcode()) {
8959   default:
8960     break;
8961   case RISCVISD::SELECT_CC: {
8962     unsigned Tmp =
8963         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
8964     if (Tmp == 1) return 1;  // Early out.
8965     unsigned Tmp2 =
8966         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
8967     return std::min(Tmp, Tmp2);
8968   }
8969   case RISCVISD::SLLW:
8970   case RISCVISD::SRAW:
8971   case RISCVISD::SRLW:
8972   case RISCVISD::DIVW:
8973   case RISCVISD::DIVUW:
8974   case RISCVISD::REMUW:
8975   case RISCVISD::ROLW:
8976   case RISCVISD::RORW:
8977   case RISCVISD::GREVW:
8978   case RISCVISD::GORCW:
8979   case RISCVISD::FSLW:
8980   case RISCVISD::FSRW:
8981   case RISCVISD::SHFLW:
8982   case RISCVISD::UNSHFLW:
8983   case RISCVISD::BCOMPRESSW:
8984   case RISCVISD::BDECOMPRESSW:
8985   case RISCVISD::BFPW:
8986   case RISCVISD::FCVT_W_RV64:
8987   case RISCVISD::FCVT_WU_RV64:
8988   case RISCVISD::STRICT_FCVT_W_RV64:
8989   case RISCVISD::STRICT_FCVT_WU_RV64:
8990     // TODO: As the result is sign-extended, this is conservatively correct. A
8991     // more precise answer could be calculated for SRAW depending on known
8992     // bits in the shift amount.
8993     return 33;
8994   case RISCVISD::SHFL:
8995   case RISCVISD::UNSHFL: {
8996     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
8997     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
8998     // will stay within the upper 32 bits. If there were more than 32 sign bits
8999     // before there will be at least 33 sign bits after.
9000     if (Op.getValueType() == MVT::i64 &&
9001         isa<ConstantSDNode>(Op.getOperand(1)) &&
9002         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9003       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9004       if (Tmp > 32)
9005         return 33;
9006     }
9007     break;
9008   }
9009   case RISCVISD::VMV_X_S: {
9010     // The number of sign bits of the scalar result is computed by obtaining the
9011     // element type of the input vector operand, subtracting its width from the
9012     // XLEN, and then adding one (sign bit within the element type). If the
9013     // element type is wider than XLen, the least-significant XLEN bits are
9014     // taken.
9015     unsigned XLen = Subtarget.getXLen();
9016     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9017     if (EltBits <= XLen)
9018       return XLen - EltBits + 1;
9019     break;
9020   }
9021   }
9022 
9023   return 1;
9024 }
9025 
9026 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9027                                                   MachineBasicBlock *BB) {
9028   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9029 
9030   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9031   // Should the count have wrapped while it was being read, we need to try
9032   // again.
9033   // ...
9034   // read:
9035   // rdcycleh x3 # load high word of cycle
9036   // rdcycle  x2 # load low word of cycle
9037   // rdcycleh x4 # load high word of cycle
9038   // bne x3, x4, read # check if high word reads match, otherwise try again
9039   // ...
9040 
9041   MachineFunction &MF = *BB->getParent();
9042   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9043   MachineFunction::iterator It = ++BB->getIterator();
9044 
9045   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9046   MF.insert(It, LoopMBB);
9047 
9048   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9049   MF.insert(It, DoneMBB);
9050 
9051   // Transfer the remainder of BB and its successor edges to DoneMBB.
9052   DoneMBB->splice(DoneMBB->begin(), BB,
9053                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9054   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9055 
9056   BB->addSuccessor(LoopMBB);
9057 
9058   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9059   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9060   Register LoReg = MI.getOperand(0).getReg();
9061   Register HiReg = MI.getOperand(1).getReg();
9062   DebugLoc DL = MI.getDebugLoc();
9063 
9064   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9065   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9066       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9067       .addReg(RISCV::X0);
9068   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9069       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9070       .addReg(RISCV::X0);
9071   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9072       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9073       .addReg(RISCV::X0);
9074 
9075   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9076       .addReg(HiReg)
9077       .addReg(ReadAgainReg)
9078       .addMBB(LoopMBB);
9079 
9080   LoopMBB->addSuccessor(LoopMBB);
9081   LoopMBB->addSuccessor(DoneMBB);
9082 
9083   MI.eraseFromParent();
9084 
9085   return DoneMBB;
9086 }
9087 
9088 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9089                                              MachineBasicBlock *BB) {
9090   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9091 
9092   MachineFunction &MF = *BB->getParent();
9093   DebugLoc DL = MI.getDebugLoc();
9094   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9095   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9096   Register LoReg = MI.getOperand(0).getReg();
9097   Register HiReg = MI.getOperand(1).getReg();
9098   Register SrcReg = MI.getOperand(2).getReg();
9099   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9100   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9101 
9102   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9103                           RI);
9104   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9105   MachineMemOperand *MMOLo =
9106       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9107   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9108       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9109   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9110       .addFrameIndex(FI)
9111       .addImm(0)
9112       .addMemOperand(MMOLo);
9113   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9114       .addFrameIndex(FI)
9115       .addImm(4)
9116       .addMemOperand(MMOHi);
9117   MI.eraseFromParent(); // The pseudo instruction is gone now.
9118   return BB;
9119 }
9120 
9121 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9122                                                  MachineBasicBlock *BB) {
9123   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9124          "Unexpected instruction");
9125 
9126   MachineFunction &MF = *BB->getParent();
9127   DebugLoc DL = MI.getDebugLoc();
9128   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9129   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9130   Register DstReg = MI.getOperand(0).getReg();
9131   Register LoReg = MI.getOperand(1).getReg();
9132   Register HiReg = MI.getOperand(2).getReg();
9133   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9134   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9135 
9136   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9137   MachineMemOperand *MMOLo =
9138       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9139   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9140       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9141   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9142       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9143       .addFrameIndex(FI)
9144       .addImm(0)
9145       .addMemOperand(MMOLo);
9146   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9147       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9148       .addFrameIndex(FI)
9149       .addImm(4)
9150       .addMemOperand(MMOHi);
9151   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9152   MI.eraseFromParent(); // The pseudo instruction is gone now.
9153   return BB;
9154 }
9155 
9156 static bool isSelectPseudo(MachineInstr &MI) {
9157   switch (MI.getOpcode()) {
9158   default:
9159     return false;
9160   case RISCV::Select_GPR_Using_CC_GPR:
9161   case RISCV::Select_FPR16_Using_CC_GPR:
9162   case RISCV::Select_FPR32_Using_CC_GPR:
9163   case RISCV::Select_FPR64_Using_CC_GPR:
9164     return true;
9165   }
9166 }
9167 
9168 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9169                                         unsigned RelOpcode, unsigned EqOpcode,
9170                                         const RISCVSubtarget &Subtarget) {
9171   DebugLoc DL = MI.getDebugLoc();
9172   Register DstReg = MI.getOperand(0).getReg();
9173   Register Src1Reg = MI.getOperand(1).getReg();
9174   Register Src2Reg = MI.getOperand(2).getReg();
9175   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9176   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9177   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9178 
9179   // Save the current FFLAGS.
9180   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9181 
9182   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9183                  .addReg(Src1Reg)
9184                  .addReg(Src2Reg);
9185   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9186     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9187 
9188   // Restore the FFLAGS.
9189   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9190       .addReg(SavedFFlags, RegState::Kill);
9191 
9192   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9193   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9194                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9195                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9196   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9197     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9198 
9199   // Erase the pseudoinstruction.
9200   MI.eraseFromParent();
9201   return BB;
9202 }
9203 
9204 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9205                                            MachineBasicBlock *BB,
9206                                            const RISCVSubtarget &Subtarget) {
9207   // To "insert" Select_* instructions, we actually have to insert the triangle
9208   // control-flow pattern.  The incoming instructions know the destination vreg
9209   // to set, the condition code register to branch on, the true/false values to
9210   // select between, and the condcode to use to select the appropriate branch.
9211   //
9212   // We produce the following control flow:
9213   //     HeadMBB
9214   //     |  \
9215   //     |  IfFalseMBB
9216   //     | /
9217   //    TailMBB
9218   //
9219   // When we find a sequence of selects we attempt to optimize their emission
9220   // by sharing the control flow. Currently we only handle cases where we have
9221   // multiple selects with the exact same condition (same LHS, RHS and CC).
9222   // The selects may be interleaved with other instructions if the other
9223   // instructions meet some requirements we deem safe:
9224   // - They are debug instructions. Otherwise,
9225   // - They do not have side-effects, do not access memory and their inputs do
9226   //   not depend on the results of the select pseudo-instructions.
9227   // The TrueV/FalseV operands of the selects cannot depend on the result of
9228   // previous selects in the sequence.
9229   // These conditions could be further relaxed. See the X86 target for a
9230   // related approach and more information.
9231   Register LHS = MI.getOperand(1).getReg();
9232   Register RHS = MI.getOperand(2).getReg();
9233   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9234 
9235   SmallVector<MachineInstr *, 4> SelectDebugValues;
9236   SmallSet<Register, 4> SelectDests;
9237   SelectDests.insert(MI.getOperand(0).getReg());
9238 
9239   MachineInstr *LastSelectPseudo = &MI;
9240 
9241   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9242        SequenceMBBI != E; ++SequenceMBBI) {
9243     if (SequenceMBBI->isDebugInstr())
9244       continue;
9245     else if (isSelectPseudo(*SequenceMBBI)) {
9246       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9247           SequenceMBBI->getOperand(2).getReg() != RHS ||
9248           SequenceMBBI->getOperand(3).getImm() != CC ||
9249           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9250           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9251         break;
9252       LastSelectPseudo = &*SequenceMBBI;
9253       SequenceMBBI->collectDebugValues(SelectDebugValues);
9254       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9255     } else {
9256       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9257           SequenceMBBI->mayLoadOrStore())
9258         break;
9259       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9260             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9261           }))
9262         break;
9263     }
9264   }
9265 
9266   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9267   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9268   DebugLoc DL = MI.getDebugLoc();
9269   MachineFunction::iterator I = ++BB->getIterator();
9270 
9271   MachineBasicBlock *HeadMBB = BB;
9272   MachineFunction *F = BB->getParent();
9273   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9274   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9275 
9276   F->insert(I, IfFalseMBB);
9277   F->insert(I, TailMBB);
9278 
9279   // Transfer debug instructions associated with the selects to TailMBB.
9280   for (MachineInstr *DebugInstr : SelectDebugValues) {
9281     TailMBB->push_back(DebugInstr->removeFromParent());
9282   }
9283 
9284   // Move all instructions after the sequence to TailMBB.
9285   TailMBB->splice(TailMBB->end(), HeadMBB,
9286                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9287   // Update machine-CFG edges by transferring all successors of the current
9288   // block to the new block which will contain the Phi nodes for the selects.
9289   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9290   // Set the successors for HeadMBB.
9291   HeadMBB->addSuccessor(IfFalseMBB);
9292   HeadMBB->addSuccessor(TailMBB);
9293 
9294   // Insert appropriate branch.
9295   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9296     .addReg(LHS)
9297     .addReg(RHS)
9298     .addMBB(TailMBB);
9299 
9300   // IfFalseMBB just falls through to TailMBB.
9301   IfFalseMBB->addSuccessor(TailMBB);
9302 
9303   // Create PHIs for all of the select pseudo-instructions.
9304   auto SelectMBBI = MI.getIterator();
9305   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9306   auto InsertionPoint = TailMBB->begin();
9307   while (SelectMBBI != SelectEnd) {
9308     auto Next = std::next(SelectMBBI);
9309     if (isSelectPseudo(*SelectMBBI)) {
9310       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9311       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9312               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9313           .addReg(SelectMBBI->getOperand(4).getReg())
9314           .addMBB(HeadMBB)
9315           .addReg(SelectMBBI->getOperand(5).getReg())
9316           .addMBB(IfFalseMBB);
9317       SelectMBBI->eraseFromParent();
9318     }
9319     SelectMBBI = Next;
9320   }
9321 
9322   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9323   return TailMBB;
9324 }
9325 
9326 MachineBasicBlock *
9327 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9328                                                  MachineBasicBlock *BB) const {
9329   switch (MI.getOpcode()) {
9330   default:
9331     llvm_unreachable("Unexpected instr type to insert");
9332   case RISCV::ReadCycleWide:
9333     assert(!Subtarget.is64Bit() &&
9334            "ReadCycleWrite is only to be used on riscv32");
9335     return emitReadCycleWidePseudo(MI, BB);
9336   case RISCV::Select_GPR_Using_CC_GPR:
9337   case RISCV::Select_FPR16_Using_CC_GPR:
9338   case RISCV::Select_FPR32_Using_CC_GPR:
9339   case RISCV::Select_FPR64_Using_CC_GPR:
9340     return emitSelectPseudo(MI, BB, Subtarget);
9341   case RISCV::BuildPairF64Pseudo:
9342     return emitBuildPairF64Pseudo(MI, BB);
9343   case RISCV::SplitF64Pseudo:
9344     return emitSplitF64Pseudo(MI, BB);
9345   case RISCV::PseudoQuietFLE_H:
9346     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9347   case RISCV::PseudoQuietFLT_H:
9348     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9349   case RISCV::PseudoQuietFLE_S:
9350     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9351   case RISCV::PseudoQuietFLT_S:
9352     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9353   case RISCV::PseudoQuietFLE_D:
9354     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9355   case RISCV::PseudoQuietFLT_D:
9356     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9357   }
9358 }
9359 
9360 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9361                                                         SDNode *Node) const {
9362   // Add FRM dependency to any instructions with dynamic rounding mode.
9363   unsigned Opc = MI.getOpcode();
9364   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9365   if (Idx < 0)
9366     return;
9367   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9368     return;
9369   // If the instruction already reads FRM, don't add another read.
9370   if (MI.readsRegister(RISCV::FRM))
9371     return;
9372   MI.addOperand(
9373       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9374 }
9375 
9376 // Calling Convention Implementation.
9377 // The expectations for frontend ABI lowering vary from target to target.
9378 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9379 // details, but this is a longer term goal. For now, we simply try to keep the
9380 // role of the frontend as simple and well-defined as possible. The rules can
9381 // be summarised as:
9382 // * Never split up large scalar arguments. We handle them here.
9383 // * If a hardfloat calling convention is being used, and the struct may be
9384 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9385 // available, then pass as two separate arguments. If either the GPRs or FPRs
9386 // are exhausted, then pass according to the rule below.
9387 // * If a struct could never be passed in registers or directly in a stack
9388 // slot (as it is larger than 2*XLEN and the floating point rules don't
9389 // apply), then pass it using a pointer with the byval attribute.
9390 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9391 // word-sized array or a 2*XLEN scalar (depending on alignment).
9392 // * The frontend can determine whether a struct is returned by reference or
9393 // not based on its size and fields. If it will be returned by reference, the
9394 // frontend must modify the prototype so a pointer with the sret annotation is
9395 // passed as the first argument. This is not necessary for large scalar
9396 // returns.
9397 // * Struct return values and varargs should be coerced to structs containing
9398 // register-size fields in the same situations they would be for fixed
9399 // arguments.
9400 
9401 static const MCPhysReg ArgGPRs[] = {
9402   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9403   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9404 };
9405 static const MCPhysReg ArgFPR16s[] = {
9406   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9407   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9408 };
9409 static const MCPhysReg ArgFPR32s[] = {
9410   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9411   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9412 };
9413 static const MCPhysReg ArgFPR64s[] = {
9414   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9415   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9416 };
9417 // This is an interim calling convention and it may be changed in the future.
9418 static const MCPhysReg ArgVRs[] = {
9419     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9420     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9421     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9422 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9423                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9424                                      RISCV::V20M2, RISCV::V22M2};
9425 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9426                                      RISCV::V20M4};
9427 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9428 
9429 // Pass a 2*XLEN argument that has been split into two XLEN values through
9430 // registers or the stack as necessary.
9431 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9432                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9433                                 MVT ValVT2, MVT LocVT2,
9434                                 ISD::ArgFlagsTy ArgFlags2) {
9435   unsigned XLenInBytes = XLen / 8;
9436   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9437     // At least one half can be passed via register.
9438     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9439                                      VA1.getLocVT(), CCValAssign::Full));
9440   } else {
9441     // Both halves must be passed on the stack, with proper alignment.
9442     Align StackAlign =
9443         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9444     State.addLoc(
9445         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9446                             State.AllocateStack(XLenInBytes, StackAlign),
9447                             VA1.getLocVT(), CCValAssign::Full));
9448     State.addLoc(CCValAssign::getMem(
9449         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9450         LocVT2, CCValAssign::Full));
9451     return false;
9452   }
9453 
9454   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9455     // The second half can also be passed via register.
9456     State.addLoc(
9457         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9458   } else {
9459     // The second half is passed via the stack, without additional alignment.
9460     State.addLoc(CCValAssign::getMem(
9461         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9462         LocVT2, CCValAssign::Full));
9463   }
9464 
9465   return false;
9466 }
9467 
9468 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9469                                Optional<unsigned> FirstMaskArgument,
9470                                CCState &State, const RISCVTargetLowering &TLI) {
9471   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9472   if (RC == &RISCV::VRRegClass) {
9473     // Assign the first mask argument to V0.
9474     // This is an interim calling convention and it may be changed in the
9475     // future.
9476     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
9477       return State.AllocateReg(RISCV::V0);
9478     return State.AllocateReg(ArgVRs);
9479   }
9480   if (RC == &RISCV::VRM2RegClass)
9481     return State.AllocateReg(ArgVRM2s);
9482   if (RC == &RISCV::VRM4RegClass)
9483     return State.AllocateReg(ArgVRM4s);
9484   if (RC == &RISCV::VRM8RegClass)
9485     return State.AllocateReg(ArgVRM8s);
9486   llvm_unreachable("Unhandled register class for ValueType");
9487 }
9488 
9489 // Implements the RISC-V calling convention. Returns true upon failure.
9490 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9491                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9492                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9493                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9494                      Optional<unsigned> FirstMaskArgument) {
9495   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9496   assert(XLen == 32 || XLen == 64);
9497   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9498 
9499   // Any return value split in to more than two values can't be returned
9500   // directly. Vectors are returned via the available vector registers.
9501   if (!LocVT.isVector() && IsRet && ValNo > 1)
9502     return true;
9503 
9504   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9505   // variadic argument, or if no F16/F32 argument registers are available.
9506   bool UseGPRForF16_F32 = true;
9507   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9508   // variadic argument, or if no F64 argument registers are available.
9509   bool UseGPRForF64 = true;
9510 
9511   switch (ABI) {
9512   default:
9513     llvm_unreachable("Unexpected ABI");
9514   case RISCVABI::ABI_ILP32:
9515   case RISCVABI::ABI_LP64:
9516     break;
9517   case RISCVABI::ABI_ILP32F:
9518   case RISCVABI::ABI_LP64F:
9519     UseGPRForF16_F32 = !IsFixed;
9520     break;
9521   case RISCVABI::ABI_ILP32D:
9522   case RISCVABI::ABI_LP64D:
9523     UseGPRForF16_F32 = !IsFixed;
9524     UseGPRForF64 = !IsFixed;
9525     break;
9526   }
9527 
9528   // FPR16, FPR32, and FPR64 alias each other.
9529   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9530     UseGPRForF16_F32 = true;
9531     UseGPRForF64 = true;
9532   }
9533 
9534   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9535   // similar local variables rather than directly checking against the target
9536   // ABI.
9537 
9538   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9539     LocVT = XLenVT;
9540     LocInfo = CCValAssign::BCvt;
9541   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9542     LocVT = MVT::i64;
9543     LocInfo = CCValAssign::BCvt;
9544   }
9545 
9546   // If this is a variadic argument, the RISC-V calling convention requires
9547   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9548   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9549   // be used regardless of whether the original argument was split during
9550   // legalisation or not. The argument will not be passed by registers if the
9551   // original type is larger than 2*XLEN, so the register alignment rule does
9552   // not apply.
9553   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9554   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9555       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9556     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9557     // Skip 'odd' register if necessary.
9558     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9559       State.AllocateReg(ArgGPRs);
9560   }
9561 
9562   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9563   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9564       State.getPendingArgFlags();
9565 
9566   assert(PendingLocs.size() == PendingArgFlags.size() &&
9567          "PendingLocs and PendingArgFlags out of sync");
9568 
9569   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9570   // registers are exhausted.
9571   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9572     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9573            "Can't lower f64 if it is split");
9574     // Depending on available argument GPRS, f64 may be passed in a pair of
9575     // GPRs, split between a GPR and the stack, or passed completely on the
9576     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9577     // cases.
9578     Register Reg = State.AllocateReg(ArgGPRs);
9579     LocVT = MVT::i32;
9580     if (!Reg) {
9581       unsigned StackOffset = State.AllocateStack(8, Align(8));
9582       State.addLoc(
9583           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9584       return false;
9585     }
9586     if (!State.AllocateReg(ArgGPRs))
9587       State.AllocateStack(4, Align(4));
9588     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9589     return false;
9590   }
9591 
9592   // Fixed-length vectors are located in the corresponding scalable-vector
9593   // container types.
9594   if (ValVT.isFixedLengthVector())
9595     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9596 
9597   // Split arguments might be passed indirectly, so keep track of the pending
9598   // values. Split vectors are passed via a mix of registers and indirectly, so
9599   // treat them as we would any other argument.
9600   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9601     LocVT = XLenVT;
9602     LocInfo = CCValAssign::Indirect;
9603     PendingLocs.push_back(
9604         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9605     PendingArgFlags.push_back(ArgFlags);
9606     if (!ArgFlags.isSplitEnd()) {
9607       return false;
9608     }
9609   }
9610 
9611   // If the split argument only had two elements, it should be passed directly
9612   // in registers or on the stack.
9613   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9614       PendingLocs.size() <= 2) {
9615     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9616     // Apply the normal calling convention rules to the first half of the
9617     // split argument.
9618     CCValAssign VA = PendingLocs[0];
9619     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9620     PendingLocs.clear();
9621     PendingArgFlags.clear();
9622     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9623                                ArgFlags);
9624   }
9625 
9626   // Allocate to a register if possible, or else a stack slot.
9627   Register Reg;
9628   unsigned StoreSizeBytes = XLen / 8;
9629   Align StackAlign = Align(XLen / 8);
9630 
9631   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9632     Reg = State.AllocateReg(ArgFPR16s);
9633   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9634     Reg = State.AllocateReg(ArgFPR32s);
9635   else if (ValVT == MVT::f64 && !UseGPRForF64)
9636     Reg = State.AllocateReg(ArgFPR64s);
9637   else if (ValVT.isVector()) {
9638     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9639     if (!Reg) {
9640       // For return values, the vector must be passed fully via registers or
9641       // via the stack.
9642       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9643       // but we're using all of them.
9644       if (IsRet)
9645         return true;
9646       // Try using a GPR to pass the address
9647       if ((Reg = State.AllocateReg(ArgGPRs))) {
9648         LocVT = XLenVT;
9649         LocInfo = CCValAssign::Indirect;
9650       } else if (ValVT.isScalableVector()) {
9651         LocVT = XLenVT;
9652         LocInfo = CCValAssign::Indirect;
9653       } else {
9654         // Pass fixed-length vectors on the stack.
9655         LocVT = ValVT;
9656         StoreSizeBytes = ValVT.getStoreSize();
9657         // Align vectors to their element sizes, being careful for vXi1
9658         // vectors.
9659         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9660       }
9661     }
9662   } else {
9663     Reg = State.AllocateReg(ArgGPRs);
9664   }
9665 
9666   unsigned StackOffset =
9667       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9668 
9669   // If we reach this point and PendingLocs is non-empty, we must be at the
9670   // end of a split argument that must be passed indirectly.
9671   if (!PendingLocs.empty()) {
9672     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9673     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9674 
9675     for (auto &It : PendingLocs) {
9676       if (Reg)
9677         It.convertToReg(Reg);
9678       else
9679         It.convertToMem(StackOffset);
9680       State.addLoc(It);
9681     }
9682     PendingLocs.clear();
9683     PendingArgFlags.clear();
9684     return false;
9685   }
9686 
9687   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9688           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9689          "Expected an XLenVT or vector types at this stage");
9690 
9691   if (Reg) {
9692     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9693     return false;
9694   }
9695 
9696   // When a floating-point value is passed on the stack, no bit-conversion is
9697   // needed.
9698   if (ValVT.isFloatingPoint()) {
9699     LocVT = ValVT;
9700     LocInfo = CCValAssign::Full;
9701   }
9702   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9703   return false;
9704 }
9705 
9706 template <typename ArgTy>
9707 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9708   for (const auto &ArgIdx : enumerate(Args)) {
9709     MVT ArgVT = ArgIdx.value().VT;
9710     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9711       return ArgIdx.index();
9712   }
9713   return None;
9714 }
9715 
9716 void RISCVTargetLowering::analyzeInputArgs(
9717     MachineFunction &MF, CCState &CCInfo,
9718     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9719     RISCVCCAssignFn Fn) const {
9720   unsigned NumArgs = Ins.size();
9721   FunctionType *FType = MF.getFunction().getFunctionType();
9722 
9723   Optional<unsigned> FirstMaskArgument;
9724   if (Subtarget.hasVInstructions())
9725     FirstMaskArgument = preAssignMask(Ins);
9726 
9727   for (unsigned i = 0; i != NumArgs; ++i) {
9728     MVT ArgVT = Ins[i].VT;
9729     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9730 
9731     Type *ArgTy = nullptr;
9732     if (IsRet)
9733       ArgTy = FType->getReturnType();
9734     else if (Ins[i].isOrigArg())
9735       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9736 
9737     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9738     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9739            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9740            FirstMaskArgument)) {
9741       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9742                         << EVT(ArgVT).getEVTString() << '\n');
9743       llvm_unreachable(nullptr);
9744     }
9745   }
9746 }
9747 
9748 void RISCVTargetLowering::analyzeOutputArgs(
9749     MachineFunction &MF, CCState &CCInfo,
9750     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9751     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9752   unsigned NumArgs = Outs.size();
9753 
9754   Optional<unsigned> FirstMaskArgument;
9755   if (Subtarget.hasVInstructions())
9756     FirstMaskArgument = preAssignMask(Outs);
9757 
9758   for (unsigned i = 0; i != NumArgs; i++) {
9759     MVT ArgVT = Outs[i].VT;
9760     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9761     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9762 
9763     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9764     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9765            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9766            FirstMaskArgument)) {
9767       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9768                         << EVT(ArgVT).getEVTString() << "\n");
9769       llvm_unreachable(nullptr);
9770     }
9771   }
9772 }
9773 
9774 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9775 // values.
9776 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9777                                    const CCValAssign &VA, const SDLoc &DL,
9778                                    const RISCVSubtarget &Subtarget) {
9779   switch (VA.getLocInfo()) {
9780   default:
9781     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9782   case CCValAssign::Full:
9783     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9784       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9785     break;
9786   case CCValAssign::BCvt:
9787     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9788       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9789     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9790       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9791     else
9792       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9793     break;
9794   }
9795   return Val;
9796 }
9797 
9798 // The caller is responsible for loading the full value if the argument is
9799 // passed with CCValAssign::Indirect.
9800 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9801                                 const CCValAssign &VA, const SDLoc &DL,
9802                                 const RISCVTargetLowering &TLI) {
9803   MachineFunction &MF = DAG.getMachineFunction();
9804   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9805   EVT LocVT = VA.getLocVT();
9806   SDValue Val;
9807   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9808   Register VReg = RegInfo.createVirtualRegister(RC);
9809   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9810   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9811 
9812   if (VA.getLocInfo() == CCValAssign::Indirect)
9813     return Val;
9814 
9815   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9816 }
9817 
9818 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9819                                    const CCValAssign &VA, const SDLoc &DL,
9820                                    const RISCVSubtarget &Subtarget) {
9821   EVT LocVT = VA.getLocVT();
9822 
9823   switch (VA.getLocInfo()) {
9824   default:
9825     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9826   case CCValAssign::Full:
9827     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9828       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9829     break;
9830   case CCValAssign::BCvt:
9831     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9832       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
9833     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9834       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
9835     else
9836       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
9837     break;
9838   }
9839   return Val;
9840 }
9841 
9842 // The caller is responsible for loading the full value if the argument is
9843 // passed with CCValAssign::Indirect.
9844 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
9845                                 const CCValAssign &VA, const SDLoc &DL) {
9846   MachineFunction &MF = DAG.getMachineFunction();
9847   MachineFrameInfo &MFI = MF.getFrameInfo();
9848   EVT LocVT = VA.getLocVT();
9849   EVT ValVT = VA.getValVT();
9850   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
9851   if (ValVT.isScalableVector()) {
9852     // When the value is a scalable vector, we save the pointer which points to
9853     // the scalable vector value in the stack. The ValVT will be the pointer
9854     // type, instead of the scalable vector type.
9855     ValVT = LocVT;
9856   }
9857   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
9858                                  /*IsImmutable=*/true);
9859   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
9860   SDValue Val;
9861 
9862   ISD::LoadExtType ExtType;
9863   switch (VA.getLocInfo()) {
9864   default:
9865     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9866   case CCValAssign::Full:
9867   case CCValAssign::Indirect:
9868   case CCValAssign::BCvt:
9869     ExtType = ISD::NON_EXTLOAD;
9870     break;
9871   }
9872   Val = DAG.getExtLoad(
9873       ExtType, DL, LocVT, Chain, FIN,
9874       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
9875   return Val;
9876 }
9877 
9878 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
9879                                        const CCValAssign &VA, const SDLoc &DL) {
9880   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
9881          "Unexpected VA");
9882   MachineFunction &MF = DAG.getMachineFunction();
9883   MachineFrameInfo &MFI = MF.getFrameInfo();
9884   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9885 
9886   if (VA.isMemLoc()) {
9887     // f64 is passed on the stack.
9888     int FI =
9889         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
9890     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9891     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
9892                        MachinePointerInfo::getFixedStack(MF, FI));
9893   }
9894 
9895   assert(VA.isRegLoc() && "Expected register VA assignment");
9896 
9897   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9898   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
9899   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
9900   SDValue Hi;
9901   if (VA.getLocReg() == RISCV::X17) {
9902     // Second half of f64 is passed on the stack.
9903     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
9904     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9905     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
9906                      MachinePointerInfo::getFixedStack(MF, FI));
9907   } else {
9908     // Second half of f64 is passed in another GPR.
9909     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9910     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
9911     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
9912   }
9913   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
9914 }
9915 
9916 // FastCC has less than 1% performance improvement for some particular
9917 // benchmark. But theoretically, it may has benenfit for some cases.
9918 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
9919                             unsigned ValNo, MVT ValVT, MVT LocVT,
9920                             CCValAssign::LocInfo LocInfo,
9921                             ISD::ArgFlagsTy ArgFlags, CCState &State,
9922                             bool IsFixed, bool IsRet, Type *OrigTy,
9923                             const RISCVTargetLowering &TLI,
9924                             Optional<unsigned> FirstMaskArgument) {
9925 
9926   // X5 and X6 might be used for save-restore libcall.
9927   static const MCPhysReg GPRList[] = {
9928       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
9929       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
9930       RISCV::X29, RISCV::X30, RISCV::X31};
9931 
9932   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9933     if (unsigned Reg = State.AllocateReg(GPRList)) {
9934       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9935       return false;
9936     }
9937   }
9938 
9939   if (LocVT == MVT::f16) {
9940     static const MCPhysReg FPR16List[] = {
9941         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
9942         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
9943         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
9944         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
9945     if (unsigned Reg = State.AllocateReg(FPR16List)) {
9946       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9947       return false;
9948     }
9949   }
9950 
9951   if (LocVT == MVT::f32) {
9952     static const MCPhysReg FPR32List[] = {
9953         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
9954         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
9955         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
9956         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
9957     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9958       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9959       return false;
9960     }
9961   }
9962 
9963   if (LocVT == MVT::f64) {
9964     static const MCPhysReg FPR64List[] = {
9965         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
9966         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
9967         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
9968         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
9969     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9970       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9971       return false;
9972     }
9973   }
9974 
9975   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
9976     unsigned Offset4 = State.AllocateStack(4, Align(4));
9977     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
9978     return false;
9979   }
9980 
9981   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
9982     unsigned Offset5 = State.AllocateStack(8, Align(8));
9983     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
9984     return false;
9985   }
9986 
9987   if (LocVT.isVector()) {
9988     if (unsigned Reg =
9989             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
9990       // Fixed-length vectors are located in the corresponding scalable-vector
9991       // container types.
9992       if (ValVT.isFixedLengthVector())
9993         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9994       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9995     } else {
9996       // Try and pass the address via a "fast" GPR.
9997       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
9998         LocInfo = CCValAssign::Indirect;
9999         LocVT = TLI.getSubtarget().getXLenVT();
10000         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10001       } else if (ValVT.isFixedLengthVector()) {
10002         auto StackAlign =
10003             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10004         unsigned StackOffset =
10005             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10006         State.addLoc(
10007             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10008       } else {
10009         // Can't pass scalable vectors on the stack.
10010         return true;
10011       }
10012     }
10013 
10014     return false;
10015   }
10016 
10017   return true; // CC didn't match.
10018 }
10019 
10020 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10021                          CCValAssign::LocInfo LocInfo,
10022                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10023 
10024   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10025     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10026     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10027     static const MCPhysReg GPRList[] = {
10028         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10029         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10030     if (unsigned Reg = State.AllocateReg(GPRList)) {
10031       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10032       return false;
10033     }
10034   }
10035 
10036   if (LocVT == MVT::f32) {
10037     // Pass in STG registers: F1, ..., F6
10038     //                        fs0 ... fs5
10039     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10040                                           RISCV::F18_F, RISCV::F19_F,
10041                                           RISCV::F20_F, RISCV::F21_F};
10042     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10043       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10044       return false;
10045     }
10046   }
10047 
10048   if (LocVT == MVT::f64) {
10049     // Pass in STG registers: D1, ..., D6
10050     //                        fs6 ... fs11
10051     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10052                                           RISCV::F24_D, RISCV::F25_D,
10053                                           RISCV::F26_D, RISCV::F27_D};
10054     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10055       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10056       return false;
10057     }
10058   }
10059 
10060   report_fatal_error("No registers left in GHC calling convention");
10061   return true;
10062 }
10063 
10064 // Transform physical registers into virtual registers.
10065 SDValue RISCVTargetLowering::LowerFormalArguments(
10066     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10067     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10068     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10069 
10070   MachineFunction &MF = DAG.getMachineFunction();
10071 
10072   switch (CallConv) {
10073   default:
10074     report_fatal_error("Unsupported calling convention");
10075   case CallingConv::C:
10076   case CallingConv::Fast:
10077     break;
10078   case CallingConv::GHC:
10079     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10080         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10081       report_fatal_error(
10082         "GHC calling convention requires the F and D instruction set extensions");
10083   }
10084 
10085   const Function &Func = MF.getFunction();
10086   if (Func.hasFnAttribute("interrupt")) {
10087     if (!Func.arg_empty())
10088       report_fatal_error(
10089         "Functions with the interrupt attribute cannot have arguments!");
10090 
10091     StringRef Kind =
10092       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10093 
10094     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10095       report_fatal_error(
10096         "Function interrupt attribute argument not supported!");
10097   }
10098 
10099   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10100   MVT XLenVT = Subtarget.getXLenVT();
10101   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10102   // Used with vargs to acumulate store chains.
10103   std::vector<SDValue> OutChains;
10104 
10105   // Assign locations to all of the incoming arguments.
10106   SmallVector<CCValAssign, 16> ArgLocs;
10107   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10108 
10109   if (CallConv == CallingConv::GHC)
10110     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10111   else
10112     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10113                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10114                                                    : CC_RISCV);
10115 
10116   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10117     CCValAssign &VA = ArgLocs[i];
10118     SDValue ArgValue;
10119     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10120     // case.
10121     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10122       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10123     else if (VA.isRegLoc())
10124       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10125     else
10126       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10127 
10128     if (VA.getLocInfo() == CCValAssign::Indirect) {
10129       // If the original argument was split and passed by reference (e.g. i128
10130       // on RV32), we need to load all parts of it here (using the same
10131       // address). Vectors may be partly split to registers and partly to the
10132       // stack, in which case the base address is partly offset and subsequent
10133       // stores are relative to that.
10134       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10135                                    MachinePointerInfo()));
10136       unsigned ArgIndex = Ins[i].OrigArgIndex;
10137       unsigned ArgPartOffset = Ins[i].PartOffset;
10138       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10139       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10140         CCValAssign &PartVA = ArgLocs[i + 1];
10141         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10142         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10143         if (PartVA.getValVT().isScalableVector())
10144           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10145         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10146         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10147                                      MachinePointerInfo()));
10148         ++i;
10149       }
10150       continue;
10151     }
10152     InVals.push_back(ArgValue);
10153   }
10154 
10155   if (IsVarArg) {
10156     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10157     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10158     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10159     MachineFrameInfo &MFI = MF.getFrameInfo();
10160     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10161     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10162 
10163     // Offset of the first variable argument from stack pointer, and size of
10164     // the vararg save area. For now, the varargs save area is either zero or
10165     // large enough to hold a0-a7.
10166     int VaArgOffset, VarArgsSaveSize;
10167 
10168     // If all registers are allocated, then all varargs must be passed on the
10169     // stack and we don't need to save any argregs.
10170     if (ArgRegs.size() == Idx) {
10171       VaArgOffset = CCInfo.getNextStackOffset();
10172       VarArgsSaveSize = 0;
10173     } else {
10174       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10175       VaArgOffset = -VarArgsSaveSize;
10176     }
10177 
10178     // Record the frame index of the first variable argument
10179     // which is a value necessary to VASTART.
10180     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10181     RVFI->setVarArgsFrameIndex(FI);
10182 
10183     // If saving an odd number of registers then create an extra stack slot to
10184     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10185     // offsets to even-numbered registered remain 2*XLEN-aligned.
10186     if (Idx % 2) {
10187       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10188       VarArgsSaveSize += XLenInBytes;
10189     }
10190 
10191     // Copy the integer registers that may have been used for passing varargs
10192     // to the vararg save area.
10193     for (unsigned I = Idx; I < ArgRegs.size();
10194          ++I, VaArgOffset += XLenInBytes) {
10195       const Register Reg = RegInfo.createVirtualRegister(RC);
10196       RegInfo.addLiveIn(ArgRegs[I], Reg);
10197       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10198       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10199       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10200       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10201                                    MachinePointerInfo::getFixedStack(MF, FI));
10202       cast<StoreSDNode>(Store.getNode())
10203           ->getMemOperand()
10204           ->setValue((Value *)nullptr);
10205       OutChains.push_back(Store);
10206     }
10207     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10208   }
10209 
10210   // All stores are grouped in one node to allow the matching between
10211   // the size of Ins and InVals. This only happens for vararg functions.
10212   if (!OutChains.empty()) {
10213     OutChains.push_back(Chain);
10214     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10215   }
10216 
10217   return Chain;
10218 }
10219 
10220 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10221 /// for tail call optimization.
10222 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10223 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10224     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10225     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10226 
10227   auto &Callee = CLI.Callee;
10228   auto CalleeCC = CLI.CallConv;
10229   auto &Outs = CLI.Outs;
10230   auto &Caller = MF.getFunction();
10231   auto CallerCC = Caller.getCallingConv();
10232 
10233   // Exception-handling functions need a special set of instructions to
10234   // indicate a return to the hardware. Tail-calling another function would
10235   // probably break this.
10236   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10237   // should be expanded as new function attributes are introduced.
10238   if (Caller.hasFnAttribute("interrupt"))
10239     return false;
10240 
10241   // Do not tail call opt if the stack is used to pass parameters.
10242   if (CCInfo.getNextStackOffset() != 0)
10243     return false;
10244 
10245   // Do not tail call opt if any parameters need to be passed indirectly.
10246   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10247   // passed indirectly. So the address of the value will be passed in a
10248   // register, or if not available, then the address is put on the stack. In
10249   // order to pass indirectly, space on the stack often needs to be allocated
10250   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10251   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10252   // are passed CCValAssign::Indirect.
10253   for (auto &VA : ArgLocs)
10254     if (VA.getLocInfo() == CCValAssign::Indirect)
10255       return false;
10256 
10257   // Do not tail call opt if either caller or callee uses struct return
10258   // semantics.
10259   auto IsCallerStructRet = Caller.hasStructRetAttr();
10260   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10261   if (IsCallerStructRet || IsCalleeStructRet)
10262     return false;
10263 
10264   // Externally-defined functions with weak linkage should not be
10265   // tail-called. The behaviour of branch instructions in this situation (as
10266   // used for tail calls) is implementation-defined, so we cannot rely on the
10267   // linker replacing the tail call with a return.
10268   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10269     const GlobalValue *GV = G->getGlobal();
10270     if (GV->hasExternalWeakLinkage())
10271       return false;
10272   }
10273 
10274   // The callee has to preserve all registers the caller needs to preserve.
10275   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10276   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10277   if (CalleeCC != CallerCC) {
10278     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10279     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10280       return false;
10281   }
10282 
10283   // Byval parameters hand the function a pointer directly into the stack area
10284   // we want to reuse during a tail call. Working around this *is* possible
10285   // but less efficient and uglier in LowerCall.
10286   for (auto &Arg : Outs)
10287     if (Arg.Flags.isByVal())
10288       return false;
10289 
10290   return true;
10291 }
10292 
10293 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10294   return DAG.getDataLayout().getPrefTypeAlign(
10295       VT.getTypeForEVT(*DAG.getContext()));
10296 }
10297 
10298 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10299 // and output parameter nodes.
10300 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10301                                        SmallVectorImpl<SDValue> &InVals) const {
10302   SelectionDAG &DAG = CLI.DAG;
10303   SDLoc &DL = CLI.DL;
10304   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10305   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10306   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10307   SDValue Chain = CLI.Chain;
10308   SDValue Callee = CLI.Callee;
10309   bool &IsTailCall = CLI.IsTailCall;
10310   CallingConv::ID CallConv = CLI.CallConv;
10311   bool IsVarArg = CLI.IsVarArg;
10312   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10313   MVT XLenVT = Subtarget.getXLenVT();
10314 
10315   MachineFunction &MF = DAG.getMachineFunction();
10316 
10317   // Analyze the operands of the call, assigning locations to each operand.
10318   SmallVector<CCValAssign, 16> ArgLocs;
10319   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10320 
10321   if (CallConv == CallingConv::GHC)
10322     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10323   else
10324     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10325                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10326                                                     : CC_RISCV);
10327 
10328   // Check if it's really possible to do a tail call.
10329   if (IsTailCall)
10330     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10331 
10332   if (IsTailCall)
10333     ++NumTailCalls;
10334   else if (CLI.CB && CLI.CB->isMustTailCall())
10335     report_fatal_error("failed to perform tail call elimination on a call "
10336                        "site marked musttail");
10337 
10338   // Get a count of how many bytes are to be pushed on the stack.
10339   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10340 
10341   // Create local copies for byval args
10342   SmallVector<SDValue, 8> ByValArgs;
10343   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10344     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10345     if (!Flags.isByVal())
10346       continue;
10347 
10348     SDValue Arg = OutVals[i];
10349     unsigned Size = Flags.getByValSize();
10350     Align Alignment = Flags.getNonZeroByValAlign();
10351 
10352     int FI =
10353         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10354     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10355     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10356 
10357     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10358                           /*IsVolatile=*/false,
10359                           /*AlwaysInline=*/false, IsTailCall,
10360                           MachinePointerInfo(), MachinePointerInfo());
10361     ByValArgs.push_back(FIPtr);
10362   }
10363 
10364   if (!IsTailCall)
10365     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10366 
10367   // Copy argument values to their designated locations.
10368   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10369   SmallVector<SDValue, 8> MemOpChains;
10370   SDValue StackPtr;
10371   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10372     CCValAssign &VA = ArgLocs[i];
10373     SDValue ArgValue = OutVals[i];
10374     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10375 
10376     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10377     bool IsF64OnRV32DSoftABI =
10378         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10379     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10380       SDValue SplitF64 = DAG.getNode(
10381           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10382       SDValue Lo = SplitF64.getValue(0);
10383       SDValue Hi = SplitF64.getValue(1);
10384 
10385       Register RegLo = VA.getLocReg();
10386       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10387 
10388       if (RegLo == RISCV::X17) {
10389         // Second half of f64 is passed on the stack.
10390         // Work out the address of the stack slot.
10391         if (!StackPtr.getNode())
10392           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10393         // Emit the store.
10394         MemOpChains.push_back(
10395             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10396       } else {
10397         // Second half of f64 is passed in another GPR.
10398         assert(RegLo < RISCV::X31 && "Invalid register pair");
10399         Register RegHigh = RegLo + 1;
10400         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10401       }
10402       continue;
10403     }
10404 
10405     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10406     // as any other MemLoc.
10407 
10408     // Promote the value if needed.
10409     // For now, only handle fully promoted and indirect arguments.
10410     if (VA.getLocInfo() == CCValAssign::Indirect) {
10411       // Store the argument in a stack slot and pass its address.
10412       Align StackAlign =
10413           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10414                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10415       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10416       // If the original argument was split (e.g. i128), we need
10417       // to store the required parts of it here (and pass just one address).
10418       // Vectors may be partly split to registers and partly to the stack, in
10419       // which case the base address is partly offset and subsequent stores are
10420       // relative to that.
10421       unsigned ArgIndex = Outs[i].OrigArgIndex;
10422       unsigned ArgPartOffset = Outs[i].PartOffset;
10423       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10424       // Calculate the total size to store. We don't have access to what we're
10425       // actually storing other than performing the loop and collecting the
10426       // info.
10427       SmallVector<std::pair<SDValue, SDValue>> Parts;
10428       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10429         SDValue PartValue = OutVals[i + 1];
10430         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10431         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10432         EVT PartVT = PartValue.getValueType();
10433         if (PartVT.isScalableVector())
10434           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10435         StoredSize += PartVT.getStoreSize();
10436         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10437         Parts.push_back(std::make_pair(PartValue, Offset));
10438         ++i;
10439       }
10440       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10441       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10442       MemOpChains.push_back(
10443           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10444                        MachinePointerInfo::getFixedStack(MF, FI)));
10445       for (const auto &Part : Parts) {
10446         SDValue PartValue = Part.first;
10447         SDValue PartOffset = Part.second;
10448         SDValue Address =
10449             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10450         MemOpChains.push_back(
10451             DAG.getStore(Chain, DL, PartValue, Address,
10452                          MachinePointerInfo::getFixedStack(MF, FI)));
10453       }
10454       ArgValue = SpillSlot;
10455     } else {
10456       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10457     }
10458 
10459     // Use local copy if it is a byval arg.
10460     if (Flags.isByVal())
10461       ArgValue = ByValArgs[j++];
10462 
10463     if (VA.isRegLoc()) {
10464       // Queue up the argument copies and emit them at the end.
10465       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10466     } else {
10467       assert(VA.isMemLoc() && "Argument not register or memory");
10468       assert(!IsTailCall && "Tail call not allowed if stack is used "
10469                             "for passing parameters");
10470 
10471       // Work out the address of the stack slot.
10472       if (!StackPtr.getNode())
10473         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10474       SDValue Address =
10475           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10476                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10477 
10478       // Emit the store.
10479       MemOpChains.push_back(
10480           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10481     }
10482   }
10483 
10484   // Join the stores, which are independent of one another.
10485   if (!MemOpChains.empty())
10486     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10487 
10488   SDValue Glue;
10489 
10490   // Build a sequence of copy-to-reg nodes, chained and glued together.
10491   for (auto &Reg : RegsToPass) {
10492     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10493     Glue = Chain.getValue(1);
10494   }
10495 
10496   // Validate that none of the argument registers have been marked as
10497   // reserved, if so report an error. Do the same for the return address if this
10498   // is not a tailcall.
10499   validateCCReservedRegs(RegsToPass, MF);
10500   if (!IsTailCall &&
10501       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10502     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10503         MF.getFunction(),
10504         "Return address register required, but has been reserved."});
10505 
10506   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10507   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10508   // split it and then direct call can be matched by PseudoCALL.
10509   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10510     const GlobalValue *GV = S->getGlobal();
10511 
10512     unsigned OpFlags = RISCVII::MO_CALL;
10513     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10514       OpFlags = RISCVII::MO_PLT;
10515 
10516     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10517   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10518     unsigned OpFlags = RISCVII::MO_CALL;
10519 
10520     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10521                                                  nullptr))
10522       OpFlags = RISCVII::MO_PLT;
10523 
10524     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10525   }
10526 
10527   // The first call operand is the chain and the second is the target address.
10528   SmallVector<SDValue, 8> Ops;
10529   Ops.push_back(Chain);
10530   Ops.push_back(Callee);
10531 
10532   // Add argument registers to the end of the list so that they are
10533   // known live into the call.
10534   for (auto &Reg : RegsToPass)
10535     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10536 
10537   if (!IsTailCall) {
10538     // Add a register mask operand representing the call-preserved registers.
10539     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10540     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10541     assert(Mask && "Missing call preserved mask for calling convention");
10542     Ops.push_back(DAG.getRegisterMask(Mask));
10543   }
10544 
10545   // Glue the call to the argument copies, if any.
10546   if (Glue.getNode())
10547     Ops.push_back(Glue);
10548 
10549   // Emit the call.
10550   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10551 
10552   if (IsTailCall) {
10553     MF.getFrameInfo().setHasTailCall();
10554     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10555   }
10556 
10557   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10558   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10559   Glue = Chain.getValue(1);
10560 
10561   // Mark the end of the call, which is glued to the call itself.
10562   Chain = DAG.getCALLSEQ_END(Chain,
10563                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10564                              DAG.getConstant(0, DL, PtrVT, true),
10565                              Glue, DL);
10566   Glue = Chain.getValue(1);
10567 
10568   // Assign locations to each value returned by this call.
10569   SmallVector<CCValAssign, 16> RVLocs;
10570   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10571   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10572 
10573   // Copy all of the result registers out of their specified physreg.
10574   for (auto &VA : RVLocs) {
10575     // Copy the value out
10576     SDValue RetValue =
10577         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10578     // Glue the RetValue to the end of the call sequence
10579     Chain = RetValue.getValue(1);
10580     Glue = RetValue.getValue(2);
10581 
10582     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10583       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10584       SDValue RetValue2 =
10585           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10586       Chain = RetValue2.getValue(1);
10587       Glue = RetValue2.getValue(2);
10588       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10589                              RetValue2);
10590     }
10591 
10592     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10593 
10594     InVals.push_back(RetValue);
10595   }
10596 
10597   return Chain;
10598 }
10599 
10600 bool RISCVTargetLowering::CanLowerReturn(
10601     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10602     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10603   SmallVector<CCValAssign, 16> RVLocs;
10604   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10605 
10606   Optional<unsigned> FirstMaskArgument;
10607   if (Subtarget.hasVInstructions())
10608     FirstMaskArgument = preAssignMask(Outs);
10609 
10610   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10611     MVT VT = Outs[i].VT;
10612     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10613     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10614     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10615                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10616                  *this, FirstMaskArgument))
10617       return false;
10618   }
10619   return true;
10620 }
10621 
10622 SDValue
10623 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10624                                  bool IsVarArg,
10625                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10626                                  const SmallVectorImpl<SDValue> &OutVals,
10627                                  const SDLoc &DL, SelectionDAG &DAG) const {
10628   const MachineFunction &MF = DAG.getMachineFunction();
10629   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10630 
10631   // Stores the assignment of the return value to a location.
10632   SmallVector<CCValAssign, 16> RVLocs;
10633 
10634   // Info about the registers and stack slot.
10635   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10636                  *DAG.getContext());
10637 
10638   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10639                     nullptr, CC_RISCV);
10640 
10641   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10642     report_fatal_error("GHC functions return void only");
10643 
10644   SDValue Glue;
10645   SmallVector<SDValue, 4> RetOps(1, Chain);
10646 
10647   // Copy the result values into the output registers.
10648   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10649     SDValue Val = OutVals[i];
10650     CCValAssign &VA = RVLocs[i];
10651     assert(VA.isRegLoc() && "Can only return in registers!");
10652 
10653     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10654       // Handle returning f64 on RV32D with a soft float ABI.
10655       assert(VA.isRegLoc() && "Expected return via registers");
10656       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10657                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10658       SDValue Lo = SplitF64.getValue(0);
10659       SDValue Hi = SplitF64.getValue(1);
10660       Register RegLo = VA.getLocReg();
10661       assert(RegLo < RISCV::X31 && "Invalid register pair");
10662       Register RegHi = RegLo + 1;
10663 
10664       if (STI.isRegisterReservedByUser(RegLo) ||
10665           STI.isRegisterReservedByUser(RegHi))
10666         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10667             MF.getFunction(),
10668             "Return value register required, but has been reserved."});
10669 
10670       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10671       Glue = Chain.getValue(1);
10672       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10673       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10674       Glue = Chain.getValue(1);
10675       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10676     } else {
10677       // Handle a 'normal' return.
10678       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10679       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10680 
10681       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10682         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10683             MF.getFunction(),
10684             "Return value register required, but has been reserved."});
10685 
10686       // Guarantee that all emitted copies are stuck together.
10687       Glue = Chain.getValue(1);
10688       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10689     }
10690   }
10691 
10692   RetOps[0] = Chain; // Update chain.
10693 
10694   // Add the glue node if we have it.
10695   if (Glue.getNode()) {
10696     RetOps.push_back(Glue);
10697   }
10698 
10699   unsigned RetOpc = RISCVISD::RET_FLAG;
10700   // Interrupt service routines use different return instructions.
10701   const Function &Func = DAG.getMachineFunction().getFunction();
10702   if (Func.hasFnAttribute("interrupt")) {
10703     if (!Func.getReturnType()->isVoidTy())
10704       report_fatal_error(
10705           "Functions with the interrupt attribute must have void return type!");
10706 
10707     MachineFunction &MF = DAG.getMachineFunction();
10708     StringRef Kind =
10709       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10710 
10711     if (Kind == "user")
10712       RetOpc = RISCVISD::URET_FLAG;
10713     else if (Kind == "supervisor")
10714       RetOpc = RISCVISD::SRET_FLAG;
10715     else
10716       RetOpc = RISCVISD::MRET_FLAG;
10717   }
10718 
10719   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10720 }
10721 
10722 void RISCVTargetLowering::validateCCReservedRegs(
10723     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10724     MachineFunction &MF) const {
10725   const Function &F = MF.getFunction();
10726   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10727 
10728   if (llvm::any_of(Regs, [&STI](auto Reg) {
10729         return STI.isRegisterReservedByUser(Reg.first);
10730       }))
10731     F.getContext().diagnose(DiagnosticInfoUnsupported{
10732         F, "Argument register required, but has been reserved."});
10733 }
10734 
10735 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10736   return CI->isTailCall();
10737 }
10738 
10739 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10740 #define NODE_NAME_CASE(NODE)                                                   \
10741   case RISCVISD::NODE:                                                         \
10742     return "RISCVISD::" #NODE;
10743   // clang-format off
10744   switch ((RISCVISD::NodeType)Opcode) {
10745   case RISCVISD::FIRST_NUMBER:
10746     break;
10747   NODE_NAME_CASE(RET_FLAG)
10748   NODE_NAME_CASE(URET_FLAG)
10749   NODE_NAME_CASE(SRET_FLAG)
10750   NODE_NAME_CASE(MRET_FLAG)
10751   NODE_NAME_CASE(CALL)
10752   NODE_NAME_CASE(SELECT_CC)
10753   NODE_NAME_CASE(BR_CC)
10754   NODE_NAME_CASE(BuildPairF64)
10755   NODE_NAME_CASE(SplitF64)
10756   NODE_NAME_CASE(TAIL)
10757   NODE_NAME_CASE(MULHSU)
10758   NODE_NAME_CASE(SLLW)
10759   NODE_NAME_CASE(SRAW)
10760   NODE_NAME_CASE(SRLW)
10761   NODE_NAME_CASE(DIVW)
10762   NODE_NAME_CASE(DIVUW)
10763   NODE_NAME_CASE(REMUW)
10764   NODE_NAME_CASE(ROLW)
10765   NODE_NAME_CASE(RORW)
10766   NODE_NAME_CASE(CLZW)
10767   NODE_NAME_CASE(CTZW)
10768   NODE_NAME_CASE(FSLW)
10769   NODE_NAME_CASE(FSRW)
10770   NODE_NAME_CASE(FSL)
10771   NODE_NAME_CASE(FSR)
10772   NODE_NAME_CASE(FMV_H_X)
10773   NODE_NAME_CASE(FMV_X_ANYEXTH)
10774   NODE_NAME_CASE(FMV_X_SIGNEXTH)
10775   NODE_NAME_CASE(FMV_W_X_RV64)
10776   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10777   NODE_NAME_CASE(FCVT_X)
10778   NODE_NAME_CASE(FCVT_XU)
10779   NODE_NAME_CASE(FCVT_W_RV64)
10780   NODE_NAME_CASE(FCVT_WU_RV64)
10781   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10782   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10783   NODE_NAME_CASE(READ_CYCLE_WIDE)
10784   NODE_NAME_CASE(GREV)
10785   NODE_NAME_CASE(GREVW)
10786   NODE_NAME_CASE(GORC)
10787   NODE_NAME_CASE(GORCW)
10788   NODE_NAME_CASE(SHFL)
10789   NODE_NAME_CASE(SHFLW)
10790   NODE_NAME_CASE(UNSHFL)
10791   NODE_NAME_CASE(UNSHFLW)
10792   NODE_NAME_CASE(BFP)
10793   NODE_NAME_CASE(BFPW)
10794   NODE_NAME_CASE(BCOMPRESS)
10795   NODE_NAME_CASE(BCOMPRESSW)
10796   NODE_NAME_CASE(BDECOMPRESS)
10797   NODE_NAME_CASE(BDECOMPRESSW)
10798   NODE_NAME_CASE(VMV_V_X_VL)
10799   NODE_NAME_CASE(VFMV_V_F_VL)
10800   NODE_NAME_CASE(VMV_X_S)
10801   NODE_NAME_CASE(VMV_S_X_VL)
10802   NODE_NAME_CASE(VFMV_S_F_VL)
10803   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10804   NODE_NAME_CASE(READ_VLENB)
10805   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10806   NODE_NAME_CASE(VSLIDEUP_VL)
10807   NODE_NAME_CASE(VSLIDE1UP_VL)
10808   NODE_NAME_CASE(VSLIDEDOWN_VL)
10809   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10810   NODE_NAME_CASE(VID_VL)
10811   NODE_NAME_CASE(VFNCVT_ROD_VL)
10812   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10813   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10814   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10815   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10816   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10817   NODE_NAME_CASE(VECREDUCE_AND_VL)
10818   NODE_NAME_CASE(VECREDUCE_OR_VL)
10819   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10820   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10821   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10822   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10823   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10824   NODE_NAME_CASE(ADD_VL)
10825   NODE_NAME_CASE(AND_VL)
10826   NODE_NAME_CASE(MUL_VL)
10827   NODE_NAME_CASE(OR_VL)
10828   NODE_NAME_CASE(SDIV_VL)
10829   NODE_NAME_CASE(SHL_VL)
10830   NODE_NAME_CASE(SREM_VL)
10831   NODE_NAME_CASE(SRA_VL)
10832   NODE_NAME_CASE(SRL_VL)
10833   NODE_NAME_CASE(SUB_VL)
10834   NODE_NAME_CASE(UDIV_VL)
10835   NODE_NAME_CASE(UREM_VL)
10836   NODE_NAME_CASE(XOR_VL)
10837   NODE_NAME_CASE(SADDSAT_VL)
10838   NODE_NAME_CASE(UADDSAT_VL)
10839   NODE_NAME_CASE(SSUBSAT_VL)
10840   NODE_NAME_CASE(USUBSAT_VL)
10841   NODE_NAME_CASE(FADD_VL)
10842   NODE_NAME_CASE(FSUB_VL)
10843   NODE_NAME_CASE(FMUL_VL)
10844   NODE_NAME_CASE(FDIV_VL)
10845   NODE_NAME_CASE(FNEG_VL)
10846   NODE_NAME_CASE(FABS_VL)
10847   NODE_NAME_CASE(FSQRT_VL)
10848   NODE_NAME_CASE(FMA_VL)
10849   NODE_NAME_CASE(FCOPYSIGN_VL)
10850   NODE_NAME_CASE(SMIN_VL)
10851   NODE_NAME_CASE(SMAX_VL)
10852   NODE_NAME_CASE(UMIN_VL)
10853   NODE_NAME_CASE(UMAX_VL)
10854   NODE_NAME_CASE(FMINNUM_VL)
10855   NODE_NAME_CASE(FMAXNUM_VL)
10856   NODE_NAME_CASE(MULHS_VL)
10857   NODE_NAME_CASE(MULHU_VL)
10858   NODE_NAME_CASE(FP_TO_SINT_VL)
10859   NODE_NAME_CASE(FP_TO_UINT_VL)
10860   NODE_NAME_CASE(SINT_TO_FP_VL)
10861   NODE_NAME_CASE(UINT_TO_FP_VL)
10862   NODE_NAME_CASE(FP_EXTEND_VL)
10863   NODE_NAME_CASE(FP_ROUND_VL)
10864   NODE_NAME_CASE(VWMUL_VL)
10865   NODE_NAME_CASE(VWMULU_VL)
10866   NODE_NAME_CASE(VWMULSU_VL)
10867   NODE_NAME_CASE(VWADD_VL)
10868   NODE_NAME_CASE(VWADDU_VL)
10869   NODE_NAME_CASE(VWSUB_VL)
10870   NODE_NAME_CASE(VWSUBU_VL)
10871   NODE_NAME_CASE(VWADD_W_VL)
10872   NODE_NAME_CASE(VWADDU_W_VL)
10873   NODE_NAME_CASE(VWSUB_W_VL)
10874   NODE_NAME_CASE(VWSUBU_W_VL)
10875   NODE_NAME_CASE(SETCC_VL)
10876   NODE_NAME_CASE(VSELECT_VL)
10877   NODE_NAME_CASE(VP_MERGE_VL)
10878   NODE_NAME_CASE(VMAND_VL)
10879   NODE_NAME_CASE(VMOR_VL)
10880   NODE_NAME_CASE(VMXOR_VL)
10881   NODE_NAME_CASE(VMCLR_VL)
10882   NODE_NAME_CASE(VMSET_VL)
10883   NODE_NAME_CASE(VRGATHER_VX_VL)
10884   NODE_NAME_CASE(VRGATHER_VV_VL)
10885   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
10886   NODE_NAME_CASE(VSEXT_VL)
10887   NODE_NAME_CASE(VZEXT_VL)
10888   NODE_NAME_CASE(VCPOP_VL)
10889   NODE_NAME_CASE(READ_CSR)
10890   NODE_NAME_CASE(WRITE_CSR)
10891   NODE_NAME_CASE(SWAP_CSR)
10892   }
10893   // clang-format on
10894   return nullptr;
10895 #undef NODE_NAME_CASE
10896 }
10897 
10898 /// getConstraintType - Given a constraint letter, return the type of
10899 /// constraint it is for this target.
10900 RISCVTargetLowering::ConstraintType
10901 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
10902   if (Constraint.size() == 1) {
10903     switch (Constraint[0]) {
10904     default:
10905       break;
10906     case 'f':
10907       return C_RegisterClass;
10908     case 'I':
10909     case 'J':
10910     case 'K':
10911       return C_Immediate;
10912     case 'A':
10913       return C_Memory;
10914     case 'S': // A symbolic address
10915       return C_Other;
10916     }
10917   } else {
10918     if (Constraint == "vr" || Constraint == "vm")
10919       return C_RegisterClass;
10920   }
10921   return TargetLowering::getConstraintType(Constraint);
10922 }
10923 
10924 std::pair<unsigned, const TargetRegisterClass *>
10925 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10926                                                   StringRef Constraint,
10927                                                   MVT VT) const {
10928   // First, see if this is a constraint that directly corresponds to a
10929   // RISCV register class.
10930   if (Constraint.size() == 1) {
10931     switch (Constraint[0]) {
10932     case 'r':
10933       // TODO: Support fixed vectors up to XLen for P extension?
10934       if (VT.isVector())
10935         break;
10936       return std::make_pair(0U, &RISCV::GPRRegClass);
10937     case 'f':
10938       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
10939         return std::make_pair(0U, &RISCV::FPR16RegClass);
10940       if (Subtarget.hasStdExtF() && VT == MVT::f32)
10941         return std::make_pair(0U, &RISCV::FPR32RegClass);
10942       if (Subtarget.hasStdExtD() && VT == MVT::f64)
10943         return std::make_pair(0U, &RISCV::FPR64RegClass);
10944       break;
10945     default:
10946       break;
10947     }
10948   } else if (Constraint == "vr") {
10949     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
10950                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10951       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
10952         return std::make_pair(0U, RC);
10953     }
10954   } else if (Constraint == "vm") {
10955     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
10956       return std::make_pair(0U, &RISCV::VMV0RegClass);
10957   }
10958 
10959   // Clang will correctly decode the usage of register name aliases into their
10960   // official names. However, other frontends like `rustc` do not. This allows
10961   // users of these frontends to use the ABI names for registers in LLVM-style
10962   // register constraints.
10963   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
10964                                .Case("{zero}", RISCV::X0)
10965                                .Case("{ra}", RISCV::X1)
10966                                .Case("{sp}", RISCV::X2)
10967                                .Case("{gp}", RISCV::X3)
10968                                .Case("{tp}", RISCV::X4)
10969                                .Case("{t0}", RISCV::X5)
10970                                .Case("{t1}", RISCV::X6)
10971                                .Case("{t2}", RISCV::X7)
10972                                .Cases("{s0}", "{fp}", RISCV::X8)
10973                                .Case("{s1}", RISCV::X9)
10974                                .Case("{a0}", RISCV::X10)
10975                                .Case("{a1}", RISCV::X11)
10976                                .Case("{a2}", RISCV::X12)
10977                                .Case("{a3}", RISCV::X13)
10978                                .Case("{a4}", RISCV::X14)
10979                                .Case("{a5}", RISCV::X15)
10980                                .Case("{a6}", RISCV::X16)
10981                                .Case("{a7}", RISCV::X17)
10982                                .Case("{s2}", RISCV::X18)
10983                                .Case("{s3}", RISCV::X19)
10984                                .Case("{s4}", RISCV::X20)
10985                                .Case("{s5}", RISCV::X21)
10986                                .Case("{s6}", RISCV::X22)
10987                                .Case("{s7}", RISCV::X23)
10988                                .Case("{s8}", RISCV::X24)
10989                                .Case("{s9}", RISCV::X25)
10990                                .Case("{s10}", RISCV::X26)
10991                                .Case("{s11}", RISCV::X27)
10992                                .Case("{t3}", RISCV::X28)
10993                                .Case("{t4}", RISCV::X29)
10994                                .Case("{t5}", RISCV::X30)
10995                                .Case("{t6}", RISCV::X31)
10996                                .Default(RISCV::NoRegister);
10997   if (XRegFromAlias != RISCV::NoRegister)
10998     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
10999 
11000   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11001   // TableGen record rather than the AsmName to choose registers for InlineAsm
11002   // constraints, plus we want to match those names to the widest floating point
11003   // register type available, manually select floating point registers here.
11004   //
11005   // The second case is the ABI name of the register, so that frontends can also
11006   // use the ABI names in register constraint lists.
11007   if (Subtarget.hasStdExtF()) {
11008     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11009                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11010                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11011                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11012                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11013                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11014                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11015                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11016                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11017                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11018                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11019                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11020                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11021                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11022                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11023                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11024                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11025                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11026                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11027                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11028                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11029                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11030                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11031                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11032                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11033                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11034                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11035                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11036                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11037                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11038                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11039                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11040                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11041                         .Default(RISCV::NoRegister);
11042     if (FReg != RISCV::NoRegister) {
11043       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11044       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11045         unsigned RegNo = FReg - RISCV::F0_F;
11046         unsigned DReg = RISCV::F0_D + RegNo;
11047         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11048       }
11049       if (VT == MVT::f32 || VT == MVT::Other)
11050         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11051       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11052         unsigned RegNo = FReg - RISCV::F0_F;
11053         unsigned HReg = RISCV::F0_H + RegNo;
11054         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11055       }
11056     }
11057   }
11058 
11059   if (Subtarget.hasVInstructions()) {
11060     Register VReg = StringSwitch<Register>(Constraint.lower())
11061                         .Case("{v0}", RISCV::V0)
11062                         .Case("{v1}", RISCV::V1)
11063                         .Case("{v2}", RISCV::V2)
11064                         .Case("{v3}", RISCV::V3)
11065                         .Case("{v4}", RISCV::V4)
11066                         .Case("{v5}", RISCV::V5)
11067                         .Case("{v6}", RISCV::V6)
11068                         .Case("{v7}", RISCV::V7)
11069                         .Case("{v8}", RISCV::V8)
11070                         .Case("{v9}", RISCV::V9)
11071                         .Case("{v10}", RISCV::V10)
11072                         .Case("{v11}", RISCV::V11)
11073                         .Case("{v12}", RISCV::V12)
11074                         .Case("{v13}", RISCV::V13)
11075                         .Case("{v14}", RISCV::V14)
11076                         .Case("{v15}", RISCV::V15)
11077                         .Case("{v16}", RISCV::V16)
11078                         .Case("{v17}", RISCV::V17)
11079                         .Case("{v18}", RISCV::V18)
11080                         .Case("{v19}", RISCV::V19)
11081                         .Case("{v20}", RISCV::V20)
11082                         .Case("{v21}", RISCV::V21)
11083                         .Case("{v22}", RISCV::V22)
11084                         .Case("{v23}", RISCV::V23)
11085                         .Case("{v24}", RISCV::V24)
11086                         .Case("{v25}", RISCV::V25)
11087                         .Case("{v26}", RISCV::V26)
11088                         .Case("{v27}", RISCV::V27)
11089                         .Case("{v28}", RISCV::V28)
11090                         .Case("{v29}", RISCV::V29)
11091                         .Case("{v30}", RISCV::V30)
11092                         .Case("{v31}", RISCV::V31)
11093                         .Default(RISCV::NoRegister);
11094     if (VReg != RISCV::NoRegister) {
11095       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11096         return std::make_pair(VReg, &RISCV::VMRegClass);
11097       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11098         return std::make_pair(VReg, &RISCV::VRRegClass);
11099       for (const auto *RC :
11100            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11101         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11102           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11103           return std::make_pair(VReg, RC);
11104         }
11105       }
11106     }
11107   }
11108 
11109   std::pair<Register, const TargetRegisterClass *> Res =
11110       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11111 
11112   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11113   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11114   // Subtarget into account.
11115   if (Res.second == &RISCV::GPRF16RegClass ||
11116       Res.second == &RISCV::GPRF32RegClass ||
11117       Res.second == &RISCV::GPRF64RegClass)
11118     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11119 
11120   return Res;
11121 }
11122 
11123 unsigned
11124 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11125   // Currently only support length 1 constraints.
11126   if (ConstraintCode.size() == 1) {
11127     switch (ConstraintCode[0]) {
11128     case 'A':
11129       return InlineAsm::Constraint_A;
11130     default:
11131       break;
11132     }
11133   }
11134 
11135   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11136 }
11137 
11138 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11139     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11140     SelectionDAG &DAG) const {
11141   // Currently only support length 1 constraints.
11142   if (Constraint.length() == 1) {
11143     switch (Constraint[0]) {
11144     case 'I':
11145       // Validate & create a 12-bit signed immediate operand.
11146       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11147         uint64_t CVal = C->getSExtValue();
11148         if (isInt<12>(CVal))
11149           Ops.push_back(
11150               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11151       }
11152       return;
11153     case 'J':
11154       // Validate & create an integer zero operand.
11155       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11156         if (C->getZExtValue() == 0)
11157           Ops.push_back(
11158               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11159       return;
11160     case 'K':
11161       // Validate & create a 5-bit unsigned immediate operand.
11162       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11163         uint64_t CVal = C->getZExtValue();
11164         if (isUInt<5>(CVal))
11165           Ops.push_back(
11166               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11167       }
11168       return;
11169     case 'S':
11170       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11171         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11172                                                  GA->getValueType(0)));
11173       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11174         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11175                                                 BA->getValueType(0)));
11176       }
11177       return;
11178     default:
11179       break;
11180     }
11181   }
11182   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11183 }
11184 
11185 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11186                                                    Instruction *Inst,
11187                                                    AtomicOrdering Ord) const {
11188   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11189     return Builder.CreateFence(Ord);
11190   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11191     return Builder.CreateFence(AtomicOrdering::Release);
11192   return nullptr;
11193 }
11194 
11195 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11196                                                     Instruction *Inst,
11197                                                     AtomicOrdering Ord) const {
11198   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11199     return Builder.CreateFence(AtomicOrdering::Acquire);
11200   return nullptr;
11201 }
11202 
11203 TargetLowering::AtomicExpansionKind
11204 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11205   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11206   // point operations can't be used in an lr/sc sequence without breaking the
11207   // forward-progress guarantee.
11208   if (AI->isFloatingPointOperation())
11209     return AtomicExpansionKind::CmpXChg;
11210 
11211   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11212   if (Size == 8 || Size == 16)
11213     return AtomicExpansionKind::MaskedIntrinsic;
11214   return AtomicExpansionKind::None;
11215 }
11216 
11217 static Intrinsic::ID
11218 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11219   if (XLen == 32) {
11220     switch (BinOp) {
11221     default:
11222       llvm_unreachable("Unexpected AtomicRMW BinOp");
11223     case AtomicRMWInst::Xchg:
11224       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11225     case AtomicRMWInst::Add:
11226       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11227     case AtomicRMWInst::Sub:
11228       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11229     case AtomicRMWInst::Nand:
11230       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11231     case AtomicRMWInst::Max:
11232       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11233     case AtomicRMWInst::Min:
11234       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11235     case AtomicRMWInst::UMax:
11236       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11237     case AtomicRMWInst::UMin:
11238       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11239     }
11240   }
11241 
11242   if (XLen == 64) {
11243     switch (BinOp) {
11244     default:
11245       llvm_unreachable("Unexpected AtomicRMW BinOp");
11246     case AtomicRMWInst::Xchg:
11247       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11248     case AtomicRMWInst::Add:
11249       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11250     case AtomicRMWInst::Sub:
11251       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11252     case AtomicRMWInst::Nand:
11253       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11254     case AtomicRMWInst::Max:
11255       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11256     case AtomicRMWInst::Min:
11257       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11258     case AtomicRMWInst::UMax:
11259       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11260     case AtomicRMWInst::UMin:
11261       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11262     }
11263   }
11264 
11265   llvm_unreachable("Unexpected XLen\n");
11266 }
11267 
11268 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11269     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11270     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11271   unsigned XLen = Subtarget.getXLen();
11272   Value *Ordering =
11273       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11274   Type *Tys[] = {AlignedAddr->getType()};
11275   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11276       AI->getModule(),
11277       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11278 
11279   if (XLen == 64) {
11280     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11281     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11282     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11283   }
11284 
11285   Value *Result;
11286 
11287   // Must pass the shift amount needed to sign extend the loaded value prior
11288   // to performing a signed comparison for min/max. ShiftAmt is the number of
11289   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11290   // is the number of bits to left+right shift the value in order to
11291   // sign-extend.
11292   if (AI->getOperation() == AtomicRMWInst::Min ||
11293       AI->getOperation() == AtomicRMWInst::Max) {
11294     const DataLayout &DL = AI->getModule()->getDataLayout();
11295     unsigned ValWidth =
11296         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11297     Value *SextShamt =
11298         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11299     Result = Builder.CreateCall(LrwOpScwLoop,
11300                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11301   } else {
11302     Result =
11303         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11304   }
11305 
11306   if (XLen == 64)
11307     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11308   return Result;
11309 }
11310 
11311 TargetLowering::AtomicExpansionKind
11312 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11313     AtomicCmpXchgInst *CI) const {
11314   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11315   if (Size == 8 || Size == 16)
11316     return AtomicExpansionKind::MaskedIntrinsic;
11317   return AtomicExpansionKind::None;
11318 }
11319 
11320 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11321     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11322     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11323   unsigned XLen = Subtarget.getXLen();
11324   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11325   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11326   if (XLen == 64) {
11327     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11328     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11329     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11330     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11331   }
11332   Type *Tys[] = {AlignedAddr->getType()};
11333   Function *MaskedCmpXchg =
11334       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11335   Value *Result = Builder.CreateCall(
11336       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11337   if (XLen == 64)
11338     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11339   return Result;
11340 }
11341 
11342 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
11343   return false;
11344 }
11345 
11346 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11347                                                EVT VT) const {
11348   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11349     return false;
11350 
11351   switch (FPVT.getSimpleVT().SimpleTy) {
11352   case MVT::f16:
11353     return Subtarget.hasStdExtZfh();
11354   case MVT::f32:
11355     return Subtarget.hasStdExtF();
11356   case MVT::f64:
11357     return Subtarget.hasStdExtD();
11358   default:
11359     return false;
11360   }
11361 }
11362 
11363 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11364   // If we are using the small code model, we can reduce size of jump table
11365   // entry to 4 bytes.
11366   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11367       getTargetMachine().getCodeModel() == CodeModel::Small) {
11368     return MachineJumpTableInfo::EK_Custom32;
11369   }
11370   return TargetLowering::getJumpTableEncoding();
11371 }
11372 
11373 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11374     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11375     unsigned uid, MCContext &Ctx) const {
11376   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11377          getTargetMachine().getCodeModel() == CodeModel::Small);
11378   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11379 }
11380 
11381 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11382                                                      EVT VT) const {
11383   VT = VT.getScalarType();
11384 
11385   if (!VT.isSimple())
11386     return false;
11387 
11388   switch (VT.getSimpleVT().SimpleTy) {
11389   case MVT::f16:
11390     return Subtarget.hasStdExtZfh();
11391   case MVT::f32:
11392     return Subtarget.hasStdExtF();
11393   case MVT::f64:
11394     return Subtarget.hasStdExtD();
11395   default:
11396     break;
11397   }
11398 
11399   return false;
11400 }
11401 
11402 Register RISCVTargetLowering::getExceptionPointerRegister(
11403     const Constant *PersonalityFn) const {
11404   return RISCV::X10;
11405 }
11406 
11407 Register RISCVTargetLowering::getExceptionSelectorRegister(
11408     const Constant *PersonalityFn) const {
11409   return RISCV::X11;
11410 }
11411 
11412 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11413   // Return false to suppress the unnecessary extensions if the LibCall
11414   // arguments or return value is f32 type for LP64 ABI.
11415   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11416   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11417     return false;
11418 
11419   return true;
11420 }
11421 
11422 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11423   if (Subtarget.is64Bit() && Type == MVT::i32)
11424     return true;
11425 
11426   return IsSigned;
11427 }
11428 
11429 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11430                                                  SDValue C) const {
11431   // Check integral scalar types.
11432   if (VT.isScalarInteger()) {
11433     // Omit the optimization if the sub target has the M extension and the data
11434     // size exceeds XLen.
11435     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11436       return false;
11437     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11438       // Break the MUL to a SLLI and an ADD/SUB.
11439       const APInt &Imm = ConstNode->getAPIntValue();
11440       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11441           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11442         return true;
11443       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11444       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11445           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11446            (Imm - 8).isPowerOf2()))
11447         return true;
11448       // Omit the following optimization if the sub target has the M extension
11449       // and the data size >= XLen.
11450       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11451         return false;
11452       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11453       // a pair of LUI/ADDI.
11454       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11455         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11456         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11457             (1 - ImmS).isPowerOf2())
11458         return true;
11459       }
11460     }
11461   }
11462 
11463   return false;
11464 }
11465 
11466 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
11467                                                       SDValue ConstNode) const {
11468   // Let the DAGCombiner decide for vectors.
11469   EVT VT = AddNode.getValueType();
11470   if (VT.isVector())
11471     return true;
11472 
11473   // Let the DAGCombiner decide for larger types.
11474   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11475     return true;
11476 
11477   // It is worse if c1 is simm12 while c1*c2 is not.
11478   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11479   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11480   const APInt &C1 = C1Node->getAPIntValue();
11481   const APInt &C2 = C2Node->getAPIntValue();
11482   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11483     return false;
11484 
11485   // Default to true and let the DAGCombiner decide.
11486   return true;
11487 }
11488 
11489 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11490     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11491     bool *Fast) const {
11492   if (!VT.isVector())
11493     return false;
11494 
11495   EVT ElemVT = VT.getVectorElementType();
11496   if (Alignment >= ElemVT.getStoreSize()) {
11497     if (Fast)
11498       *Fast = true;
11499     return true;
11500   }
11501 
11502   return false;
11503 }
11504 
11505 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11506     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11507     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11508   bool IsABIRegCopy = CC.hasValue();
11509   EVT ValueVT = Val.getValueType();
11510   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11511     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11512     // and cast to f32.
11513     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11514     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11515     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11516                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11517     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11518     Parts[0] = Val;
11519     return true;
11520   }
11521 
11522   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11523     LLVMContext &Context = *DAG.getContext();
11524     EVT ValueEltVT = ValueVT.getVectorElementType();
11525     EVT PartEltVT = PartVT.getVectorElementType();
11526     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11527     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11528     if (PartVTBitSize % ValueVTBitSize == 0) {
11529       assert(PartVTBitSize >= ValueVTBitSize);
11530       // If the element types are different, bitcast to the same element type of
11531       // PartVT first.
11532       // Give an example here, we want copy a <vscale x 1 x i8> value to
11533       // <vscale x 4 x i16>.
11534       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11535       // subvector, then we can bitcast to <vscale x 4 x i16>.
11536       if (ValueEltVT != PartEltVT) {
11537         if (PartVTBitSize > ValueVTBitSize) {
11538           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11539           assert(Count != 0 && "The number of element should not be zero.");
11540           EVT SameEltTypeVT =
11541               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11542           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11543                             DAG.getUNDEF(SameEltTypeVT), Val,
11544                             DAG.getVectorIdxConstant(0, DL));
11545         }
11546         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11547       } else {
11548         Val =
11549             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11550                         Val, DAG.getVectorIdxConstant(0, DL));
11551       }
11552       Parts[0] = Val;
11553       return true;
11554     }
11555   }
11556   return false;
11557 }
11558 
11559 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11560     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11561     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11562   bool IsABIRegCopy = CC.hasValue();
11563   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11564     SDValue Val = Parts[0];
11565 
11566     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11567     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11568     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11569     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11570     return Val;
11571   }
11572 
11573   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11574     LLVMContext &Context = *DAG.getContext();
11575     SDValue Val = Parts[0];
11576     EVT ValueEltVT = ValueVT.getVectorElementType();
11577     EVT PartEltVT = PartVT.getVectorElementType();
11578     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11579     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11580     if (PartVTBitSize % ValueVTBitSize == 0) {
11581       assert(PartVTBitSize >= ValueVTBitSize);
11582       EVT SameEltTypeVT = ValueVT;
11583       // If the element types are different, convert it to the same element type
11584       // of PartVT.
11585       // Give an example here, we want copy a <vscale x 1 x i8> value from
11586       // <vscale x 4 x i16>.
11587       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11588       // then we can extract <vscale x 1 x i8>.
11589       if (ValueEltVT != PartEltVT) {
11590         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11591         assert(Count != 0 && "The number of element should not be zero.");
11592         SameEltTypeVT =
11593             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11594         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11595       }
11596       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11597                         DAG.getVectorIdxConstant(0, DL));
11598       return Val;
11599     }
11600   }
11601   return SDValue();
11602 }
11603 
11604 SDValue
11605 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11606                                    SelectionDAG &DAG,
11607                                    SmallVectorImpl<SDNode *> &Created) const {
11608   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11609   if (isIntDivCheap(N->getValueType(0), Attr))
11610     return SDValue(N, 0); // Lower SDIV as SDIV
11611 
11612   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11613          "Unexpected divisor!");
11614 
11615   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11616   if (!Subtarget.hasStdExtZbt())
11617     return SDValue();
11618 
11619   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11620   // Besides, more critical path instructions will be generated when dividing
11621   // by 2. So we keep using the original DAGs for these cases.
11622   unsigned Lg2 = Divisor.countTrailingZeros();
11623   if (Lg2 == 1 || Lg2 >= 12)
11624     return SDValue();
11625 
11626   // fold (sdiv X, pow2)
11627   EVT VT = N->getValueType(0);
11628   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11629     return SDValue();
11630 
11631   SDLoc DL(N);
11632   SDValue N0 = N->getOperand(0);
11633   SDValue Zero = DAG.getConstant(0, DL, VT);
11634   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11635 
11636   // Add (N0 < 0) ? Pow2 - 1 : 0;
11637   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
11638   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11639   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11640 
11641   Created.push_back(Cmp.getNode());
11642   Created.push_back(Add.getNode());
11643   Created.push_back(Sel.getNode());
11644 
11645   // Divide by pow2.
11646   SDValue SRA =
11647       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11648 
11649   // If we're dividing by a positive value, we're done.  Otherwise, we must
11650   // negate the result.
11651   if (Divisor.isNonNegative())
11652     return SRA;
11653 
11654   Created.push_back(SRA.getNode());
11655   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11656 }
11657 
11658 #define GET_REGISTER_MATCHER
11659 #include "RISCVGenAsmMatcher.inc"
11660 
11661 Register
11662 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11663                                        const MachineFunction &MF) const {
11664   Register Reg = MatchRegisterAltName(RegName);
11665   if (Reg == RISCV::NoRegister)
11666     Reg = MatchRegisterName(RegName);
11667   if (Reg == RISCV::NoRegister)
11668     report_fatal_error(
11669         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11670   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11671   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11672     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11673                              StringRef(RegName) + "\"."));
11674   return Reg;
11675 }
11676 
11677 namespace llvm {
11678 namespace RISCVVIntrinsicsTable {
11679 
11680 #define GET_RISCVVIntrinsicsTable_IMPL
11681 #include "RISCVGenSearchableTables.inc"
11682 
11683 } // namespace RISCVVIntrinsicsTable
11684 
11685 } // namespace llvm
11686