xref: /freebsd/contrib/llvm-project/llvm/lib/Target/RISCV/RISCVISelLowering.cpp (revision e6bfd18d21b225af6a0ed67ceeaf1293b7b9eba5)
1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/DiagnosticPrinter.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/IntrinsicsRISCV.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/KnownBits.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "riscv-lower"
45 
46 STATISTIC(NumTailCalls, "Number of tail calls");
47 
48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
49                                          const RISCVSubtarget &STI)
50     : TargetLowering(TM), Subtarget(STI) {
51 
52   if (Subtarget.isRV32E())
53     report_fatal_error("Codegen not yet implemented for RV32E");
54 
55   RISCVABI::ABI ABI = Subtarget.getTargetABI();
56   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
57 
58   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
59       !Subtarget.hasStdExtF()) {
60     errs() << "Hard-float 'f' ABI can't be used for a target that "
61                 "doesn't support the F instruction set extension (ignoring "
62                           "target-abi)\n";
63     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
64   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
65              !Subtarget.hasStdExtD()) {
66     errs() << "Hard-float 'd' ABI can't be used for a target that "
67               "doesn't support the D instruction set extension (ignoring "
68               "target-abi)\n";
69     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
70   }
71 
72   switch (ABI) {
73   default:
74     report_fatal_error("Don't know how to lower this ABI");
75   case RISCVABI::ABI_ILP32:
76   case RISCVABI::ABI_ILP32F:
77   case RISCVABI::ABI_ILP32D:
78   case RISCVABI::ABI_LP64:
79   case RISCVABI::ABI_LP64F:
80   case RISCVABI::ABI_LP64D:
81     break;
82   }
83 
84   MVT XLenVT = Subtarget.getXLenVT();
85 
86   // Set up the register classes.
87   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
88 
89   if (Subtarget.hasStdExtZfh())
90     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
91   if (Subtarget.hasStdExtF())
92     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
93   if (Subtarget.hasStdExtD())
94     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
95 
96   static const MVT::SimpleValueType BoolVecVTs[] = {
97       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
98       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
99   static const MVT::SimpleValueType IntVecVTs[] = {
100       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
101       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
102       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
103       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
104       MVT::nxv4i64, MVT::nxv8i64};
105   static const MVT::SimpleValueType F16VecVTs[] = {
106       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
107       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
108   static const MVT::SimpleValueType F32VecVTs[] = {
109       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
110   static const MVT::SimpleValueType F64VecVTs[] = {
111       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
112 
113   if (Subtarget.hasVInstructions()) {
114     auto addRegClassForRVV = [this](MVT VT) {
115       // Disable the smallest fractional LMUL types if ELEN is less than
116       // RVVBitsPerBlock.
117       unsigned MinElts = RISCV::RVVBitsPerBlock / Subtarget.getELEN();
118       if (VT.getVectorMinNumElements() < MinElts)
119         return;
120 
121       unsigned Size = VT.getSizeInBits().getKnownMinValue();
122       const TargetRegisterClass *RC;
123       if (Size <= RISCV::RVVBitsPerBlock)
124         RC = &RISCV::VRRegClass;
125       else if (Size == 2 * RISCV::RVVBitsPerBlock)
126         RC = &RISCV::VRM2RegClass;
127       else if (Size == 4 * RISCV::RVVBitsPerBlock)
128         RC = &RISCV::VRM4RegClass;
129       else if (Size == 8 * RISCV::RVVBitsPerBlock)
130         RC = &RISCV::VRM8RegClass;
131       else
132         llvm_unreachable("Unexpected size");
133 
134       addRegisterClass(VT, RC);
135     };
136 
137     for (MVT VT : BoolVecVTs)
138       addRegClassForRVV(VT);
139     for (MVT VT : IntVecVTs) {
140       if (VT.getVectorElementType() == MVT::i64 &&
141           !Subtarget.hasVInstructionsI64())
142         continue;
143       addRegClassForRVV(VT);
144     }
145 
146     if (Subtarget.hasVInstructionsF16())
147       for (MVT VT : F16VecVTs)
148         addRegClassForRVV(VT);
149 
150     if (Subtarget.hasVInstructionsF32())
151       for (MVT VT : F32VecVTs)
152         addRegClassForRVV(VT);
153 
154     if (Subtarget.hasVInstructionsF64())
155       for (MVT VT : F64VecVTs)
156         addRegClassForRVV(VT);
157 
158     if (Subtarget.useRVVForFixedLengthVectors()) {
159       auto addRegClassForFixedVectors = [this](MVT VT) {
160         MVT ContainerVT = getContainerForFixedLengthVector(VT);
161         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
162         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
163         addRegisterClass(VT, TRI.getRegClass(RCID));
164       };
165       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
166         if (useRVVForFixedLengthVectorVT(VT))
167           addRegClassForFixedVectors(VT);
168 
169       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
170         if (useRVVForFixedLengthVectorVT(VT))
171           addRegClassForFixedVectors(VT);
172     }
173   }
174 
175   // Compute derived properties from the register classes.
176   computeRegisterProperties(STI.getRegisterInfo());
177 
178   setStackPointerRegisterToSaveRestore(RISCV::X2);
179 
180   setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, XLenVT,
181                    MVT::i1, Promote);
182 
183   // TODO: add all necessary setOperationAction calls.
184   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
185 
186   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
187   setOperationAction(ISD::BR_CC, XLenVT, Expand);
188   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
189   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
190 
191   setOperationAction({ISD::STACKSAVE, ISD::STACKRESTORE}, MVT::Other, Expand);
192 
193   setOperationAction(ISD::VASTART, MVT::Other, Custom);
194   setOperationAction({ISD::VAARG, ISD::VACOPY, ISD::VAEND}, MVT::Other, Expand);
195 
196   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
197 
198   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
199 
200   if (!Subtarget.hasStdExtZbb())
201     setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand);
202 
203   if (Subtarget.is64Bit()) {
204     setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
205 
206     setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL},
207                        MVT::i32, Custom);
208 
209     setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT},
210                        MVT::i32, Custom);
211   } else {
212     setLibcallName(
213         {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128},
214         nullptr);
215     setLibcallName(RTLIB::MULO_I64, nullptr);
216   }
217 
218   if (!Subtarget.hasStdExtM() && !Subtarget.hasStdExtZmmul()) {
219     setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU}, XLenVT, Expand);
220   } else {
221     if (Subtarget.is64Bit()) {
222       setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom);
223     } else {
224       setOperationAction(ISD::MUL, MVT::i64, Custom);
225     }
226   }
227 
228   if (!Subtarget.hasStdExtM()) {
229     setOperationAction({ISD::SDIV, ISD::UDIV, ISD::SREM, ISD::UREM},
230                        XLenVT, Expand);
231   } else {
232     if (Subtarget.is64Bit()) {
233       setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM},
234                           {MVT::i8, MVT::i16, MVT::i32}, Custom);
235     }
236   }
237 
238   setOperationAction(
239       {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT,
240       Expand);
241 
242   setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT,
243                      Custom);
244 
245   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
246       Subtarget.hasStdExtZbkb()) {
247     if (Subtarget.is64Bit())
248       setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom);
249   } else {
250     setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand);
251   }
252 
253   if (Subtarget.hasStdExtZbp()) {
254     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
255     // more combining.
256     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom);
257 
258     // BSWAP i8 doesn't exist.
259     setOperationAction(ISD::BITREVERSE, MVT::i8, Custom);
260 
261     setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom);
262 
263     if (Subtarget.is64Bit())
264       setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom);
265   } else {
266     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
267     // pattern match it directly in isel.
268     setOperationAction(ISD::BSWAP, XLenVT,
269                        (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
270                            ? Legal
271                            : Expand);
272     // Zbkb can use rev8+brev8 to implement bitreverse.
273     setOperationAction(ISD::BITREVERSE, XLenVT,
274                        Subtarget.hasStdExtZbkb() ? Custom : Expand);
275   }
276 
277   if (Subtarget.hasStdExtZbb()) {
278     setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT,
279                        Legal);
280 
281     if (Subtarget.is64Bit())
282       setOperationAction(
283           {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF},
284           MVT::i32, Custom);
285   } else {
286     setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand);
287 
288     if (Subtarget.is64Bit())
289       setOperationAction(ISD::ABS, MVT::i32, Custom);
290   }
291 
292   if (Subtarget.hasStdExtZbt()) {
293     setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom);
294     setOperationAction(ISD::SELECT, XLenVT, Legal);
295 
296     if (Subtarget.is64Bit())
297       setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom);
298   } else {
299     setOperationAction(ISD::SELECT, XLenVT, Custom);
300   }
301 
302   static const unsigned FPLegalNodeTypes[] = {
303       ISD::FMINNUM,        ISD::FMAXNUM,       ISD::LRINT,
304       ISD::LLRINT,         ISD::LROUND,        ISD::LLROUND,
305       ISD::STRICT_LRINT,   ISD::STRICT_LLRINT, ISD::STRICT_LROUND,
306       ISD::STRICT_LLROUND, ISD::STRICT_FMA,    ISD::STRICT_FADD,
307       ISD::STRICT_FSUB,    ISD::STRICT_FMUL,   ISD::STRICT_FDIV,
308       ISD::STRICT_FSQRT,   ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS};
309 
310   static const ISD::CondCode FPCCToExpand[] = {
311       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
312       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
313       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
314 
315   static const unsigned FPOpToExpand[] = {
316       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
317       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
318 
319   if (Subtarget.hasStdExtZfh())
320     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
321 
322   if (Subtarget.hasStdExtZfh()) {
323     setOperationAction(FPLegalNodeTypes, MVT::f16, Legal);
324     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
325     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
326     setCondCodeAction(FPCCToExpand, MVT::f16, Expand);
327     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
328     setOperationAction(ISD::SELECT, MVT::f16, Custom);
329     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
330 
331     setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT,
332                         ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC,
333                         ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN,
334                         ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG,
335                         ISD::FLOG2, ISD::FLOG10},
336                        MVT::f16, Promote);
337 
338     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
339     // complete support for all operations in LegalizeDAG.
340 
341     // We need to custom promote this.
342     if (Subtarget.is64Bit())
343       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
344   }
345 
346   if (Subtarget.hasStdExtF()) {
347     setOperationAction(FPLegalNodeTypes, MVT::f32, Legal);
348     setCondCodeAction(FPCCToExpand, MVT::f32, Expand);
349     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
350     setOperationAction(ISD::SELECT, MVT::f32, Custom);
351     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
352     setOperationAction(FPOpToExpand, MVT::f32, Expand);
353     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
354     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
355   }
356 
357   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
358     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
359 
360   if (Subtarget.hasStdExtD()) {
361     setOperationAction(FPLegalNodeTypes, MVT::f64, Legal);
362     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
363     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
364     setCondCodeAction(FPCCToExpand, MVT::f64, Expand);
365     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
366     setOperationAction(ISD::SELECT, MVT::f64, Custom);
367     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
368     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
369     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
370     setOperationAction(FPOpToExpand, MVT::f64, Expand);
371     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
372     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
373   }
374 
375   if (Subtarget.is64Bit())
376     setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT,
377                         ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT},
378                        MVT::i32, Custom);
379 
380   if (Subtarget.hasStdExtF()) {
381     setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT,
382                        Custom);
383 
384     setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT,
385                         ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP},
386                        XLenVT, Legal);
387 
388     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
389     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
390   }
391 
392   setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool,
393                       ISD::JumpTable},
394                      XLenVT, Custom);
395 
396   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
397 
398   if (Subtarget.is64Bit())
399     setOperationAction(ISD::Constant, MVT::i64, Custom);
400 
401   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
402   // Unfortunately this can't be determined just from the ISA naming string.
403   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
404                      Subtarget.is64Bit() ? Legal : Custom);
405 
406   setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal);
407   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
408   if (Subtarget.is64Bit())
409     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
410 
411   if (Subtarget.hasStdExtA()) {
412     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
413     setMinCmpXchgSizeInBits(32);
414   } else {
415     setMaxAtomicSizeInBitsSupported(0);
416   }
417 
418   setBooleanContents(ZeroOrOneBooleanContent);
419 
420   if (Subtarget.hasVInstructions()) {
421     setBooleanVectorContents(ZeroOrOneBooleanContent);
422 
423     setOperationAction(ISD::VSCALE, XLenVT, Custom);
424 
425     // RVV intrinsics may have illegal operands.
426     // We also need to custom legalize vmv.x.s.
427     setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
428                        {MVT::i8, MVT::i16}, Custom);
429     if (Subtarget.is64Bit())
430       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
431     else
432       setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
433                          MVT::i64, Custom);
434 
435     setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID},
436                        MVT::Other, Custom);
437 
438     static const unsigned IntegerVPOps[] = {
439         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
440         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
441         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
442         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
443         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
444         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
445         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
446         ISD::VP_MERGE,       ISD::VP_SELECT,      ISD::VP_FPTOSI,
447         ISD::VP_FPTOUI,      ISD::VP_SETCC,       ISD::VP_SIGN_EXTEND,
448         ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE};
449 
450     static const unsigned FloatingPointVPOps[] = {
451         ISD::VP_FADD,        ISD::VP_FSUB,
452         ISD::VP_FMUL,        ISD::VP_FDIV,
453         ISD::VP_FNEG,        ISD::VP_FMA,
454         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
455         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX,
456         ISD::VP_MERGE,       ISD::VP_SELECT,
457         ISD::VP_SITOFP,      ISD::VP_UITOFP,
458         ISD::VP_SETCC,       ISD::VP_FP_ROUND,
459         ISD::VP_FP_EXTEND};
460 
461     static const unsigned IntegerVecReduceOps[] = {
462         ISD::VECREDUCE_ADD,  ISD::VECREDUCE_AND,  ISD::VECREDUCE_OR,
463         ISD::VECREDUCE_XOR,  ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
464         ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN};
465 
466     static const unsigned FloatingPointVecReduceOps[] = {
467         ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, ISD::VECREDUCE_FMIN,
468         ISD::VECREDUCE_FMAX};
469 
470     if (!Subtarget.is64Bit()) {
471       // We must custom-lower certain vXi64 operations on RV32 due to the vector
472       // element type being illegal.
473       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
474                          MVT::i64, Custom);
475 
476       setOperationAction(IntegerVecReduceOps, MVT::i64, Custom);
477 
478       setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND,
479                           ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR,
480                           ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN,
481                           ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN},
482                          MVT::i64, Custom);
483     }
484 
485     for (MVT VT : BoolVecVTs) {
486       if (!isTypeLegal(VT))
487         continue;
488 
489       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
490 
491       // Mask VTs are custom-expanded into a series of standard nodes
492       setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS,
493                           ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
494                          VT, Custom);
495 
496       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
497                          Custom);
498 
499       setOperationAction(ISD::SELECT, VT, Custom);
500       setOperationAction(
501           {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT,
502           Expand);
503 
504       setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom);
505 
506       setOperationAction(
507           {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
508           Custom);
509 
510       setOperationAction(
511           {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
512           Custom);
513 
514       // RVV has native int->float & float->int conversions where the
515       // element type sizes are within one power-of-two of each other. Any
516       // wider distances between type sizes have to be lowered as sequences
517       // which progressively narrow the gap in stages.
518       setOperationAction(
519           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
520           VT, Custom);
521 
522       // Expand all extending loads to types larger than this, and truncating
523       // stores from types larger than this.
524       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
525         setTruncStoreAction(OtherVT, VT, Expand);
526         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
527                          VT, Expand);
528       }
529 
530       setOperationAction(
531           {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT,
532           Custom);
533       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
534 
535       setOperationPromotedToType(
536           ISD::VECTOR_SPLICE, VT,
537           MVT::getVectorVT(MVT::i8, VT.getVectorElementCount()));
538     }
539 
540     for (MVT VT : IntVecVTs) {
541       if (!isTypeLegal(VT))
542         continue;
543 
544       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
545       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
546 
547       // Vectors implement MULHS/MULHU.
548       setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand);
549 
550       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
551       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV())
552         setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand);
553 
554       setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT,
555                          Legal);
556 
557       setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand);
558 
559       setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT,
560                          Expand);
561 
562       setOperationAction(ISD::BSWAP, VT, Expand);
563 
564       // Custom-lower extensions and truncations from/to mask types.
565       setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND},
566                          VT, Custom);
567 
568       // RVV has native int->float & float->int conversions where the
569       // element type sizes are within one power-of-two of each other. Any
570       // wider distances between type sizes have to be lowered as sequences
571       // which progressively narrow the gap in stages.
572       setOperationAction(
573           {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
574           VT, Custom);
575 
576       setOperationAction(
577           {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal);
578 
579       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
580       // nodes which truncate by one power of two at a time.
581       setOperationAction(ISD::TRUNCATE, VT, Custom);
582 
583       // Custom-lower insert/extract operations to simplify patterns.
584       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
585                          Custom);
586 
587       // Custom-lower reduction operations to set up the corresponding custom
588       // nodes' operands.
589       setOperationAction(IntegerVecReduceOps, VT, Custom);
590 
591       setOperationAction(IntegerVPOps, VT, Custom);
592 
593       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
594 
595       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
596                          VT, Custom);
597 
598       setOperationAction(
599           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
600           Custom);
601 
602       setOperationAction(
603           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
604           VT, Custom);
605 
606       setOperationAction(ISD::SELECT, VT, Custom);
607       setOperationAction(ISD::SELECT_CC, VT, Expand);
608 
609       setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom);
610 
611       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
612         setTruncStoreAction(VT, OtherVT, Expand);
613         setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
614                          VT, Expand);
615       }
616 
617       // Splice
618       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
619 
620       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
621       // type that can represent the value exactly.
622       if (VT.getVectorElementType() != MVT::i64) {
623         MVT FloatEltVT =
624             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
625         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
626         if (isTypeLegal(FloatVT)) {
627           setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
628                              Custom);
629         }
630       }
631     }
632 
633     // Expand various CCs to best match the RVV ISA, which natively supports UNE
634     // but no other unordered comparisons, and supports all ordered comparisons
635     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
636     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
637     // and we pattern-match those back to the "original", swapping operands once
638     // more. This way we catch both operations and both "vf" and "fv" forms with
639     // fewer patterns.
640     static const ISD::CondCode VFPCCToExpand[] = {
641         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
642         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
643         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
644     };
645 
646     // Sets common operation actions on RVV floating-point vector types.
647     const auto SetCommonVFPActions = [&](MVT VT) {
648       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
649       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
650       // sizes are within one power-of-two of each other. Therefore conversions
651       // between vXf16 and vXf64 must be lowered as sequences which convert via
652       // vXf32.
653       setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
654       // Custom-lower insert/extract operations to simplify patterns.
655       setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
656                          Custom);
657       // Expand various condition codes (explained above).
658       setCondCodeAction(VFPCCToExpand, VT, Expand);
659 
660       setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal);
661 
662       setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
663                          VT, Custom);
664 
665       setOperationAction(FloatingPointVecReduceOps, VT, Custom);
666 
667       // Expand FP operations that need libcalls.
668       setOperationAction(ISD::FREM, VT, Expand);
669       setOperationAction(ISD::FPOW, VT, Expand);
670       setOperationAction(ISD::FCOS, VT, Expand);
671       setOperationAction(ISD::FSIN, VT, Expand);
672       setOperationAction(ISD::FSINCOS, VT, Expand);
673       setOperationAction(ISD::FEXP, VT, Expand);
674       setOperationAction(ISD::FEXP2, VT, Expand);
675       setOperationAction(ISD::FLOG, VT, Expand);
676       setOperationAction(ISD::FLOG2, VT, Expand);
677       setOperationAction(ISD::FLOG10, VT, Expand);
678       setOperationAction(ISD::FRINT, VT, Expand);
679       setOperationAction(ISD::FNEARBYINT, VT, Expand);
680 
681       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
682       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
683       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
684       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
685 
686       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
687 
688       setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
689 
690       setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
691                          VT, Custom);
692 
693       setOperationAction(
694           {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
695           Custom);
696 
697       setOperationAction(ISD::SELECT, VT, Custom);
698       setOperationAction(ISD::SELECT_CC, VT, Expand);
699 
700       setOperationAction(
701           {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
702           VT, Custom);
703 
704       setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom);
705 
706       setOperationAction(FloatingPointVPOps, VT, Custom);
707     };
708 
709     // Sets common extload/truncstore actions on RVV floating-point vector
710     // types.
711     const auto SetCommonVFPExtLoadTruncStoreActions =
712         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
713           for (auto SmallVT : SmallerVTs) {
714             setTruncStoreAction(VT, SmallVT, Expand);
715             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
716           }
717         };
718 
719     if (Subtarget.hasVInstructionsF16()) {
720       for (MVT VT : F16VecVTs) {
721         if (!isTypeLegal(VT))
722           continue;
723         SetCommonVFPActions(VT);
724       }
725     }
726 
727     if (Subtarget.hasVInstructionsF32()) {
728       for (MVT VT : F32VecVTs) {
729         if (!isTypeLegal(VT))
730           continue;
731         SetCommonVFPActions(VT);
732         SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
733       }
734     }
735 
736     if (Subtarget.hasVInstructionsF64()) {
737       for (MVT VT : F64VecVTs) {
738         if (!isTypeLegal(VT))
739           continue;
740         SetCommonVFPActions(VT);
741         SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
742         SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
743       }
744     }
745 
746     if (Subtarget.useRVVForFixedLengthVectors()) {
747       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
748         if (!useRVVForFixedLengthVectorVT(VT))
749           continue;
750 
751         // By default everything must be expanded.
752         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
753           setOperationAction(Op, VT, Expand);
754         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
755           setTruncStoreAction(VT, OtherVT, Expand);
756           setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD},
757                            OtherVT, VT, Expand);
758         }
759 
760         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
761         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
762                            Custom);
763 
764         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT,
765                            Custom);
766 
767         setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
768                            VT, Custom);
769 
770         setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
771 
772         setOperationAction(ISD::SETCC, VT, Custom);
773 
774         setOperationAction(ISD::SELECT, VT, Custom);
775 
776         setOperationAction(ISD::TRUNCATE, VT, Custom);
777 
778         setOperationAction(ISD::BITCAST, VT, Custom);
779 
780         setOperationAction(
781             {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
782             Custom);
783 
784         setOperationAction(
785             {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
786             Custom);
787 
788         setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT,
789                             ISD::FP_TO_UINT},
790                            VT, Custom);
791 
792         // Operations below are different for between masks and other vectors.
793         if (VT.getVectorElementType() == MVT::i1) {
794           setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND,
795                               ISD::OR, ISD::XOR},
796                              VT, Custom);
797 
798           setOperationAction(
799               {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE},
800               VT, Custom);
801           continue;
802         }
803 
804         // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
805         // it before type legalization for i64 vectors on RV32. It will then be
806         // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
807         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
808         // improvements first.
809         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
810           setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
811           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
812         }
813 
814         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
815         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
816 
817         setOperationAction(
818             {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom);
819 
820         setOperationAction(
821             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
822             Custom);
823 
824         setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR,
825                             ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV,
826                             ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL},
827                            VT, Custom);
828 
829         setOperationAction(
830             {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom);
831 
832         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
833         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV())
834           setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom);
835 
836         setOperationAction(
837             {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT,
838             Custom);
839 
840         setOperationAction(ISD::VSELECT, VT, Custom);
841         setOperationAction(ISD::SELECT_CC, VT, Expand);
842 
843         setOperationAction(
844             {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom);
845 
846         // Custom-lower reduction operations to set up the corresponding custom
847         // nodes' operands.
848         setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX,
849                             ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX,
850                             ISD::VECREDUCE_UMIN},
851                            VT, Custom);
852 
853         setOperationAction(IntegerVPOps, VT, Custom);
854 
855         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
856         // type that can represent the value exactly.
857         if (VT.getVectorElementType() != MVT::i64) {
858           MVT FloatEltVT =
859               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
860           EVT FloatVT =
861               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
862           if (isTypeLegal(FloatVT))
863             setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
864                                Custom);
865         }
866       }
867 
868       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
869         if (!useRVVForFixedLengthVectorVT(VT))
870           continue;
871 
872         // By default everything must be expanded.
873         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
874           setOperationAction(Op, VT, Expand);
875         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
876           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
877           setTruncStoreAction(VT, OtherVT, Expand);
878         }
879 
880         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
881         setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
882                            Custom);
883 
884         setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS,
885                             ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT,
886                             ISD::EXTRACT_VECTOR_ELT},
887                            VT, Custom);
888 
889         setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE,
890                             ISD::MGATHER, ISD::MSCATTER},
891                            VT, Custom);
892 
893         setOperationAction(
894             {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT,
895             Custom);
896 
897         setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV,
898                             ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT,
899                             ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM},
900                            VT, Custom);
901 
902         setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
903 
904         setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND},
905                            VT, Custom);
906 
907         setCondCodeAction(VFPCCToExpand, VT, Expand);
908 
909         setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom);
910         setOperationAction(ISD::SELECT_CC, VT, Expand);
911 
912         setOperationAction(ISD::BITCAST, VT, Custom);
913 
914         setOperationAction(FloatingPointVecReduceOps, VT, Custom);
915 
916         setOperationAction(FloatingPointVPOps, VT, Custom);
917       }
918 
919       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
920       setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64},
921                          Custom);
922       if (Subtarget.hasStdExtZfh())
923         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
924       if (Subtarget.hasStdExtF())
925         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
926       if (Subtarget.hasStdExtD())
927         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
928     }
929   }
930 
931   // Function alignments.
932   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
933   setMinFunctionAlignment(FunctionAlignment);
934   setPrefFunctionAlignment(FunctionAlignment);
935 
936   setMinimumJumpTableEntries(5);
937 
938   // Jumps are expensive, compared to logic
939   setJumpIsExpensive();
940 
941   setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND,
942                        ISD::OR, ISD::XOR, ISD::SETCC});
943   if (Subtarget.is64Bit())
944     setTargetDAGCombine(ISD::SRA);
945 
946   if (Subtarget.hasStdExtF())
947     setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM});
948 
949   if (Subtarget.hasStdExtZbp())
950     setTargetDAGCombine({ISD::ROTL, ISD::ROTR});
951 
952   if (Subtarget.hasStdExtZbb())
953     setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN});
954 
955   if (Subtarget.hasStdExtZbkb())
956     setTargetDAGCombine(ISD::BITREVERSE);
957   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
958     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
959   if (Subtarget.hasStdExtF())
960     setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
961                          ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT});
962   if (Subtarget.hasVInstructions())
963     setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER,
964                          ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL,
965                          ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR});
966   if (Subtarget.useRVVForFixedLengthVectors())
967     setTargetDAGCombine(ISD::BITCAST);
968 
969   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
970   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
971 }
972 
973 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
974                                             LLVMContext &Context,
975                                             EVT VT) const {
976   if (!VT.isVector())
977     return getPointerTy(DL);
978   if (Subtarget.hasVInstructions() &&
979       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
980     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
981   return VT.changeVectorElementTypeToInteger();
982 }
983 
984 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
985   return Subtarget.getXLenVT();
986 }
987 
988 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
989                                              const CallInst &I,
990                                              MachineFunction &MF,
991                                              unsigned Intrinsic) const {
992   auto &DL = I.getModule()->getDataLayout();
993   switch (Intrinsic) {
994   default:
995     return false;
996   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
997   case Intrinsic::riscv_masked_atomicrmw_add_i32:
998   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
999   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1000   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1001   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1002   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1003   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1004   case Intrinsic::riscv_masked_cmpxchg_i32:
1005     Info.opc = ISD::INTRINSIC_W_CHAIN;
1006     Info.memVT = MVT::i32;
1007     Info.ptrVal = I.getArgOperand(0);
1008     Info.offset = 0;
1009     Info.align = Align(4);
1010     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1011                  MachineMemOperand::MOVolatile;
1012     return true;
1013   case Intrinsic::riscv_masked_strided_load:
1014     Info.opc = ISD::INTRINSIC_W_CHAIN;
1015     Info.ptrVal = I.getArgOperand(1);
1016     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1017     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1018     Info.size = MemoryLocation::UnknownSize;
1019     Info.flags |= MachineMemOperand::MOLoad;
1020     return true;
1021   case Intrinsic::riscv_masked_strided_store:
1022     Info.opc = ISD::INTRINSIC_VOID;
1023     Info.ptrVal = I.getArgOperand(1);
1024     Info.memVT =
1025         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1026     Info.align = Align(
1027         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1028         8);
1029     Info.size = MemoryLocation::UnknownSize;
1030     Info.flags |= MachineMemOperand::MOStore;
1031     return true;
1032   case Intrinsic::riscv_seg2_load:
1033   case Intrinsic::riscv_seg3_load:
1034   case Intrinsic::riscv_seg4_load:
1035   case Intrinsic::riscv_seg5_load:
1036   case Intrinsic::riscv_seg6_load:
1037   case Intrinsic::riscv_seg7_load:
1038   case Intrinsic::riscv_seg8_load:
1039     Info.opc = ISD::INTRINSIC_W_CHAIN;
1040     Info.ptrVal = I.getArgOperand(0);
1041     Info.memVT =
1042         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
1043     Info.align =
1044         Align(DL.getTypeSizeInBits(
1045                   I.getType()->getStructElementType(0)->getScalarType()) /
1046               8);
1047     Info.size = MemoryLocation::UnknownSize;
1048     Info.flags |= MachineMemOperand::MOLoad;
1049     return true;
1050   }
1051 }
1052 
1053 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1054                                                 const AddrMode &AM, Type *Ty,
1055                                                 unsigned AS,
1056                                                 Instruction *I) const {
1057   // No global is ever allowed as a base.
1058   if (AM.BaseGV)
1059     return false;
1060 
1061   // RVV instructions only support register addressing.
1062   if (Subtarget.hasVInstructions() && isa<VectorType>(Ty))
1063     return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs;
1064 
1065   // Require a 12-bit signed offset.
1066   if (!isInt<12>(AM.BaseOffs))
1067     return false;
1068 
1069   switch (AM.Scale) {
1070   case 0: // "r+i" or just "i", depending on HasBaseReg.
1071     break;
1072   case 1:
1073     if (!AM.HasBaseReg) // allow "r+i".
1074       break;
1075     return false; // disallow "r+r" or "r+r+i".
1076   default:
1077     return false;
1078   }
1079 
1080   return true;
1081 }
1082 
1083 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1084   return isInt<12>(Imm);
1085 }
1086 
1087 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1088   return isInt<12>(Imm);
1089 }
1090 
1091 // On RV32, 64-bit integers are split into their high and low parts and held
1092 // in two different registers, so the trunc is free since the low register can
1093 // just be used.
1094 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1095   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1096     return false;
1097   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1098   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1099   return (SrcBits == 64 && DestBits == 32);
1100 }
1101 
1102 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1103   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1104       !SrcVT.isInteger() || !DstVT.isInteger())
1105     return false;
1106   unsigned SrcBits = SrcVT.getSizeInBits();
1107   unsigned DestBits = DstVT.getSizeInBits();
1108   return (SrcBits == 64 && DestBits == 32);
1109 }
1110 
1111 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1112   // Zexts are free if they can be combined with a load.
1113   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1114   // poorly with type legalization of compares preferring sext.
1115   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1116     EVT MemVT = LD->getMemoryVT();
1117     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1118         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1119          LD->getExtensionType() == ISD::ZEXTLOAD))
1120       return true;
1121   }
1122 
1123   return TargetLowering::isZExtFree(Val, VT2);
1124 }
1125 
1126 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1127   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1128 }
1129 
1130 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const {
1131   return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
1132 }
1133 
1134 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1135   return Subtarget.hasStdExtZbb();
1136 }
1137 
1138 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1139   return Subtarget.hasStdExtZbb();
1140 }
1141 
1142 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1143   EVT VT = Y.getValueType();
1144 
1145   // FIXME: Support vectors once we have tests.
1146   if (VT.isVector())
1147     return false;
1148 
1149   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1150           Subtarget.hasStdExtZbkb()) &&
1151          !isa<ConstantSDNode>(Y);
1152 }
1153 
1154 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
1155   // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1156   auto *C = dyn_cast<ConstantSDNode>(Y);
1157   return C && C->getAPIntValue().ule(10);
1158 }
1159 
1160 bool RISCVTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1161                                                             Type *Ty) const {
1162   assert(Ty->isIntegerTy());
1163 
1164   unsigned BitSize = Ty->getIntegerBitWidth();
1165   if (BitSize > Subtarget.getXLen())
1166     return false;
1167 
1168   // Fast path, assume 32-bit immediates are cheap.
1169   int64_t Val = Imm.getSExtValue();
1170   if (isInt<32>(Val))
1171     return true;
1172 
1173   // A constant pool entry may be more aligned thant he load we're trying to
1174   // replace. If we don't support unaligned scalar mem, prefer the constant
1175   // pool.
1176   // TODO: Can the caller pass down the alignment?
1177   if (!Subtarget.enableUnalignedScalarMem())
1178     return true;
1179 
1180   // Prefer to keep the load if it would require many instructions.
1181   // This uses the same threshold we use for constant pools but doesn't
1182   // check useConstantPoolForLargeInts.
1183   // TODO: Should we keep the load only when we're definitely going to emit a
1184   // constant pool?
1185 
1186   RISCVMatInt::InstSeq Seq =
1187       RISCVMatInt::generateInstSeq(Val, Subtarget.getFeatureBits());
1188   return Seq.size() <= Subtarget.getMaxBuildIntsCost();
1189 }
1190 
1191 bool RISCVTargetLowering::
1192     shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
1193         SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
1194         unsigned OldShiftOpcode, unsigned NewShiftOpcode,
1195         SelectionDAG &DAG) const {
1196   // One interesting pattern that we'd want to form is 'bit extract':
1197   //   ((1 >> Y) & 1) ==/!= 0
1198   // But we also need to be careful not to try to reverse that fold.
1199 
1200   // Is this '((1 >> Y) & 1)'?
1201   if (XC && OldShiftOpcode == ISD::SRL && XC->isOne())
1202     return false; // Keep the 'bit extract' pattern.
1203 
1204   // Will this be '((1 >> Y) & 1)' after the transform?
1205   if (NewShiftOpcode == ISD::SRL && CC->isOne())
1206     return true; // Do form the 'bit extract' pattern.
1207 
1208   // If 'X' is a constant, and we transform, then we will immediately
1209   // try to undo the fold, thus causing endless combine loop.
1210   // So only do the transform if X is not a constant. This matches the default
1211   // implementation of this function.
1212   return !XC;
1213 }
1214 
1215 /// Check if sinking \p I's operands to I's basic block is profitable, because
1216 /// the operands can be folded into a target instruction, e.g.
1217 /// splats of scalars can fold into vector instructions.
1218 bool RISCVTargetLowering::shouldSinkOperands(
1219     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1220   using namespace llvm::PatternMatch;
1221 
1222   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1223     return false;
1224 
1225   auto IsSinker = [&](Instruction *I, int Operand) {
1226     switch (I->getOpcode()) {
1227     case Instruction::Add:
1228     case Instruction::Sub:
1229     case Instruction::Mul:
1230     case Instruction::And:
1231     case Instruction::Or:
1232     case Instruction::Xor:
1233     case Instruction::FAdd:
1234     case Instruction::FSub:
1235     case Instruction::FMul:
1236     case Instruction::FDiv:
1237     case Instruction::ICmp:
1238     case Instruction::FCmp:
1239       return true;
1240     case Instruction::Shl:
1241     case Instruction::LShr:
1242     case Instruction::AShr:
1243     case Instruction::UDiv:
1244     case Instruction::SDiv:
1245     case Instruction::URem:
1246     case Instruction::SRem:
1247       return Operand == 1;
1248     case Instruction::Call:
1249       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1250         switch (II->getIntrinsicID()) {
1251         case Intrinsic::fma:
1252         case Intrinsic::vp_fma:
1253           return Operand == 0 || Operand == 1;
1254         // FIXME: Our patterns can only match vx/vf instructions when the splat
1255         // it on the RHS, because TableGen doesn't recognize our VP operations
1256         // as commutative.
1257         case Intrinsic::vp_add:
1258         case Intrinsic::vp_mul:
1259         case Intrinsic::vp_and:
1260         case Intrinsic::vp_or:
1261         case Intrinsic::vp_xor:
1262         case Intrinsic::vp_fadd:
1263         case Intrinsic::vp_fmul:
1264         case Intrinsic::vp_shl:
1265         case Intrinsic::vp_lshr:
1266         case Intrinsic::vp_ashr:
1267         case Intrinsic::vp_udiv:
1268         case Intrinsic::vp_sdiv:
1269         case Intrinsic::vp_urem:
1270         case Intrinsic::vp_srem:
1271           return Operand == 1;
1272         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1273         // explicit patterns for both LHS and RHS (as 'vr' versions).
1274         case Intrinsic::vp_sub:
1275         case Intrinsic::vp_fsub:
1276         case Intrinsic::vp_fdiv:
1277           return Operand == 0 || Operand == 1;
1278         default:
1279           return false;
1280         }
1281       }
1282       return false;
1283     default:
1284       return false;
1285     }
1286   };
1287 
1288   for (auto OpIdx : enumerate(I->operands())) {
1289     if (!IsSinker(I, OpIdx.index()))
1290       continue;
1291 
1292     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1293     // Make sure we are not already sinking this operand
1294     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1295       continue;
1296 
1297     // We are looking for a splat that can be sunk.
1298     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1299                              m_Undef(), m_ZeroMask())))
1300       continue;
1301 
1302     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1303     // and vector registers
1304     for (Use &U : Op->uses()) {
1305       Instruction *Insn = cast<Instruction>(U.getUser());
1306       if (!IsSinker(Insn, U.getOperandNo()))
1307         return false;
1308     }
1309 
1310     Ops.push_back(&Op->getOperandUse(0));
1311     Ops.push_back(&OpIdx.value());
1312   }
1313   return true;
1314 }
1315 
1316 bool RISCVTargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
1317   unsigned Opc = VecOp.getOpcode();
1318 
1319   // Assume target opcodes can't be scalarized.
1320   // TODO - do we have any exceptions?
1321   if (Opc >= ISD::BUILTIN_OP_END)
1322     return false;
1323 
1324   // If the vector op is not supported, try to convert to scalar.
1325   EVT VecVT = VecOp.getValueType();
1326   if (!isOperationLegalOrCustomOrPromote(Opc, VecVT))
1327     return true;
1328 
1329   // If the vector op is supported, but the scalar op is not, the transform may
1330   // not be worthwhile.
1331   EVT ScalarVT = VecVT.getScalarType();
1332   return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
1333 }
1334 
1335 bool RISCVTargetLowering::isOffsetFoldingLegal(
1336     const GlobalAddressSDNode *GA) const {
1337   // In order to maximise the opportunity for common subexpression elimination,
1338   // keep a separate ADD node for the global address offset instead of folding
1339   // it in the global address node. Later peephole optimisations may choose to
1340   // fold it back in when profitable.
1341   return false;
1342 }
1343 
1344 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1345                                        bool ForCodeSize) const {
1346   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1347   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1348     return false;
1349   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1350     return false;
1351   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1352     return false;
1353   return Imm.isZero();
1354 }
1355 
1356 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1357   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1358          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1359          (VT == MVT::f64 && Subtarget.hasStdExtD());
1360 }
1361 
1362 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1363                                                       CallingConv::ID CC,
1364                                                       EVT VT) const {
1365   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1366   // We might still end up using a GPR but that will be decided based on ABI.
1367   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1368   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1369     return MVT::f32;
1370 
1371   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1372 }
1373 
1374 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1375                                                            CallingConv::ID CC,
1376                                                            EVT VT) const {
1377   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1378   // We might still end up using a GPR but that will be decided based on ABI.
1379   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1380   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1381     return 1;
1382 
1383   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1384 }
1385 
1386 // Changes the condition code and swaps operands if necessary, so the SetCC
1387 // operation matches one of the comparisons supported directly by branches
1388 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1389 // with 1/-1.
1390 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1391                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1392   // If this is a single bit test that can't be handled by ANDI, shift the
1393   // bit to be tested to the MSB and perform a signed compare with 0.
1394   if (isIntEqualitySetCC(CC) && isNullConstant(RHS) &&
1395       LHS.getOpcode() == ISD::AND && LHS.hasOneUse() &&
1396       isa<ConstantSDNode>(LHS.getOperand(1))) {
1397     uint64_t Mask = LHS.getConstantOperandVal(1);
1398     if (isPowerOf2_64(Mask) && !isInt<12>(Mask)) {
1399       CC = CC == ISD::SETEQ ? ISD::SETGE : ISD::SETLT;
1400       unsigned ShAmt = LHS.getValueSizeInBits() - 1 - Log2_64(Mask);
1401       LHS = LHS.getOperand(0);
1402       if (ShAmt != 0)
1403         LHS = DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS,
1404                           DAG.getConstant(ShAmt, DL, LHS.getValueType()));
1405       return;
1406     }
1407   }
1408 
1409   if (auto *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1410     int64_t C = RHSC->getSExtValue();
1411     switch (CC) {
1412     default: break;
1413     case ISD::SETGT:
1414       // Convert X > -1 to X >= 0.
1415       if (C == -1) {
1416         RHS = DAG.getConstant(0, DL, RHS.getValueType());
1417         CC = ISD::SETGE;
1418         return;
1419       }
1420       break;
1421     case ISD::SETLT:
1422       // Convert X < 1 to 0 <= X.
1423       if (C == 1) {
1424         RHS = LHS;
1425         LHS = DAG.getConstant(0, DL, RHS.getValueType());
1426         CC = ISD::SETGE;
1427         return;
1428       }
1429       break;
1430     }
1431   }
1432 
1433   switch (CC) {
1434   default:
1435     break;
1436   case ISD::SETGT:
1437   case ISD::SETLE:
1438   case ISD::SETUGT:
1439   case ISD::SETULE:
1440     CC = ISD::getSetCCSwappedOperands(CC);
1441     std::swap(LHS, RHS);
1442     break;
1443   }
1444 }
1445 
1446 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1447   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1448   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1449   if (VT.getVectorElementType() == MVT::i1)
1450     KnownSize *= 8;
1451 
1452   switch (KnownSize) {
1453   default:
1454     llvm_unreachable("Invalid LMUL.");
1455   case 8:
1456     return RISCVII::VLMUL::LMUL_F8;
1457   case 16:
1458     return RISCVII::VLMUL::LMUL_F4;
1459   case 32:
1460     return RISCVII::VLMUL::LMUL_F2;
1461   case 64:
1462     return RISCVII::VLMUL::LMUL_1;
1463   case 128:
1464     return RISCVII::VLMUL::LMUL_2;
1465   case 256:
1466     return RISCVII::VLMUL::LMUL_4;
1467   case 512:
1468     return RISCVII::VLMUL::LMUL_8;
1469   }
1470 }
1471 
1472 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1473   switch (LMul) {
1474   default:
1475     llvm_unreachable("Invalid LMUL.");
1476   case RISCVII::VLMUL::LMUL_F8:
1477   case RISCVII::VLMUL::LMUL_F4:
1478   case RISCVII::VLMUL::LMUL_F2:
1479   case RISCVII::VLMUL::LMUL_1:
1480     return RISCV::VRRegClassID;
1481   case RISCVII::VLMUL::LMUL_2:
1482     return RISCV::VRM2RegClassID;
1483   case RISCVII::VLMUL::LMUL_4:
1484     return RISCV::VRM4RegClassID;
1485   case RISCVII::VLMUL::LMUL_8:
1486     return RISCV::VRM8RegClassID;
1487   }
1488 }
1489 
1490 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1491   RISCVII::VLMUL LMUL = getLMUL(VT);
1492   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1493       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1494       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1495       LMUL == RISCVII::VLMUL::LMUL_1) {
1496     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1497                   "Unexpected subreg numbering");
1498     return RISCV::sub_vrm1_0 + Index;
1499   }
1500   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1501     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1502                   "Unexpected subreg numbering");
1503     return RISCV::sub_vrm2_0 + Index;
1504   }
1505   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1506     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1507                   "Unexpected subreg numbering");
1508     return RISCV::sub_vrm4_0 + Index;
1509   }
1510   llvm_unreachable("Invalid vector type.");
1511 }
1512 
1513 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1514   if (VT.getVectorElementType() == MVT::i1)
1515     return RISCV::VRRegClassID;
1516   return getRegClassIDForLMUL(getLMUL(VT));
1517 }
1518 
1519 // Attempt to decompose a subvector insert/extract between VecVT and
1520 // SubVecVT via subregister indices. Returns the subregister index that
1521 // can perform the subvector insert/extract with the given element index, as
1522 // well as the index corresponding to any leftover subvectors that must be
1523 // further inserted/extracted within the register class for SubVecVT.
1524 std::pair<unsigned, unsigned>
1525 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1526     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1527     const RISCVRegisterInfo *TRI) {
1528   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1529                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1530                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1531                 "Register classes not ordered");
1532   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1533   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1534   // Try to compose a subregister index that takes us from the incoming
1535   // LMUL>1 register class down to the outgoing one. At each step we half
1536   // the LMUL:
1537   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1538   // Note that this is not guaranteed to find a subregister index, such as
1539   // when we are extracting from one VR type to another.
1540   unsigned SubRegIdx = RISCV::NoSubRegister;
1541   for (const unsigned RCID :
1542        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1543     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1544       VecVT = VecVT.getHalfNumVectorElementsVT();
1545       bool IsHi =
1546           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1547       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1548                                             getSubregIndexByMVT(VecVT, IsHi));
1549       if (IsHi)
1550         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1551     }
1552   return {SubRegIdx, InsertExtractIdx};
1553 }
1554 
1555 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1556 // stores for those types.
1557 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1558   return !Subtarget.useRVVForFixedLengthVectors() ||
1559          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1560 }
1561 
1562 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1563   if (ScalarTy->isPointerTy())
1564     return true;
1565 
1566   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1567       ScalarTy->isIntegerTy(32))
1568     return true;
1569 
1570   if (ScalarTy->isIntegerTy(64))
1571     return Subtarget.hasVInstructionsI64();
1572 
1573   if (ScalarTy->isHalfTy())
1574     return Subtarget.hasVInstructionsF16();
1575   if (ScalarTy->isFloatTy())
1576     return Subtarget.hasVInstructionsF32();
1577   if (ScalarTy->isDoubleTy())
1578     return Subtarget.hasVInstructionsF64();
1579 
1580   return false;
1581 }
1582 
1583 static SDValue getVLOperand(SDValue Op) {
1584   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1585           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1586          "Unexpected opcode");
1587   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1588   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1589   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1590       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1591   if (!II)
1592     return SDValue();
1593   return Op.getOperand(II->VLOperand + 1 + HasChain);
1594 }
1595 
1596 static bool useRVVForFixedLengthVectorVT(MVT VT,
1597                                          const RISCVSubtarget &Subtarget) {
1598   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1599   if (!Subtarget.useRVVForFixedLengthVectors())
1600     return false;
1601 
1602   // We only support a set of vector types with a consistent maximum fixed size
1603   // across all supported vector element types to avoid legalization issues.
1604   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1605   // fixed-length vector type we support is 1024 bytes.
1606   if (VT.getFixedSizeInBits() > 1024 * 8)
1607     return false;
1608 
1609   unsigned MinVLen = Subtarget.getRealMinVLen();
1610 
1611   MVT EltVT = VT.getVectorElementType();
1612 
1613   // Don't use RVV for vectors we cannot scalarize if required.
1614   switch (EltVT.SimpleTy) {
1615   // i1 is supported but has different rules.
1616   default:
1617     return false;
1618   case MVT::i1:
1619     // Masks can only use a single register.
1620     if (VT.getVectorNumElements() > MinVLen)
1621       return false;
1622     MinVLen /= 8;
1623     break;
1624   case MVT::i8:
1625   case MVT::i16:
1626   case MVT::i32:
1627     break;
1628   case MVT::i64:
1629     if (!Subtarget.hasVInstructionsI64())
1630       return false;
1631     break;
1632   case MVT::f16:
1633     if (!Subtarget.hasVInstructionsF16())
1634       return false;
1635     break;
1636   case MVT::f32:
1637     if (!Subtarget.hasVInstructionsF32())
1638       return false;
1639     break;
1640   case MVT::f64:
1641     if (!Subtarget.hasVInstructionsF64())
1642       return false;
1643     break;
1644   }
1645 
1646   // Reject elements larger than ELEN.
1647   if (EltVT.getSizeInBits() > Subtarget.getELEN())
1648     return false;
1649 
1650   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1651   // Don't use RVV for types that don't fit.
1652   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1653     return false;
1654 
1655   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1656   // the base fixed length RVV support in place.
1657   if (!VT.isPow2VectorType())
1658     return false;
1659 
1660   return true;
1661 }
1662 
1663 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1664   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1665 }
1666 
1667 // Return the largest legal scalable vector type that matches VT's element type.
1668 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1669                                             const RISCVSubtarget &Subtarget) {
1670   // This may be called before legal types are setup.
1671   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1672           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1673          "Expected legal fixed length vector!");
1674 
1675   unsigned MinVLen = Subtarget.getRealMinVLen();
1676   unsigned MaxELen = Subtarget.getELEN();
1677 
1678   MVT EltVT = VT.getVectorElementType();
1679   switch (EltVT.SimpleTy) {
1680   default:
1681     llvm_unreachable("unexpected element type for RVV container");
1682   case MVT::i1:
1683   case MVT::i8:
1684   case MVT::i16:
1685   case MVT::i32:
1686   case MVT::i64:
1687   case MVT::f16:
1688   case MVT::f32:
1689   case MVT::f64: {
1690     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1691     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1692     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1693     unsigned NumElts =
1694         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1695     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1696     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1697     return MVT::getScalableVectorVT(EltVT, NumElts);
1698   }
1699   }
1700 }
1701 
1702 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1703                                             const RISCVSubtarget &Subtarget) {
1704   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1705                                           Subtarget);
1706 }
1707 
1708 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1709   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1710 }
1711 
1712 // Grow V to consume an entire RVV register.
1713 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1714                                        const RISCVSubtarget &Subtarget) {
1715   assert(VT.isScalableVector() &&
1716          "Expected to convert into a scalable vector!");
1717   assert(V.getValueType().isFixedLengthVector() &&
1718          "Expected a fixed length vector operand!");
1719   SDLoc DL(V);
1720   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1721   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1722 }
1723 
1724 // Shrink V so it's just big enough to maintain a VT's worth of data.
1725 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1726                                          const RISCVSubtarget &Subtarget) {
1727   assert(VT.isFixedLengthVector() &&
1728          "Expected to convert into a fixed length vector!");
1729   assert(V.getValueType().isScalableVector() &&
1730          "Expected a scalable vector operand!");
1731   SDLoc DL(V);
1732   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1733   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1734 }
1735 
1736 /// Return the type of the mask type suitable for masking the provided
1737 /// vector type.  This is simply an i1 element type vector of the same
1738 /// (possibly scalable) length.
1739 static MVT getMaskTypeFor(MVT VecVT) {
1740   assert(VecVT.isVector());
1741   ElementCount EC = VecVT.getVectorElementCount();
1742   return MVT::getVectorVT(MVT::i1, EC);
1743 }
1744 
1745 /// Creates an all ones mask suitable for masking a vector of type VecTy with
1746 /// vector length VL.  .
1747 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL,
1748                               SelectionDAG &DAG) {
1749   MVT MaskVT = getMaskTypeFor(VecVT);
1750   return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1751 }
1752 
1753 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1754 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1755 // the vector type that it is contained in.
1756 static std::pair<SDValue, SDValue>
1757 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1758                 const RISCVSubtarget &Subtarget) {
1759   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1760   MVT XLenVT = Subtarget.getXLenVT();
1761   SDValue VL = VecVT.isFixedLengthVector()
1762                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1763                    : DAG.getRegister(RISCV::X0, XLenVT);
1764   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
1765   return {Mask, VL};
1766 }
1767 
1768 // As above but assuming the given type is a scalable vector type.
1769 static std::pair<SDValue, SDValue>
1770 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1771                         const RISCVSubtarget &Subtarget) {
1772   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1773   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1774 }
1775 
1776 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1777 // of either is (currently) supported. This can get us into an infinite loop
1778 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1779 // as a ..., etc.
1780 // Until either (or both) of these can reliably lower any node, reporting that
1781 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1782 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1783 // which is not desirable.
1784 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1785     EVT VT, unsigned DefinedValues) const {
1786   return false;
1787 }
1788 
1789 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1790                                   const RISCVSubtarget &Subtarget) {
1791   // RISCV FP-to-int conversions saturate to the destination register size, but
1792   // don't produce 0 for nan. We can use a conversion instruction and fix the
1793   // nan case with a compare and a select.
1794   SDValue Src = Op.getOperand(0);
1795 
1796   EVT DstVT = Op.getValueType();
1797   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1798 
1799   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1800   unsigned Opc;
1801   if (SatVT == DstVT)
1802     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1803   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1804     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1805   else
1806     return SDValue();
1807   // FIXME: Support other SatVTs by clamping before or after the conversion.
1808 
1809   SDLoc DL(Op);
1810   SDValue FpToInt = DAG.getNode(
1811       Opc, DL, DstVT, Src,
1812       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1813 
1814   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1815   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1816 }
1817 
1818 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1819 // and back. Taking care to avoid converting values that are nan or already
1820 // correct.
1821 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1822 // have FRM dependencies modeled yet.
1823 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1824   MVT VT = Op.getSimpleValueType();
1825   assert(VT.isVector() && "Unexpected type");
1826 
1827   SDLoc DL(Op);
1828 
1829   // Freeze the source since we are increasing the number of uses.
1830   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1831 
1832   // Truncate to integer and convert back to FP.
1833   MVT IntVT = VT.changeVectorElementTypeToInteger();
1834   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1835   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1836 
1837   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1838 
1839   if (Op.getOpcode() == ISD::FCEIL) {
1840     // If the truncated value is the greater than or equal to the original
1841     // value, we've computed the ceil. Otherwise, we went the wrong way and
1842     // need to increase by 1.
1843     // FIXME: This should use a masked operation. Handle here or in isel?
1844     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1845                                  DAG.getConstantFP(1.0, DL, VT));
1846     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1847     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1848   } else if (Op.getOpcode() == ISD::FFLOOR) {
1849     // If the truncated value is the less than or equal to the original value,
1850     // we've computed the floor. Otherwise, we went the wrong way and need to
1851     // decrease by 1.
1852     // FIXME: This should use a masked operation. Handle here or in isel?
1853     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1854                                  DAG.getConstantFP(1.0, DL, VT));
1855     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1856     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1857   }
1858 
1859   // Restore the original sign so that -0.0 is preserved.
1860   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1861 
1862   // Determine the largest integer that can be represented exactly. This and
1863   // values larger than it don't have any fractional bits so don't need to
1864   // be converted.
1865   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1866   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1867   APFloat MaxVal = APFloat(FltSem);
1868   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1869                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1870   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1871 
1872   // If abs(Src) was larger than MaxVal or nan, keep it.
1873   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1874   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1875   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1876 }
1877 
1878 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1879 // This mode isn't supported in vector hardware on RISCV. But as long as we
1880 // aren't compiling with trapping math, we can emulate this with
1881 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1882 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1883 // dependencies modeled yet.
1884 // FIXME: Use masked operations to avoid final merge.
1885 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1886   MVT VT = Op.getSimpleValueType();
1887   assert(VT.isVector() && "Unexpected type");
1888 
1889   SDLoc DL(Op);
1890 
1891   // Freeze the source since we are increasing the number of uses.
1892   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1893 
1894   // We do the conversion on the absolute value and fix the sign at the end.
1895   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1896 
1897   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1898   bool Ignored;
1899   APFloat Point5Pred = APFloat(0.5f);
1900   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1901   Point5Pred.next(/*nextDown*/ true);
1902 
1903   // Add the adjustment.
1904   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1905                                DAG.getConstantFP(Point5Pred, DL, VT));
1906 
1907   // Truncate to integer and convert back to fp.
1908   MVT IntVT = VT.changeVectorElementTypeToInteger();
1909   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1910   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1911 
1912   // Restore the original sign.
1913   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1914 
1915   // Determine the largest integer that can be represented exactly. This and
1916   // values larger than it don't have any fractional bits so don't need to
1917   // be converted.
1918   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1919   APFloat MaxVal = APFloat(FltSem);
1920   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1921                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1922   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1923 
1924   // If abs(Src) was larger than MaxVal or nan, keep it.
1925   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1926   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1927   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1928 }
1929 
1930 struct VIDSequence {
1931   int64_t StepNumerator;
1932   unsigned StepDenominator;
1933   int64_t Addend;
1934 };
1935 
1936 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1937 // to the (non-zero) step S and start value X. This can be then lowered as the
1938 // RVV sequence (VID * S) + X, for example.
1939 // The step S is represented as an integer numerator divided by a positive
1940 // denominator. Note that the implementation currently only identifies
1941 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1942 // cannot detect 2/3, for example.
1943 // Note that this method will also match potentially unappealing index
1944 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1945 // determine whether this is worth generating code for.
1946 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1947   unsigned NumElts = Op.getNumOperands();
1948   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1949   if (!Op.getValueType().isInteger())
1950     return None;
1951 
1952   Optional<unsigned> SeqStepDenom;
1953   Optional<int64_t> SeqStepNum, SeqAddend;
1954   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1955   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1956   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1957     // Assume undef elements match the sequence; we just have to be careful
1958     // when interpolating across them.
1959     if (Op.getOperand(Idx).isUndef())
1960       continue;
1961     // The BUILD_VECTOR must be all constants.
1962     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1963       return None;
1964 
1965     uint64_t Val = Op.getConstantOperandVal(Idx) &
1966                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1967 
1968     if (PrevElt) {
1969       // Calculate the step since the last non-undef element, and ensure
1970       // it's consistent across the entire sequence.
1971       unsigned IdxDiff = Idx - PrevElt->second;
1972       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1973 
1974       // A zero-value value difference means that we're somewhere in the middle
1975       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1976       // step change before evaluating the sequence.
1977       if (ValDiff == 0)
1978         continue;
1979 
1980       int64_t Remainder = ValDiff % IdxDiff;
1981       // Normalize the step if it's greater than 1.
1982       if (Remainder != ValDiff) {
1983         // The difference must cleanly divide the element span.
1984         if (Remainder != 0)
1985           return None;
1986         ValDiff /= IdxDiff;
1987         IdxDiff = 1;
1988       }
1989 
1990       if (!SeqStepNum)
1991         SeqStepNum = ValDiff;
1992       else if (ValDiff != SeqStepNum)
1993         return None;
1994 
1995       if (!SeqStepDenom)
1996         SeqStepDenom = IdxDiff;
1997       else if (IdxDiff != *SeqStepDenom)
1998         return None;
1999     }
2000 
2001     // Record this non-undef element for later.
2002     if (!PrevElt || PrevElt->first != Val)
2003       PrevElt = std::make_pair(Val, Idx);
2004   }
2005 
2006   // We need to have logged a step for this to count as a legal index sequence.
2007   if (!SeqStepNum || !SeqStepDenom)
2008     return None;
2009 
2010   // Loop back through the sequence and validate elements we might have skipped
2011   // while waiting for a valid step. While doing this, log any sequence addend.
2012   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
2013     if (Op.getOperand(Idx).isUndef())
2014       continue;
2015     uint64_t Val = Op.getConstantOperandVal(Idx) &
2016                    maskTrailingOnes<uint64_t>(EltSizeInBits);
2017     uint64_t ExpectedVal =
2018         (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
2019     int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
2020     if (!SeqAddend)
2021       SeqAddend = Addend;
2022     else if (Addend != SeqAddend)
2023       return None;
2024   }
2025 
2026   assert(SeqAddend && "Must have an addend if we have a step");
2027 
2028   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
2029 }
2030 
2031 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
2032 // and lower it as a VRGATHER_VX_VL from the source vector.
2033 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
2034                                   SelectionDAG &DAG,
2035                                   const RISCVSubtarget &Subtarget) {
2036   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
2037     return SDValue();
2038   SDValue Vec = SplatVal.getOperand(0);
2039   // Only perform this optimization on vectors of the same size for simplicity.
2040   // Don't perform this optimization for i1 vectors.
2041   // FIXME: Support i1 vectors, maybe by promoting to i8?
2042   if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1)
2043     return SDValue();
2044   SDValue Idx = SplatVal.getOperand(1);
2045   // The index must be a legal type.
2046   if (Idx.getValueType() != Subtarget.getXLenVT())
2047     return SDValue();
2048 
2049   MVT ContainerVT = VT;
2050   if (VT.isFixedLengthVector()) {
2051     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2052     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2053   }
2054 
2055   SDValue Mask, VL;
2056   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2057 
2058   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
2059                                Idx, Mask, DAG.getUNDEF(ContainerVT), VL);
2060 
2061   if (!VT.isFixedLengthVector())
2062     return Gather;
2063 
2064   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2065 }
2066 
2067 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
2068                                  const RISCVSubtarget &Subtarget) {
2069   MVT VT = Op.getSimpleValueType();
2070   assert(VT.isFixedLengthVector() && "Unexpected vector!");
2071 
2072   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2073 
2074   SDLoc DL(Op);
2075   SDValue Mask, VL;
2076   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2077 
2078   MVT XLenVT = Subtarget.getXLenVT();
2079   unsigned NumElts = Op.getNumOperands();
2080 
2081   if (VT.getVectorElementType() == MVT::i1) {
2082     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
2083       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
2084       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
2085     }
2086 
2087     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
2088       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
2089       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
2090     }
2091 
2092     // Lower constant mask BUILD_VECTORs via an integer vector type, in
2093     // scalar integer chunks whose bit-width depends on the number of mask
2094     // bits and XLEN.
2095     // First, determine the most appropriate scalar integer type to use. This
2096     // is at most XLenVT, but may be shrunk to a smaller vector element type
2097     // according to the size of the final vector - use i8 chunks rather than
2098     // XLenVT if we're producing a v8i1. This results in more consistent
2099     // codegen across RV32 and RV64.
2100     unsigned NumViaIntegerBits =
2101         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2102     NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN());
2103     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2104       // If we have to use more than one INSERT_VECTOR_ELT then this
2105       // optimization is likely to increase code size; avoid peforming it in
2106       // such a case. We can use a load from a constant pool in this case.
2107       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2108         return SDValue();
2109       // Now we can create our integer vector type. Note that it may be larger
2110       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2111       MVT IntegerViaVecVT =
2112           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2113                            divideCeil(NumElts, NumViaIntegerBits));
2114 
2115       uint64_t Bits = 0;
2116       unsigned BitPos = 0, IntegerEltIdx = 0;
2117       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2118 
2119       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2120         // Once we accumulate enough bits to fill our scalar type, insert into
2121         // our vector and clear our accumulated data.
2122         if (I != 0 && I % NumViaIntegerBits == 0) {
2123           if (NumViaIntegerBits <= 32)
2124             Bits = SignExtend64<32>(Bits);
2125           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2126           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2127                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2128           Bits = 0;
2129           BitPos = 0;
2130           IntegerEltIdx++;
2131         }
2132         SDValue V = Op.getOperand(I);
2133         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2134         Bits |= ((uint64_t)BitValue << BitPos);
2135       }
2136 
2137       // Insert the (remaining) scalar value into position in our integer
2138       // vector type.
2139       if (NumViaIntegerBits <= 32)
2140         Bits = SignExtend64<32>(Bits);
2141       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2142       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2143                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2144 
2145       if (NumElts < NumViaIntegerBits) {
2146         // If we're producing a smaller vector than our minimum legal integer
2147         // type, bitcast to the equivalent (known-legal) mask type, and extract
2148         // our final mask.
2149         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2150         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2151         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2152                           DAG.getConstant(0, DL, XLenVT));
2153       } else {
2154         // Else we must have produced an integer type with the same size as the
2155         // mask type; bitcast for the final result.
2156         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2157         Vec = DAG.getBitcast(VT, Vec);
2158       }
2159 
2160       return Vec;
2161     }
2162 
2163     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2164     // vector type, we have a legal equivalently-sized i8 type, so we can use
2165     // that.
2166     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2167     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2168 
2169     SDValue WideVec;
2170     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2171       // For a splat, perform a scalar truncate before creating the wider
2172       // vector.
2173       assert(Splat.getValueType() == XLenVT &&
2174              "Unexpected type for i1 splat value");
2175       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2176                           DAG.getConstant(1, DL, XLenVT));
2177       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2178     } else {
2179       SmallVector<SDValue, 8> Ops(Op->op_values());
2180       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2181       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2182       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2183     }
2184 
2185     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2186   }
2187 
2188   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2189     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2190       return Gather;
2191     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2192                                         : RISCVISD::VMV_V_X_VL;
2193     Splat =
2194         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2195     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2196   }
2197 
2198   // Try and match index sequences, which we can lower to the vid instruction
2199   // with optional modifications. An all-undef vector is matched by
2200   // getSplatValue, above.
2201   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2202     int64_t StepNumerator = SimpleVID->StepNumerator;
2203     unsigned StepDenominator = SimpleVID->StepDenominator;
2204     int64_t Addend = SimpleVID->Addend;
2205 
2206     assert(StepNumerator != 0 && "Invalid step");
2207     bool Negate = false;
2208     int64_t SplatStepVal = StepNumerator;
2209     unsigned StepOpcode = ISD::MUL;
2210     if (StepNumerator != 1) {
2211       if (isPowerOf2_64(std::abs(StepNumerator))) {
2212         Negate = StepNumerator < 0;
2213         StepOpcode = ISD::SHL;
2214         SplatStepVal = Log2_64(std::abs(StepNumerator));
2215       }
2216     }
2217 
2218     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2219     // threshold since it's the immediate value many RVV instructions accept.
2220     // There is no vmul.vi instruction so ensure multiply constant can fit in
2221     // a single addi instruction.
2222     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2223          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2224         isPowerOf2_32(StepDenominator) &&
2225         (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) {
2226       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2227       // Convert right out of the scalable type so we can use standard ISD
2228       // nodes for the rest of the computation. If we used scalable types with
2229       // these, we'd lose the fixed-length vector info and generate worse
2230       // vsetvli code.
2231       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2232       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2233           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2234         SDValue SplatStep = DAG.getSplatBuildVector(
2235             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2236         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2237       }
2238       if (StepDenominator != 1) {
2239         SDValue SplatStep = DAG.getSplatBuildVector(
2240             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2241         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2242       }
2243       if (Addend != 0 || Negate) {
2244         SDValue SplatAddend = DAG.getSplatBuildVector(
2245             VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2246         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2247       }
2248       return VID;
2249     }
2250   }
2251 
2252   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2253   // when re-interpreted as a vector with a larger element type. For example,
2254   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2255   // could be instead splat as
2256   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2257   // TODO: This optimization could also work on non-constant splats, but it
2258   // would require bit-manipulation instructions to construct the splat value.
2259   SmallVector<SDValue> Sequence;
2260   unsigned EltBitSize = VT.getScalarSizeInBits();
2261   const auto *BV = cast<BuildVectorSDNode>(Op);
2262   if (VT.isInteger() && EltBitSize < 64 &&
2263       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2264       BV->getRepeatedSequence(Sequence) &&
2265       (Sequence.size() * EltBitSize) <= 64) {
2266     unsigned SeqLen = Sequence.size();
2267     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2268     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2269     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2270             ViaIntVT == MVT::i64) &&
2271            "Unexpected sequence type");
2272 
2273     unsigned EltIdx = 0;
2274     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2275     uint64_t SplatValue = 0;
2276     // Construct the amalgamated value which can be splatted as this larger
2277     // vector type.
2278     for (const auto &SeqV : Sequence) {
2279       if (!SeqV.isUndef())
2280         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2281                        << (EltIdx * EltBitSize));
2282       EltIdx++;
2283     }
2284 
2285     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2286     // achieve better constant materializion.
2287     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2288       SplatValue = SignExtend64<32>(SplatValue);
2289 
2290     // Since we can't introduce illegal i64 types at this stage, we can only
2291     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2292     // way we can use RVV instructions to splat.
2293     assert((ViaIntVT.bitsLE(XLenVT) ||
2294             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2295            "Unexpected bitcast sequence");
2296     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2297       SDValue ViaVL =
2298           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2299       MVT ViaContainerVT =
2300           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2301       SDValue Splat =
2302           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2303                       DAG.getUNDEF(ViaContainerVT),
2304                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2305       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2306       return DAG.getBitcast(VT, Splat);
2307     }
2308   }
2309 
2310   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2311   // which constitute a large proportion of the elements. In such cases we can
2312   // splat a vector with the dominant element and make up the shortfall with
2313   // INSERT_VECTOR_ELTs.
2314   // Note that this includes vectors of 2 elements by association. The
2315   // upper-most element is the "dominant" one, allowing us to use a splat to
2316   // "insert" the upper element, and an insert of the lower element at position
2317   // 0, which improves codegen.
2318   SDValue DominantValue;
2319   unsigned MostCommonCount = 0;
2320   DenseMap<SDValue, unsigned> ValueCounts;
2321   unsigned NumUndefElts =
2322       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2323 
2324   // Track the number of scalar loads we know we'd be inserting, estimated as
2325   // any non-zero floating-point constant. Other kinds of element are either
2326   // already in registers or are materialized on demand. The threshold at which
2327   // a vector load is more desirable than several scalar materializion and
2328   // vector-insertion instructions is not known.
2329   unsigned NumScalarLoads = 0;
2330 
2331   for (SDValue V : Op->op_values()) {
2332     if (V.isUndef())
2333       continue;
2334 
2335     ValueCounts.insert(std::make_pair(V, 0));
2336     unsigned &Count = ValueCounts[V];
2337 
2338     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2339       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2340 
2341     // Is this value dominant? In case of a tie, prefer the highest element as
2342     // it's cheaper to insert near the beginning of a vector than it is at the
2343     // end.
2344     if (++Count >= MostCommonCount) {
2345       DominantValue = V;
2346       MostCommonCount = Count;
2347     }
2348   }
2349 
2350   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2351   unsigned NumDefElts = NumElts - NumUndefElts;
2352   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2353 
2354   // Don't perform this optimization when optimizing for size, since
2355   // materializing elements and inserting them tends to cause code bloat.
2356   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2357       ((MostCommonCount > DominantValueCountThreshold) ||
2358        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2359     // Start by splatting the most common element.
2360     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2361 
2362     DenseSet<SDValue> Processed{DominantValue};
2363     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2364     for (const auto &OpIdx : enumerate(Op->ops())) {
2365       const SDValue &V = OpIdx.value();
2366       if (V.isUndef() || !Processed.insert(V).second)
2367         continue;
2368       if (ValueCounts[V] == 1) {
2369         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2370                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2371       } else {
2372         // Blend in all instances of this value using a VSELECT, using a
2373         // mask where each bit signals whether that element is the one
2374         // we're after.
2375         SmallVector<SDValue> Ops;
2376         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2377           return DAG.getConstant(V == V1, DL, XLenVT);
2378         });
2379         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2380                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2381                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2382       }
2383     }
2384 
2385     return Vec;
2386   }
2387 
2388   return SDValue();
2389 }
2390 
2391 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2392                                    SDValue Lo, SDValue Hi, SDValue VL,
2393                                    SelectionDAG &DAG) {
2394   if (!Passthru)
2395     Passthru = DAG.getUNDEF(VT);
2396   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2397     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2398     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2399     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2400     // node in order to try and match RVV vector/scalar instructions.
2401     if ((LoC >> 31) == HiC)
2402       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2403 
2404     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2405     // vmv.v.x whose EEW = 32 to lower it.
2406     auto *Const = dyn_cast<ConstantSDNode>(VL);
2407     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2408       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2409       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2410       // access the subtarget here now.
2411       auto InterVec = DAG.getNode(
2412           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2413                                   DAG.getRegister(RISCV::X0, MVT::i32));
2414       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2415     }
2416   }
2417 
2418   // Fall back to a stack store and stride x0 vector load.
2419   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2420                      Hi, VL);
2421 }
2422 
2423 // Called by type legalization to handle splat of i64 on RV32.
2424 // FIXME: We can optimize this when the type has sign or zero bits in one
2425 // of the halves.
2426 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2427                                    SDValue Scalar, SDValue VL,
2428                                    SelectionDAG &DAG) {
2429   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2430   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2431                            DAG.getConstant(0, DL, MVT::i32));
2432   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2433                            DAG.getConstant(1, DL, MVT::i32));
2434   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2435 }
2436 
2437 // This function lowers a splat of a scalar operand Splat with the vector
2438 // length VL. It ensures the final sequence is type legal, which is useful when
2439 // lowering a splat after type legalization.
2440 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2441                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2442                                 const RISCVSubtarget &Subtarget) {
2443   bool HasPassthru = Passthru && !Passthru.isUndef();
2444   if (!HasPassthru && !Passthru)
2445     Passthru = DAG.getUNDEF(VT);
2446   if (VT.isFloatingPoint()) {
2447     // If VL is 1, we could use vfmv.s.f.
2448     if (isOneConstant(VL))
2449       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2450     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2451   }
2452 
2453   MVT XLenVT = Subtarget.getXLenVT();
2454 
2455   // Simplest case is that the operand needs to be promoted to XLenVT.
2456   if (Scalar.getValueType().bitsLE(XLenVT)) {
2457     // If the operand is a constant, sign extend to increase our chances
2458     // of being able to use a .vi instruction. ANY_EXTEND would become a
2459     // a zero extend and the simm5 check in isel would fail.
2460     // FIXME: Should we ignore the upper bits in isel instead?
2461     unsigned ExtOpc =
2462         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2463     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2464     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2465     // If VL is 1 and the scalar value won't benefit from immediate, we could
2466     // use vmv.s.x.
2467     if (isOneConstant(VL) &&
2468         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2469       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2470     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2471   }
2472 
2473   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2474          "Unexpected scalar for splat lowering!");
2475 
2476   if (isOneConstant(VL) && isNullConstant(Scalar))
2477     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2478                        DAG.getConstant(0, DL, XLenVT), VL);
2479 
2480   // Otherwise use the more complicated splatting algorithm.
2481   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2482 }
2483 
2484 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2485                                 const RISCVSubtarget &Subtarget) {
2486   // We need to be able to widen elements to the next larger integer type.
2487   if (VT.getScalarSizeInBits() >= Subtarget.getELEN())
2488     return false;
2489 
2490   int Size = Mask.size();
2491   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2492 
2493   int Srcs[] = {-1, -1};
2494   for (int i = 0; i != Size; ++i) {
2495     // Ignore undef elements.
2496     if (Mask[i] < 0)
2497       continue;
2498 
2499     // Is this an even or odd element.
2500     int Pol = i % 2;
2501 
2502     // Ensure we consistently use the same source for this element polarity.
2503     int Src = Mask[i] / Size;
2504     if (Srcs[Pol] < 0)
2505       Srcs[Pol] = Src;
2506     if (Srcs[Pol] != Src)
2507       return false;
2508 
2509     // Make sure the element within the source is appropriate for this element
2510     // in the destination.
2511     int Elt = Mask[i] % Size;
2512     if (Elt != i / 2)
2513       return false;
2514   }
2515 
2516   // We need to find a source for each polarity and they can't be the same.
2517   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2518     return false;
2519 
2520   // Swap the sources if the second source was in the even polarity.
2521   SwapSources = Srcs[0] > Srcs[1];
2522 
2523   return true;
2524 }
2525 
2526 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2527 /// and then extract the original number of elements from the rotated result.
2528 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2529 /// returned rotation amount is for a rotate right, where elements move from
2530 /// higher elements to lower elements. \p LoSrc indicates the first source
2531 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2532 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2533 /// 0 or 1 if a rotation is found.
2534 ///
2535 /// NOTE: We talk about rotate to the right which matches how bit shift and
2536 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2537 /// and the table below write vectors with the lowest elements on the left.
2538 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2539   int Size = Mask.size();
2540 
2541   // We need to detect various ways of spelling a rotation:
2542   //   [11, 12, 13, 14, 15,  0,  1,  2]
2543   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2544   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2545   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2546   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2547   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2548   int Rotation = 0;
2549   LoSrc = -1;
2550   HiSrc = -1;
2551   for (int i = 0; i != Size; ++i) {
2552     int M = Mask[i];
2553     if (M < 0)
2554       continue;
2555 
2556     // Determine where a rotate vector would have started.
2557     int StartIdx = i - (M % Size);
2558     // The identity rotation isn't interesting, stop.
2559     if (StartIdx == 0)
2560       return -1;
2561 
2562     // If we found the tail of a vector the rotation must be the missing
2563     // front. If we found the head of a vector, it must be how much of the
2564     // head.
2565     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2566 
2567     if (Rotation == 0)
2568       Rotation = CandidateRotation;
2569     else if (Rotation != CandidateRotation)
2570       // The rotations don't match, so we can't match this mask.
2571       return -1;
2572 
2573     // Compute which value this mask is pointing at.
2574     int MaskSrc = M < Size ? 0 : 1;
2575 
2576     // Compute which of the two target values this index should be assigned to.
2577     // This reflects whether the high elements are remaining or the low elemnts
2578     // are remaining.
2579     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2580 
2581     // Either set up this value if we've not encountered it before, or check
2582     // that it remains consistent.
2583     if (TargetSrc < 0)
2584       TargetSrc = MaskSrc;
2585     else if (TargetSrc != MaskSrc)
2586       // This may be a rotation, but it pulls from the inputs in some
2587       // unsupported interleaving.
2588       return -1;
2589   }
2590 
2591   // Check that we successfully analyzed the mask, and normalize the results.
2592   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2593   assert((LoSrc >= 0 || HiSrc >= 0) &&
2594          "Failed to find a rotated input vector!");
2595 
2596   return Rotation;
2597 }
2598 
2599 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2600                                    const RISCVSubtarget &Subtarget) {
2601   SDValue V1 = Op.getOperand(0);
2602   SDValue V2 = Op.getOperand(1);
2603   SDLoc DL(Op);
2604   MVT XLenVT = Subtarget.getXLenVT();
2605   MVT VT = Op.getSimpleValueType();
2606   unsigned NumElts = VT.getVectorNumElements();
2607   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2608 
2609   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2610 
2611   SDValue TrueMask, VL;
2612   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2613 
2614   if (SVN->isSplat()) {
2615     const int Lane = SVN->getSplatIndex();
2616     if (Lane >= 0) {
2617       MVT SVT = VT.getVectorElementType();
2618 
2619       // Turn splatted vector load into a strided load with an X0 stride.
2620       SDValue V = V1;
2621       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2622       // with undef.
2623       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2624       int Offset = Lane;
2625       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2626         int OpElements =
2627             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2628         V = V.getOperand(Offset / OpElements);
2629         Offset %= OpElements;
2630       }
2631 
2632       // We need to ensure the load isn't atomic or volatile.
2633       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2634         auto *Ld = cast<LoadSDNode>(V);
2635         Offset *= SVT.getStoreSize();
2636         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2637                                                    TypeSize::Fixed(Offset), DL);
2638 
2639         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2640         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2641           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2642           SDValue IntID =
2643               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2644           SDValue Ops[] = {Ld->getChain(),
2645                            IntID,
2646                            DAG.getUNDEF(ContainerVT),
2647                            NewAddr,
2648                            DAG.getRegister(RISCV::X0, XLenVT),
2649                            VL};
2650           SDValue NewLoad = DAG.getMemIntrinsicNode(
2651               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2652               DAG.getMachineFunction().getMachineMemOperand(
2653                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2654           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2655           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2656         }
2657 
2658         // Otherwise use a scalar load and splat. This will give the best
2659         // opportunity to fold a splat into the operation. ISel can turn it into
2660         // the x0 strided load if we aren't able to fold away the select.
2661         if (SVT.isFloatingPoint())
2662           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2663                           Ld->getPointerInfo().getWithOffset(Offset),
2664                           Ld->getOriginalAlign(),
2665                           Ld->getMemOperand()->getFlags());
2666         else
2667           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2668                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2669                              Ld->getOriginalAlign(),
2670                              Ld->getMemOperand()->getFlags());
2671         DAG.makeEquivalentMemoryOrdering(Ld, V);
2672 
2673         unsigned Opc =
2674             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2675         SDValue Splat =
2676             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2677         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2678       }
2679 
2680       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2681       assert(Lane < (int)NumElts && "Unexpected lane!");
2682       SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT,
2683                                    V1, DAG.getConstant(Lane, DL, XLenVT),
2684                                    TrueMask, DAG.getUNDEF(ContainerVT), VL);
2685       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2686     }
2687   }
2688 
2689   ArrayRef<int> Mask = SVN->getMask();
2690 
2691   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2692   // be undef which can be handled with a single SLIDEDOWN/UP.
2693   int LoSrc, HiSrc;
2694   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2695   if (Rotation > 0) {
2696     SDValue LoV, HiV;
2697     if (LoSrc >= 0) {
2698       LoV = LoSrc == 0 ? V1 : V2;
2699       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2700     }
2701     if (HiSrc >= 0) {
2702       HiV = HiSrc == 0 ? V1 : V2;
2703       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2704     }
2705 
2706     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2707     // to slide LoV up by (NumElts - Rotation).
2708     unsigned InvRotate = NumElts - Rotation;
2709 
2710     SDValue Res = DAG.getUNDEF(ContainerVT);
2711     if (HiV) {
2712       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2713       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2714       // causes multiple vsetvlis in some test cases such as lowering
2715       // reduce.mul
2716       SDValue DownVL = VL;
2717       if (LoV)
2718         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2719       Res =
2720           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2721                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2722     }
2723     if (LoV)
2724       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2725                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2726 
2727     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2728   }
2729 
2730   // Detect an interleave shuffle and lower to
2731   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2732   bool SwapSources;
2733   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2734     // Swap sources if needed.
2735     if (SwapSources)
2736       std::swap(V1, V2);
2737 
2738     // Extract the lower half of the vectors.
2739     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2740     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2741                      DAG.getConstant(0, DL, XLenVT));
2742     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2743                      DAG.getConstant(0, DL, XLenVT));
2744 
2745     // Double the element width and halve the number of elements in an int type.
2746     unsigned EltBits = VT.getScalarSizeInBits();
2747     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2748     MVT WideIntVT =
2749         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2750     // Convert this to a scalable vector. We need to base this on the
2751     // destination size to ensure there's always a type with a smaller LMUL.
2752     MVT WideIntContainerVT =
2753         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2754 
2755     // Convert sources to scalable vectors with the same element count as the
2756     // larger type.
2757     MVT HalfContainerVT = MVT::getVectorVT(
2758         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2759     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2760     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2761 
2762     // Cast sources to integer.
2763     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2764     MVT IntHalfVT =
2765         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2766     V1 = DAG.getBitcast(IntHalfVT, V1);
2767     V2 = DAG.getBitcast(IntHalfVT, V2);
2768 
2769     // Freeze V2 since we use it twice and we need to be sure that the add and
2770     // multiply see the same value.
2771     V2 = DAG.getFreeze(V2);
2772 
2773     // Recreate TrueMask using the widened type's element count.
2774     TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG);
2775 
2776     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2777     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2778                               V2, TrueMask, VL);
2779     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2780     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2781                                      DAG.getUNDEF(IntHalfVT),
2782                                      DAG.getAllOnesConstant(DL, XLenVT));
2783     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2784                                    V2, Multiplier, TrueMask, VL);
2785     // Add the new copies to our previous addition giving us 2^eltbits copies of
2786     // V2. This is equivalent to shifting V2 left by eltbits. This should
2787     // combine with the vwmulu.vv above to form vwmaccu.vv.
2788     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2789                       TrueMask, VL);
2790     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2791     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2792     // vector VT.
2793     ContainerVT =
2794         MVT::getVectorVT(VT.getVectorElementType(),
2795                          WideIntContainerVT.getVectorElementCount() * 2);
2796     Add = DAG.getBitcast(ContainerVT, Add);
2797     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2798   }
2799 
2800   // Detect shuffles which can be re-expressed as vector selects; these are
2801   // shuffles in which each element in the destination is taken from an element
2802   // at the corresponding index in either source vectors.
2803   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2804     int MaskIndex = MaskIdx.value();
2805     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2806   });
2807 
2808   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2809 
2810   SmallVector<SDValue> MaskVals;
2811   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2812   // merged with a second vrgather.
2813   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2814 
2815   // By default we preserve the original operand order, and use a mask to
2816   // select LHS as true and RHS as false. However, since RVV vector selects may
2817   // feature splats but only on the LHS, we may choose to invert our mask and
2818   // instead select between RHS and LHS.
2819   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2820   bool InvertMask = IsSelect == SwapOps;
2821 
2822   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2823   // half.
2824   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2825 
2826   // Now construct the mask that will be used by the vselect or blended
2827   // vrgather operation. For vrgathers, construct the appropriate indices into
2828   // each vector.
2829   for (int MaskIndex : Mask) {
2830     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2831     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2832     if (!IsSelect) {
2833       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2834       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2835                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2836                                      : DAG.getUNDEF(XLenVT));
2837       GatherIndicesRHS.push_back(
2838           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2839                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2840       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2841         ++LHSIndexCounts[MaskIndex];
2842       if (!IsLHSOrUndefIndex)
2843         ++RHSIndexCounts[MaskIndex - NumElts];
2844     }
2845   }
2846 
2847   if (SwapOps) {
2848     std::swap(V1, V2);
2849     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2850   }
2851 
2852   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2853   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2854   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2855 
2856   if (IsSelect)
2857     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2858 
2859   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2860     // On such a large vector we're unable to use i8 as the index type.
2861     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2862     // may involve vector splitting if we're already at LMUL=8, or our
2863     // user-supplied maximum fixed-length LMUL.
2864     return SDValue();
2865   }
2866 
2867   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2868   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2869   MVT IndexVT = VT.changeTypeToInteger();
2870   // Since we can't introduce illegal index types at this stage, use i16 and
2871   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2872   // than XLenVT.
2873   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2874     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2875     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2876   }
2877 
2878   MVT IndexContainerVT =
2879       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2880 
2881   SDValue Gather;
2882   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2883   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2884   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2885     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2886                               Subtarget);
2887   } else {
2888     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2889     // If only one index is used, we can use a "splat" vrgather.
2890     // TODO: We can splat the most-common index and fix-up any stragglers, if
2891     // that's beneficial.
2892     if (LHSIndexCounts.size() == 1) {
2893       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2894       Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2895                            DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask,
2896                            DAG.getUNDEF(ContainerVT), VL);
2897     } else {
2898       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2899       LHSIndices =
2900           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2901 
2902       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2903                            TrueMask, DAG.getUNDEF(ContainerVT), VL);
2904     }
2905   }
2906 
2907   // If a second vector operand is used by this shuffle, blend it in with an
2908   // additional vrgather.
2909   if (!V2.isUndef()) {
2910     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2911 
2912     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2913     SelectMask =
2914         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2915 
2916     // If only one index is used, we can use a "splat" vrgather.
2917     // TODO: We can splat the most-common index and fix-up any stragglers, if
2918     // that's beneficial.
2919     if (RHSIndexCounts.size() == 1) {
2920       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2921       Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2922                            DAG.getConstant(SplatIndex, DL, XLenVT), SelectMask,
2923                            Gather, VL);
2924     } else {
2925       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2926       RHSIndices =
2927           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2928       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices,
2929                            SelectMask, Gather, VL);
2930     }
2931   }
2932 
2933   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2934 }
2935 
2936 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2937   // Support splats for any type. These should type legalize well.
2938   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2939     return true;
2940 
2941   // Only support legal VTs for other shuffles for now.
2942   if (!isTypeLegal(VT))
2943     return false;
2944 
2945   MVT SVT = VT.getSimpleVT();
2946 
2947   bool SwapSources;
2948   int LoSrc, HiSrc;
2949   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2950          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2951 }
2952 
2953 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2954 // the exponent.
2955 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2956   MVT VT = Op.getSimpleValueType();
2957   unsigned EltSize = VT.getScalarSizeInBits();
2958   SDValue Src = Op.getOperand(0);
2959   SDLoc DL(Op);
2960 
2961   // We need a FP type that can represent the value.
2962   // TODO: Use f16 for i8 when possible?
2963   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2964   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2965 
2966   // Legal types should have been checked in the RISCVTargetLowering
2967   // constructor.
2968   // TODO: Splitting may make sense in some cases.
2969   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2970          "Expected legal float type!");
2971 
2972   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2973   // The trailing zero count is equal to log2 of this single bit value.
2974   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2975     SDValue Neg =
2976         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2977     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2978   }
2979 
2980   // We have a legal FP type, convert to it.
2981   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2982   // Bitcast to integer and shift the exponent to the LSB.
2983   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2984   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2985   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2986   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2987                               DAG.getConstant(ShiftAmt, DL, IntVT));
2988   // Truncate back to original type to allow vnsrl.
2989   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2990   // The exponent contains log2 of the value in biased form.
2991   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2992 
2993   // For trailing zeros, we just need to subtract the bias.
2994   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2995     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2996                        DAG.getConstant(ExponentBias, DL, VT));
2997 
2998   // For leading zeros, we need to remove the bias and convert from log2 to
2999   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
3000   unsigned Adjust = ExponentBias + (EltSize - 1);
3001   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
3002 }
3003 
3004 // While RVV has alignment restrictions, we should always be able to load as a
3005 // legal equivalently-sized byte-typed vector instead. This method is
3006 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
3007 // the load is already correctly-aligned, it returns SDValue().
3008 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
3009                                                     SelectionDAG &DAG) const {
3010   auto *Load = cast<LoadSDNode>(Op);
3011   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
3012 
3013   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3014                                      Load->getMemoryVT(),
3015                                      *Load->getMemOperand()))
3016     return SDValue();
3017 
3018   SDLoc DL(Op);
3019   MVT VT = Op.getSimpleValueType();
3020   unsigned EltSizeBits = VT.getScalarSizeInBits();
3021   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3022          "Unexpected unaligned RVV load type");
3023   MVT NewVT =
3024       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3025   assert(NewVT.isValid() &&
3026          "Expecting equally-sized RVV vector types to be legal");
3027   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
3028                           Load->getPointerInfo(), Load->getOriginalAlign(),
3029                           Load->getMemOperand()->getFlags());
3030   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
3031 }
3032 
3033 // While RVV has alignment restrictions, we should always be able to store as a
3034 // legal equivalently-sized byte-typed vector instead. This method is
3035 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
3036 // returns SDValue() if the store is already correctly aligned.
3037 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
3038                                                      SelectionDAG &DAG) const {
3039   auto *Store = cast<StoreSDNode>(Op);
3040   assert(Store && Store->getValue().getValueType().isVector() &&
3041          "Expected vector store");
3042 
3043   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3044                                      Store->getMemoryVT(),
3045                                      *Store->getMemOperand()))
3046     return SDValue();
3047 
3048   SDLoc DL(Op);
3049   SDValue StoredVal = Store->getValue();
3050   MVT VT = StoredVal.getSimpleValueType();
3051   unsigned EltSizeBits = VT.getScalarSizeInBits();
3052   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3053          "Unexpected unaligned RVV store type");
3054   MVT NewVT =
3055       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3056   assert(NewVT.isValid() &&
3057          "Expecting equally-sized RVV vector types to be legal");
3058   StoredVal = DAG.getBitcast(NewVT, StoredVal);
3059   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
3060                       Store->getPointerInfo(), Store->getOriginalAlign(),
3061                       Store->getMemOperand()->getFlags());
3062 }
3063 
3064 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG,
3065                              const RISCVSubtarget &Subtarget) {
3066   assert(Op.getValueType() == MVT::i64 && "Unexpected VT");
3067 
3068   int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue();
3069 
3070   // All simm32 constants should be handled by isel.
3071   // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making
3072   // this check redundant, but small immediates are common so this check
3073   // should have better compile time.
3074   if (isInt<32>(Imm))
3075     return Op;
3076 
3077   // We only need to cost the immediate, if constant pool lowering is enabled.
3078   if (!Subtarget.useConstantPoolForLargeInts())
3079     return Op;
3080 
3081   RISCVMatInt::InstSeq Seq =
3082       RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits());
3083   if (Seq.size() <= Subtarget.getMaxBuildIntsCost())
3084     return Op;
3085 
3086   // Expand to a constant pool using the default expansion code.
3087   return SDValue();
3088 }
3089 
3090 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
3091                                             SelectionDAG &DAG) const {
3092   switch (Op.getOpcode()) {
3093   default:
3094     report_fatal_error("unimplemented operand");
3095   case ISD::GlobalAddress:
3096     return lowerGlobalAddress(Op, DAG);
3097   case ISD::BlockAddress:
3098     return lowerBlockAddress(Op, DAG);
3099   case ISD::ConstantPool:
3100     return lowerConstantPool(Op, DAG);
3101   case ISD::JumpTable:
3102     return lowerJumpTable(Op, DAG);
3103   case ISD::GlobalTLSAddress:
3104     return lowerGlobalTLSAddress(Op, DAG);
3105   case ISD::Constant:
3106     return lowerConstant(Op, DAG, Subtarget);
3107   case ISD::SELECT:
3108     return lowerSELECT(Op, DAG);
3109   case ISD::BRCOND:
3110     return lowerBRCOND(Op, DAG);
3111   case ISD::VASTART:
3112     return lowerVASTART(Op, DAG);
3113   case ISD::FRAMEADDR:
3114     return lowerFRAMEADDR(Op, DAG);
3115   case ISD::RETURNADDR:
3116     return lowerRETURNADDR(Op, DAG);
3117   case ISD::SHL_PARTS:
3118     return lowerShiftLeftParts(Op, DAG);
3119   case ISD::SRA_PARTS:
3120     return lowerShiftRightParts(Op, DAG, true);
3121   case ISD::SRL_PARTS:
3122     return lowerShiftRightParts(Op, DAG, false);
3123   case ISD::BITCAST: {
3124     SDLoc DL(Op);
3125     EVT VT = Op.getValueType();
3126     SDValue Op0 = Op.getOperand(0);
3127     EVT Op0VT = Op0.getValueType();
3128     MVT XLenVT = Subtarget.getXLenVT();
3129     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3130       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3131       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3132       return FPConv;
3133     }
3134     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3135         Subtarget.hasStdExtF()) {
3136       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3137       SDValue FPConv =
3138           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3139       return FPConv;
3140     }
3141 
3142     // Consider other scalar<->scalar casts as legal if the types are legal.
3143     // Otherwise expand them.
3144     if (!VT.isVector() && !Op0VT.isVector()) {
3145       if (isTypeLegal(VT) && isTypeLegal(Op0VT))
3146         return Op;
3147       return SDValue();
3148     }
3149 
3150     assert(!VT.isScalableVector() && !Op0VT.isScalableVector() &&
3151            "Unexpected types");
3152 
3153     if (VT.isFixedLengthVector()) {
3154       // We can handle fixed length vector bitcasts with a simple replacement
3155       // in isel.
3156       if (Op0VT.isFixedLengthVector())
3157         return Op;
3158       // When bitcasting from scalar to fixed-length vector, insert the scalar
3159       // into a one-element vector of the result type, and perform a vector
3160       // bitcast.
3161       if (!Op0VT.isVector()) {
3162         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3163         if (!isTypeLegal(BVT))
3164           return SDValue();
3165         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3166                                               DAG.getUNDEF(BVT), Op0,
3167                                               DAG.getConstant(0, DL, XLenVT)));
3168       }
3169       return SDValue();
3170     }
3171     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3172     // thus: bitcast the vector to a one-element vector type whose element type
3173     // is the same as the result type, and extract the first element.
3174     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3175       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3176       if (!isTypeLegal(BVT))
3177         return SDValue();
3178       SDValue BVec = DAG.getBitcast(BVT, Op0);
3179       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3180                          DAG.getConstant(0, DL, XLenVT));
3181     }
3182     return SDValue();
3183   }
3184   case ISD::INTRINSIC_WO_CHAIN:
3185     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3186   case ISD::INTRINSIC_W_CHAIN:
3187     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3188   case ISD::INTRINSIC_VOID:
3189     return LowerINTRINSIC_VOID(Op, DAG);
3190   case ISD::BSWAP:
3191   case ISD::BITREVERSE: {
3192     MVT VT = Op.getSimpleValueType();
3193     SDLoc DL(Op);
3194     if (Subtarget.hasStdExtZbp()) {
3195       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3196       // Start with the maximum immediate value which is the bitwidth - 1.
3197       unsigned Imm = VT.getSizeInBits() - 1;
3198       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3199       if (Op.getOpcode() == ISD::BSWAP)
3200         Imm &= ~0x7U;
3201       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3202                          DAG.getConstant(Imm, DL, VT));
3203     }
3204     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3205     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3206     // Expand bitreverse to a bswap(rev8) followed by brev8.
3207     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3208     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3209     // as brev8 by an isel pattern.
3210     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3211                        DAG.getConstant(7, DL, VT));
3212   }
3213   case ISD::FSHL:
3214   case ISD::FSHR: {
3215     MVT VT = Op.getSimpleValueType();
3216     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3217     SDLoc DL(Op);
3218     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3219     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3220     // accidentally setting the extra bit.
3221     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3222     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3223                                 DAG.getConstant(ShAmtWidth, DL, VT));
3224     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3225     // instruction use different orders. fshl will return its first operand for
3226     // shift of zero, fshr will return its second operand. fsl and fsr both
3227     // return rs1 so the ISD nodes need to have different operand orders.
3228     // Shift amount is in rs2.
3229     SDValue Op0 = Op.getOperand(0);
3230     SDValue Op1 = Op.getOperand(1);
3231     unsigned Opc = RISCVISD::FSL;
3232     if (Op.getOpcode() == ISD::FSHR) {
3233       std::swap(Op0, Op1);
3234       Opc = RISCVISD::FSR;
3235     }
3236     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3237   }
3238   case ISD::TRUNCATE:
3239     // Only custom-lower vector truncates
3240     if (!Op.getSimpleValueType().isVector())
3241       return Op;
3242     return lowerVectorTruncLike(Op, DAG);
3243   case ISD::ANY_EXTEND:
3244   case ISD::ZERO_EXTEND:
3245     if (Op.getOperand(0).getValueType().isVector() &&
3246         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3247       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3248     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3249   case ISD::SIGN_EXTEND:
3250     if (Op.getOperand(0).getValueType().isVector() &&
3251         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3252       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3253     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3254   case ISD::SPLAT_VECTOR_PARTS:
3255     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3256   case ISD::INSERT_VECTOR_ELT:
3257     return lowerINSERT_VECTOR_ELT(Op, DAG);
3258   case ISD::EXTRACT_VECTOR_ELT:
3259     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3260   case ISD::VSCALE: {
3261     MVT VT = Op.getSimpleValueType();
3262     SDLoc DL(Op);
3263     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3264     // We define our scalable vector types for lmul=1 to use a 64 bit known
3265     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3266     // vscale as VLENB / 8.
3267     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3268     if (Subtarget.getRealMinVLen() < RISCV::RVVBitsPerBlock)
3269       report_fatal_error("Support for VLEN==32 is incomplete.");
3270     // We assume VLENB is a multiple of 8. We manually choose the best shift
3271     // here because SimplifyDemandedBits isn't always able to simplify it.
3272     uint64_t Val = Op.getConstantOperandVal(0);
3273     if (isPowerOf2_64(Val)) {
3274       uint64_t Log2 = Log2_64(Val);
3275       if (Log2 < 3)
3276         return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3277                            DAG.getConstant(3 - Log2, DL, VT));
3278       if (Log2 > 3)
3279         return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3280                            DAG.getConstant(Log2 - 3, DL, VT));
3281       return VLENB;
3282     }
3283     // If the multiplier is a multiple of 8, scale it down to avoid needing
3284     // to shift the VLENB value.
3285     if ((Val % 8) == 0)
3286       return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3287                          DAG.getConstant(Val / 8, DL, VT));
3288 
3289     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3290                                  DAG.getConstant(3, DL, VT));
3291     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3292   }
3293   case ISD::FPOWI: {
3294     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3295     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3296     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3297         Op.getOperand(1).getValueType() == MVT::i32) {
3298       SDLoc DL(Op);
3299       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3300       SDValue Powi =
3301           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3302       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3303                          DAG.getIntPtrConstant(0, DL));
3304     }
3305     return SDValue();
3306   }
3307   case ISD::FP_EXTEND:
3308   case ISD::FP_ROUND:
3309     if (!Op.getValueType().isVector())
3310       return Op;
3311     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3312   case ISD::FP_TO_SINT:
3313   case ISD::FP_TO_UINT:
3314   case ISD::SINT_TO_FP:
3315   case ISD::UINT_TO_FP: {
3316     // RVV can only do fp<->int conversions to types half/double the size as
3317     // the source. We custom-lower any conversions that do two hops into
3318     // sequences.
3319     MVT VT = Op.getSimpleValueType();
3320     if (!VT.isVector())
3321       return Op;
3322     SDLoc DL(Op);
3323     SDValue Src = Op.getOperand(0);
3324     MVT EltVT = VT.getVectorElementType();
3325     MVT SrcVT = Src.getSimpleValueType();
3326     MVT SrcEltVT = SrcVT.getVectorElementType();
3327     unsigned EltSize = EltVT.getSizeInBits();
3328     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3329     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3330            "Unexpected vector element types");
3331 
3332     bool IsInt2FP = SrcEltVT.isInteger();
3333     // Widening conversions
3334     if (EltSize > (2 * SrcEltSize)) {
3335       if (IsInt2FP) {
3336         // Do a regular integer sign/zero extension then convert to float.
3337         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize),
3338                                       VT.getVectorElementCount());
3339         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3340                                  ? ISD::ZERO_EXTEND
3341                                  : ISD::SIGN_EXTEND;
3342         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3343         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3344       }
3345       // FP2Int
3346       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3347       // Do one doubling fp_extend then complete the operation by converting
3348       // to int.
3349       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3350       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3351       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3352     }
3353 
3354     // Narrowing conversions
3355     if (SrcEltSize > (2 * EltSize)) {
3356       if (IsInt2FP) {
3357         // One narrowing int_to_fp, then an fp_round.
3358         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3359         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3360         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3361         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3362       }
3363       // FP2Int
3364       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3365       // representable by the integer, the result is poison.
3366       MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
3367                                     VT.getVectorElementCount());
3368       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3369       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3370     }
3371 
3372     // Scalable vectors can exit here. Patterns will handle equally-sized
3373     // conversions halving/doubling ones.
3374     if (!VT.isFixedLengthVector())
3375       return Op;
3376 
3377     // For fixed-length vectors we lower to a custom "VL" node.
3378     unsigned RVVOpc = 0;
3379     switch (Op.getOpcode()) {
3380     default:
3381       llvm_unreachable("Impossible opcode");
3382     case ISD::FP_TO_SINT:
3383       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3384       break;
3385     case ISD::FP_TO_UINT:
3386       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3387       break;
3388     case ISD::SINT_TO_FP:
3389       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3390       break;
3391     case ISD::UINT_TO_FP:
3392       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3393       break;
3394     }
3395 
3396     MVT ContainerVT, SrcContainerVT;
3397     // Derive the reference container type from the larger vector type.
3398     if (SrcEltSize > EltSize) {
3399       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3400       ContainerVT =
3401           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3402     } else {
3403       ContainerVT = getContainerForFixedLengthVector(VT);
3404       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3405     }
3406 
3407     SDValue Mask, VL;
3408     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3409 
3410     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3411     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3412     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3413   }
3414   case ISD::FP_TO_SINT_SAT:
3415   case ISD::FP_TO_UINT_SAT:
3416     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3417   case ISD::FTRUNC:
3418   case ISD::FCEIL:
3419   case ISD::FFLOOR:
3420     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3421   case ISD::FROUND:
3422     return lowerFROUND(Op, DAG);
3423   case ISD::VECREDUCE_ADD:
3424   case ISD::VECREDUCE_UMAX:
3425   case ISD::VECREDUCE_SMAX:
3426   case ISD::VECREDUCE_UMIN:
3427   case ISD::VECREDUCE_SMIN:
3428     return lowerVECREDUCE(Op, DAG);
3429   case ISD::VECREDUCE_AND:
3430   case ISD::VECREDUCE_OR:
3431   case ISD::VECREDUCE_XOR:
3432     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3433       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3434     return lowerVECREDUCE(Op, DAG);
3435   case ISD::VECREDUCE_FADD:
3436   case ISD::VECREDUCE_SEQ_FADD:
3437   case ISD::VECREDUCE_FMIN:
3438   case ISD::VECREDUCE_FMAX:
3439     return lowerFPVECREDUCE(Op, DAG);
3440   case ISD::VP_REDUCE_ADD:
3441   case ISD::VP_REDUCE_UMAX:
3442   case ISD::VP_REDUCE_SMAX:
3443   case ISD::VP_REDUCE_UMIN:
3444   case ISD::VP_REDUCE_SMIN:
3445   case ISD::VP_REDUCE_FADD:
3446   case ISD::VP_REDUCE_SEQ_FADD:
3447   case ISD::VP_REDUCE_FMIN:
3448   case ISD::VP_REDUCE_FMAX:
3449     return lowerVPREDUCE(Op, DAG);
3450   case ISD::VP_REDUCE_AND:
3451   case ISD::VP_REDUCE_OR:
3452   case ISD::VP_REDUCE_XOR:
3453     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3454       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3455     return lowerVPREDUCE(Op, DAG);
3456   case ISD::INSERT_SUBVECTOR:
3457     return lowerINSERT_SUBVECTOR(Op, DAG);
3458   case ISD::EXTRACT_SUBVECTOR:
3459     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3460   case ISD::STEP_VECTOR:
3461     return lowerSTEP_VECTOR(Op, DAG);
3462   case ISD::VECTOR_REVERSE:
3463     return lowerVECTOR_REVERSE(Op, DAG);
3464   case ISD::VECTOR_SPLICE:
3465     return lowerVECTOR_SPLICE(Op, DAG);
3466   case ISD::BUILD_VECTOR:
3467     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3468   case ISD::SPLAT_VECTOR:
3469     if (Op.getValueType().getVectorElementType() == MVT::i1)
3470       return lowerVectorMaskSplat(Op, DAG);
3471     return SDValue();
3472   case ISD::VECTOR_SHUFFLE:
3473     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3474   case ISD::CONCAT_VECTORS: {
3475     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3476     // better than going through the stack, as the default expansion does.
3477     SDLoc DL(Op);
3478     MVT VT = Op.getSimpleValueType();
3479     unsigned NumOpElts =
3480         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3481     SDValue Vec = DAG.getUNDEF(VT);
3482     for (const auto &OpIdx : enumerate(Op->ops())) {
3483       SDValue SubVec = OpIdx.value();
3484       // Don't insert undef subvectors.
3485       if (SubVec.isUndef())
3486         continue;
3487       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3488                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3489     }
3490     return Vec;
3491   }
3492   case ISD::LOAD:
3493     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3494       return V;
3495     if (Op.getValueType().isFixedLengthVector())
3496       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3497     return Op;
3498   case ISD::STORE:
3499     if (auto V = expandUnalignedRVVStore(Op, DAG))
3500       return V;
3501     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3502       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3503     return Op;
3504   case ISD::MLOAD:
3505   case ISD::VP_LOAD:
3506     return lowerMaskedLoad(Op, DAG);
3507   case ISD::MSTORE:
3508   case ISD::VP_STORE:
3509     return lowerMaskedStore(Op, DAG);
3510   case ISD::SETCC:
3511     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3512   case ISD::ADD:
3513     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3514   case ISD::SUB:
3515     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3516   case ISD::MUL:
3517     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3518   case ISD::MULHS:
3519     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3520   case ISD::MULHU:
3521     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3522   case ISD::AND:
3523     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3524                                               RISCVISD::AND_VL);
3525   case ISD::OR:
3526     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3527                                               RISCVISD::OR_VL);
3528   case ISD::XOR:
3529     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3530                                               RISCVISD::XOR_VL);
3531   case ISD::SDIV:
3532     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3533   case ISD::SREM:
3534     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3535   case ISD::UDIV:
3536     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3537   case ISD::UREM:
3538     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3539   case ISD::SHL:
3540   case ISD::SRA:
3541   case ISD::SRL:
3542     if (Op.getSimpleValueType().isFixedLengthVector())
3543       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3544     // This can be called for an i32 shift amount that needs to be promoted.
3545     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3546            "Unexpected custom legalisation");
3547     return SDValue();
3548   case ISD::SADDSAT:
3549     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3550   case ISD::UADDSAT:
3551     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3552   case ISD::SSUBSAT:
3553     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3554   case ISD::USUBSAT:
3555     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3556   case ISD::FADD:
3557     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3558   case ISD::FSUB:
3559     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3560   case ISD::FMUL:
3561     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3562   case ISD::FDIV:
3563     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3564   case ISD::FNEG:
3565     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3566   case ISD::FABS:
3567     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3568   case ISD::FSQRT:
3569     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3570   case ISD::FMA:
3571     return lowerToScalableOp(Op, DAG, RISCVISD::VFMADD_VL);
3572   case ISD::SMIN:
3573     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3574   case ISD::SMAX:
3575     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3576   case ISD::UMIN:
3577     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3578   case ISD::UMAX:
3579     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3580   case ISD::FMINNUM:
3581     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3582   case ISD::FMAXNUM:
3583     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3584   case ISD::ABS:
3585     return lowerABS(Op, DAG);
3586   case ISD::CTLZ_ZERO_UNDEF:
3587   case ISD::CTTZ_ZERO_UNDEF:
3588     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3589   case ISD::VSELECT:
3590     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3591   case ISD::FCOPYSIGN:
3592     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3593   case ISD::MGATHER:
3594   case ISD::VP_GATHER:
3595     return lowerMaskedGather(Op, DAG);
3596   case ISD::MSCATTER:
3597   case ISD::VP_SCATTER:
3598     return lowerMaskedScatter(Op, DAG);
3599   case ISD::FLT_ROUNDS_:
3600     return lowerGET_ROUNDING(Op, DAG);
3601   case ISD::SET_ROUNDING:
3602     return lowerSET_ROUNDING(Op, DAG);
3603   case ISD::EH_DWARF_CFA:
3604     return lowerEH_DWARF_CFA(Op, DAG);
3605   case ISD::VP_SELECT:
3606     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3607   case ISD::VP_MERGE:
3608     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3609   case ISD::VP_ADD:
3610     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3611   case ISD::VP_SUB:
3612     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3613   case ISD::VP_MUL:
3614     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3615   case ISD::VP_SDIV:
3616     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3617   case ISD::VP_UDIV:
3618     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3619   case ISD::VP_SREM:
3620     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3621   case ISD::VP_UREM:
3622     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3623   case ISD::VP_AND:
3624     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3625   case ISD::VP_OR:
3626     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3627   case ISD::VP_XOR:
3628     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3629   case ISD::VP_ASHR:
3630     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3631   case ISD::VP_LSHR:
3632     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3633   case ISD::VP_SHL:
3634     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3635   case ISD::VP_FADD:
3636     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3637   case ISD::VP_FSUB:
3638     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3639   case ISD::VP_FMUL:
3640     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3641   case ISD::VP_FDIV:
3642     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3643   case ISD::VP_FNEG:
3644     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3645   case ISD::VP_FMA:
3646     return lowerVPOp(Op, DAG, RISCVISD::VFMADD_VL);
3647   case ISD::VP_SIGN_EXTEND:
3648   case ISD::VP_ZERO_EXTEND:
3649     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3650       return lowerVPExtMaskOp(Op, DAG);
3651     return lowerVPOp(Op, DAG,
3652                      Op.getOpcode() == ISD::VP_SIGN_EXTEND
3653                          ? RISCVISD::VSEXT_VL
3654                          : RISCVISD::VZEXT_VL);
3655   case ISD::VP_TRUNCATE:
3656     return lowerVectorTruncLike(Op, DAG);
3657   case ISD::VP_FP_EXTEND:
3658   case ISD::VP_FP_ROUND:
3659     return lowerVectorFPExtendOrRoundLike(Op, DAG);
3660   case ISD::VP_FPTOSI:
3661     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL);
3662   case ISD::VP_FPTOUI:
3663     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL);
3664   case ISD::VP_SITOFP:
3665     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
3666   case ISD::VP_UITOFP:
3667     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL);
3668   case ISD::VP_SETCC:
3669     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3670       return lowerVPSetCCMaskOp(Op, DAG);
3671     return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL);
3672   }
3673 }
3674 
3675 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3676                              SelectionDAG &DAG, unsigned Flags) {
3677   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3678 }
3679 
3680 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3681                              SelectionDAG &DAG, unsigned Flags) {
3682   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3683                                    Flags);
3684 }
3685 
3686 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3687                              SelectionDAG &DAG, unsigned Flags) {
3688   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3689                                    N->getOffset(), Flags);
3690 }
3691 
3692 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3693                              SelectionDAG &DAG, unsigned Flags) {
3694   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3695 }
3696 
3697 template <class NodeTy>
3698 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3699                                      bool IsLocal) const {
3700   SDLoc DL(N);
3701   EVT Ty = getPointerTy(DAG.getDataLayout());
3702 
3703   if (isPositionIndependent()) {
3704     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3705     if (IsLocal)
3706       // Use PC-relative addressing to access the symbol. This generates the
3707       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3708       // %pcrel_lo(auipc)).
3709       return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
3710 
3711     // Use PC-relative addressing to access the GOT for this symbol, then load
3712     // the address from the GOT. This generates the pattern (PseudoLA sym),
3713     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3714     MachineFunction &MF = DAG.getMachineFunction();
3715     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3716         MachinePointerInfo::getGOT(MF),
3717         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3718             MachineMemOperand::MOInvariant,
3719         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3720     SDValue Load =
3721         DAG.getMemIntrinsicNode(RISCVISD::LA, DL, DAG.getVTList(Ty, MVT::Other),
3722                                 {DAG.getEntryNode(), Addr}, Ty, MemOp);
3723     return Load;
3724   }
3725 
3726   switch (getTargetMachine().getCodeModel()) {
3727   default:
3728     report_fatal_error("Unsupported code model for lowering");
3729   case CodeModel::Small: {
3730     // Generate a sequence for accessing addresses within the first 2 GiB of
3731     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3732     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3733     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3734     SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
3735     return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo);
3736   }
3737   case CodeModel::Medium: {
3738     // Generate a sequence for accessing addresses within any 2GiB range within
3739     // the address space. This generates the pattern (PseudoLLA sym), which
3740     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3741     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3742     return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
3743   }
3744   }
3745 }
3746 
3747 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3748                                                 SelectionDAG &DAG) const {
3749   SDLoc DL(Op);
3750   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3751   assert(N->getOffset() == 0 && "unexpected offset in global node");
3752   return getAddr(N, DAG, N->getGlobal()->isDSOLocal());
3753 }
3754 
3755 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3756                                                SelectionDAG &DAG) const {
3757   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3758 
3759   return getAddr(N, DAG);
3760 }
3761 
3762 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3763                                                SelectionDAG &DAG) const {
3764   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3765 
3766   return getAddr(N, DAG);
3767 }
3768 
3769 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3770                                             SelectionDAG &DAG) const {
3771   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3772 
3773   return getAddr(N, DAG);
3774 }
3775 
3776 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3777                                               SelectionDAG &DAG,
3778                                               bool UseGOT) const {
3779   SDLoc DL(N);
3780   EVT Ty = getPointerTy(DAG.getDataLayout());
3781   const GlobalValue *GV = N->getGlobal();
3782   MVT XLenVT = Subtarget.getXLenVT();
3783 
3784   if (UseGOT) {
3785     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3786     // load the address from the GOT and add the thread pointer. This generates
3787     // the pattern (PseudoLA_TLS_IE sym), which expands to
3788     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3789     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3790     MachineFunction &MF = DAG.getMachineFunction();
3791     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3792         MachinePointerInfo::getGOT(MF),
3793         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3794             MachineMemOperand::MOInvariant,
3795         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3796     SDValue Load = DAG.getMemIntrinsicNode(
3797         RISCVISD::LA_TLS_IE, DL, DAG.getVTList(Ty, MVT::Other),
3798         {DAG.getEntryNode(), Addr}, Ty, MemOp);
3799 
3800     // Add the thread pointer.
3801     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3802     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3803   }
3804 
3805   // Generate a sequence for accessing the address relative to the thread
3806   // pointer, with the appropriate adjustment for the thread pointer offset.
3807   // This generates the pattern
3808   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3809   SDValue AddrHi =
3810       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3811   SDValue AddrAdd =
3812       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3813   SDValue AddrLo =
3814       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3815 
3816   SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
3817   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3818   SDValue MNAdd =
3819       DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd);
3820   return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo);
3821 }
3822 
3823 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3824                                                SelectionDAG &DAG) const {
3825   SDLoc DL(N);
3826   EVT Ty = getPointerTy(DAG.getDataLayout());
3827   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3828   const GlobalValue *GV = N->getGlobal();
3829 
3830   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3831   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3832   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3833   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3834   SDValue Load = DAG.getNode(RISCVISD::LA_TLS_GD, DL, Ty, Addr);
3835 
3836   // Prepare argument list to generate call.
3837   ArgListTy Args;
3838   ArgListEntry Entry;
3839   Entry.Node = Load;
3840   Entry.Ty = CallTy;
3841   Args.push_back(Entry);
3842 
3843   // Setup call to __tls_get_addr.
3844   TargetLowering::CallLoweringInfo CLI(DAG);
3845   CLI.setDebugLoc(DL)
3846       .setChain(DAG.getEntryNode())
3847       .setLibCallee(CallingConv::C, CallTy,
3848                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3849                     std::move(Args));
3850 
3851   return LowerCallTo(CLI).first;
3852 }
3853 
3854 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3855                                                    SelectionDAG &DAG) const {
3856   SDLoc DL(Op);
3857   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3858   assert(N->getOffset() == 0 && "unexpected offset in global node");
3859 
3860   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3861 
3862   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3863       CallingConv::GHC)
3864     report_fatal_error("In GHC calling convention TLS is not supported");
3865 
3866   SDValue Addr;
3867   switch (Model) {
3868   case TLSModel::LocalExec:
3869     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3870     break;
3871   case TLSModel::InitialExec:
3872     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3873     break;
3874   case TLSModel::LocalDynamic:
3875   case TLSModel::GeneralDynamic:
3876     Addr = getDynamicTLSAddr(N, DAG);
3877     break;
3878   }
3879 
3880   return Addr;
3881 }
3882 
3883 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3884   SDValue CondV = Op.getOperand(0);
3885   SDValue TrueV = Op.getOperand(1);
3886   SDValue FalseV = Op.getOperand(2);
3887   SDLoc DL(Op);
3888   MVT VT = Op.getSimpleValueType();
3889   MVT XLenVT = Subtarget.getXLenVT();
3890 
3891   // Lower vector SELECTs to VSELECTs by splatting the condition.
3892   if (VT.isVector()) {
3893     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3894     SDValue CondSplat = VT.isScalableVector()
3895                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3896                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3897     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3898   }
3899 
3900   // If the result type is XLenVT and CondV is the output of a SETCC node
3901   // which also operated on XLenVT inputs, then merge the SETCC node into the
3902   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3903   // compare+branch instructions. i.e.:
3904   // (select (setcc lhs, rhs, cc), truev, falsev)
3905   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3906   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3907       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3908     SDValue LHS = CondV.getOperand(0);
3909     SDValue RHS = CondV.getOperand(1);
3910     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3911     ISD::CondCode CCVal = CC->get();
3912 
3913     // Special case for a select of 2 constants that have a diffence of 1.
3914     // Normally this is done by DAGCombine, but if the select is introduced by
3915     // type legalization or op legalization, we miss it. Restricting to SETLT
3916     // case for now because that is what signed saturating add/sub need.
3917     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3918     // but we would probably want to swap the true/false values if the condition
3919     // is SETGE/SETLE to avoid an XORI.
3920     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3921         CCVal == ISD::SETLT) {
3922       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3923       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3924       if (TrueVal - 1 == FalseVal)
3925         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3926       if (TrueVal + 1 == FalseVal)
3927         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3928     }
3929 
3930     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3931 
3932     SDValue TargetCC = DAG.getCondCode(CCVal);
3933     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3934     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3935   }
3936 
3937   // Otherwise:
3938   // (select condv, truev, falsev)
3939   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3940   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3941   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3942 
3943   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3944 
3945   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3946 }
3947 
3948 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3949   SDValue CondV = Op.getOperand(1);
3950   SDLoc DL(Op);
3951   MVT XLenVT = Subtarget.getXLenVT();
3952 
3953   if (CondV.getOpcode() == ISD::SETCC &&
3954       CondV.getOperand(0).getValueType() == XLenVT) {
3955     SDValue LHS = CondV.getOperand(0);
3956     SDValue RHS = CondV.getOperand(1);
3957     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3958 
3959     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3960 
3961     SDValue TargetCC = DAG.getCondCode(CCVal);
3962     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3963                        LHS, RHS, TargetCC, Op.getOperand(2));
3964   }
3965 
3966   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3967                      CondV, DAG.getConstant(0, DL, XLenVT),
3968                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3969 }
3970 
3971 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3972   MachineFunction &MF = DAG.getMachineFunction();
3973   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3974 
3975   SDLoc DL(Op);
3976   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3977                                  getPointerTy(MF.getDataLayout()));
3978 
3979   // vastart just stores the address of the VarArgsFrameIndex slot into the
3980   // memory location argument.
3981   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3982   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3983                       MachinePointerInfo(SV));
3984 }
3985 
3986 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3987                                             SelectionDAG &DAG) const {
3988   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3989   MachineFunction &MF = DAG.getMachineFunction();
3990   MachineFrameInfo &MFI = MF.getFrameInfo();
3991   MFI.setFrameAddressIsTaken(true);
3992   Register FrameReg = RI.getFrameRegister(MF);
3993   int XLenInBytes = Subtarget.getXLen() / 8;
3994 
3995   EVT VT = Op.getValueType();
3996   SDLoc DL(Op);
3997   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3998   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3999   while (Depth--) {
4000     int Offset = -(XLenInBytes * 2);
4001     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
4002                               DAG.getIntPtrConstant(Offset, DL));
4003     FrameAddr =
4004         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
4005   }
4006   return FrameAddr;
4007 }
4008 
4009 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
4010                                              SelectionDAG &DAG) const {
4011   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4012   MachineFunction &MF = DAG.getMachineFunction();
4013   MachineFrameInfo &MFI = MF.getFrameInfo();
4014   MFI.setReturnAddressIsTaken(true);
4015   MVT XLenVT = Subtarget.getXLenVT();
4016   int XLenInBytes = Subtarget.getXLen() / 8;
4017 
4018   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4019     return SDValue();
4020 
4021   EVT VT = Op.getValueType();
4022   SDLoc DL(Op);
4023   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4024   if (Depth) {
4025     int Off = -XLenInBytes;
4026     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4027     SDValue Offset = DAG.getConstant(Off, DL, VT);
4028     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4029                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4030                        MachinePointerInfo());
4031   }
4032 
4033   // Return the value of the return address register, marking it an implicit
4034   // live-in.
4035   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
4036   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
4037 }
4038 
4039 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
4040                                                  SelectionDAG &DAG) const {
4041   SDLoc DL(Op);
4042   SDValue Lo = Op.getOperand(0);
4043   SDValue Hi = Op.getOperand(1);
4044   SDValue Shamt = Op.getOperand(2);
4045   EVT VT = Lo.getValueType();
4046 
4047   // if Shamt-XLEN < 0: // Shamt < XLEN
4048   //   Lo = Lo << Shamt
4049   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
4050   // else:
4051   //   Lo = 0
4052   //   Hi = Lo << (Shamt-XLEN)
4053 
4054   SDValue Zero = DAG.getConstant(0, DL, VT);
4055   SDValue One = DAG.getConstant(1, DL, VT);
4056   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4057   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4058   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4059   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4060 
4061   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
4062   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
4063   SDValue ShiftRightLo =
4064       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
4065   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
4066   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
4067   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
4068 
4069   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4070 
4071   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
4072   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4073 
4074   SDValue Parts[2] = {Lo, Hi};
4075   return DAG.getMergeValues(Parts, DL);
4076 }
4077 
4078 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
4079                                                   bool IsSRA) const {
4080   SDLoc DL(Op);
4081   SDValue Lo = Op.getOperand(0);
4082   SDValue Hi = Op.getOperand(1);
4083   SDValue Shamt = Op.getOperand(2);
4084   EVT VT = Lo.getValueType();
4085 
4086   // SRA expansion:
4087   //   if Shamt-XLEN < 0: // Shamt < XLEN
4088   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4089   //     Hi = Hi >>s Shamt
4090   //   else:
4091   //     Lo = Hi >>s (Shamt-XLEN);
4092   //     Hi = Hi >>s (XLEN-1)
4093   //
4094   // SRL expansion:
4095   //   if Shamt-XLEN < 0: // Shamt < XLEN
4096   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4097   //     Hi = Hi >>u Shamt
4098   //   else:
4099   //     Lo = Hi >>u (Shamt-XLEN);
4100   //     Hi = 0;
4101 
4102   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4103 
4104   SDValue Zero = DAG.getConstant(0, DL, VT);
4105   SDValue One = DAG.getConstant(1, DL, VT);
4106   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4107   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4108   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4109   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4110 
4111   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4112   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4113   SDValue ShiftLeftHi =
4114       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4115   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4116   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4117   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4118   SDValue HiFalse =
4119       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4120 
4121   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4122 
4123   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4124   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4125 
4126   SDValue Parts[2] = {Lo, Hi};
4127   return DAG.getMergeValues(Parts, DL);
4128 }
4129 
4130 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4131 // legal equivalently-sized i8 type, so we can use that as a go-between.
4132 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4133                                                   SelectionDAG &DAG) const {
4134   SDLoc DL(Op);
4135   MVT VT = Op.getSimpleValueType();
4136   SDValue SplatVal = Op.getOperand(0);
4137   // All-zeros or all-ones splats are handled specially.
4138   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4139     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4140     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4141   }
4142   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4143     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4144     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4145   }
4146   MVT XLenVT = Subtarget.getXLenVT();
4147   assert(SplatVal.getValueType() == XLenVT &&
4148          "Unexpected type for i1 splat value");
4149   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4150   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4151                          DAG.getConstant(1, DL, XLenVT));
4152   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4153   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4154   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4155 }
4156 
4157 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4158 // illegal (currently only vXi64 RV32).
4159 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4160 // them to VMV_V_X_VL.
4161 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4162                                                      SelectionDAG &DAG) const {
4163   SDLoc DL(Op);
4164   MVT VecVT = Op.getSimpleValueType();
4165   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4166          "Unexpected SPLAT_VECTOR_PARTS lowering");
4167 
4168   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4169   SDValue Lo = Op.getOperand(0);
4170   SDValue Hi = Op.getOperand(1);
4171 
4172   if (VecVT.isFixedLengthVector()) {
4173     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4174     SDLoc DL(Op);
4175     SDValue Mask, VL;
4176     std::tie(Mask, VL) =
4177         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4178 
4179     SDValue Res =
4180         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4181     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4182   }
4183 
4184   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4185     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4186     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4187     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4188     // node in order to try and match RVV vector/scalar instructions.
4189     if ((LoC >> 31) == HiC)
4190       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4191                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4192   }
4193 
4194   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4195   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4196       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4197       Hi.getConstantOperandVal(1) == 31)
4198     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4199                        DAG.getRegister(RISCV::X0, MVT::i32));
4200 
4201   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4202   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4203                      DAG.getUNDEF(VecVT), Lo, Hi,
4204                      DAG.getRegister(RISCV::X0, MVT::i32));
4205 }
4206 
4207 // Custom-lower extensions from mask vectors by using a vselect either with 1
4208 // for zero/any-extension or -1 for sign-extension:
4209 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4210 // Note that any-extension is lowered identically to zero-extension.
4211 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4212                                                 int64_t ExtTrueVal) const {
4213   SDLoc DL(Op);
4214   MVT VecVT = Op.getSimpleValueType();
4215   SDValue Src = Op.getOperand(0);
4216   // Only custom-lower extensions from mask types
4217   assert(Src.getValueType().isVector() &&
4218          Src.getValueType().getVectorElementType() == MVT::i1);
4219 
4220   if (VecVT.isScalableVector()) {
4221     SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
4222     SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
4223     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4224   }
4225 
4226   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4227   MVT I1ContainerVT =
4228       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4229 
4230   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4231 
4232   SDValue Mask, VL;
4233   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4234 
4235   MVT XLenVT = Subtarget.getXLenVT();
4236   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4237   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4238 
4239   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4240                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4241   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4242                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4243   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4244                                SplatTrueVal, SplatZero, VL);
4245 
4246   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4247 }
4248 
4249 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4250     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4251   MVT ExtVT = Op.getSimpleValueType();
4252   // Only custom-lower extensions from fixed-length vector types.
4253   if (!ExtVT.isFixedLengthVector())
4254     return Op;
4255   MVT VT = Op.getOperand(0).getSimpleValueType();
4256   // Grab the canonical container type for the extended type. Infer the smaller
4257   // type from that to ensure the same number of vector elements, as we know
4258   // the LMUL will be sufficient to hold the smaller type.
4259   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4260   // Get the extended container type manually to ensure the same number of
4261   // vector elements between source and dest.
4262   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4263                                      ContainerExtVT.getVectorElementCount());
4264 
4265   SDValue Op1 =
4266       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4267 
4268   SDLoc DL(Op);
4269   SDValue Mask, VL;
4270   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4271 
4272   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4273 
4274   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4275 }
4276 
4277 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4278 // setcc operation:
4279 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4280 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op,
4281                                                       SelectionDAG &DAG) const {
4282   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4283   SDLoc DL(Op);
4284   EVT MaskVT = Op.getValueType();
4285   // Only expect to custom-lower truncations to mask types
4286   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4287          "Unexpected type for vector mask lowering");
4288   SDValue Src = Op.getOperand(0);
4289   MVT VecVT = Src.getSimpleValueType();
4290   SDValue Mask, VL;
4291   if (IsVPTrunc) {
4292     Mask = Op.getOperand(1);
4293     VL = Op.getOperand(2);
4294   }
4295   // If this is a fixed vector, we need to convert it to a scalable vector.
4296   MVT ContainerVT = VecVT;
4297 
4298   if (VecVT.isFixedLengthVector()) {
4299     ContainerVT = getContainerForFixedLengthVector(VecVT);
4300     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4301     if (IsVPTrunc) {
4302       MVT MaskContainerVT =
4303           getContainerForFixedLengthVector(Mask.getSimpleValueType());
4304       Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget);
4305     }
4306   }
4307 
4308   if (!IsVPTrunc) {
4309     std::tie(Mask, VL) =
4310         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4311   }
4312 
4313   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4314   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4315 
4316   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4317                          DAG.getUNDEF(ContainerVT), SplatOne, VL);
4318   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4319                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4320 
4321   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4322   SDValue Trunc =
4323       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4324   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4325                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4326   if (MaskVT.isFixedLengthVector())
4327     Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4328   return Trunc;
4329 }
4330 
4331 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op,
4332                                                   SelectionDAG &DAG) const {
4333   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
4334   SDLoc DL(Op);
4335 
4336   MVT VT = Op.getSimpleValueType();
4337   // Only custom-lower vector truncates
4338   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4339 
4340   // Truncates to mask types are handled differently
4341   if (VT.getVectorElementType() == MVT::i1)
4342     return lowerVectorMaskTruncLike(Op, DAG);
4343 
4344   // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
4345   // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
4346   // truncate by one power of two at a time.
4347   MVT DstEltVT = VT.getVectorElementType();
4348 
4349   SDValue Src = Op.getOperand(0);
4350   MVT SrcVT = Src.getSimpleValueType();
4351   MVT SrcEltVT = SrcVT.getVectorElementType();
4352 
4353   assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) &&
4354          isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
4355          "Unexpected vector truncate lowering");
4356 
4357   MVT ContainerVT = SrcVT;
4358   SDValue Mask, VL;
4359   if (IsVPTrunc) {
4360     Mask = Op.getOperand(1);
4361     VL = Op.getOperand(2);
4362   }
4363   if (SrcVT.isFixedLengthVector()) {
4364     ContainerVT = getContainerForFixedLengthVector(SrcVT);
4365     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4366     if (IsVPTrunc) {
4367       MVT MaskVT = getMaskTypeFor(ContainerVT);
4368       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4369     }
4370   }
4371 
4372   SDValue Result = Src;
4373   if (!IsVPTrunc) {
4374     std::tie(Mask, VL) =
4375         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4376   }
4377 
4378   LLVMContext &Context = *DAG.getContext();
4379   const ElementCount Count = ContainerVT.getVectorElementCount();
4380   do {
4381     SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
4382     EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
4383     Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
4384                          Mask, VL);
4385   } while (SrcEltVT != DstEltVT);
4386 
4387   if (SrcVT.isFixedLengthVector())
4388     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4389 
4390   return Result;
4391 }
4392 
4393 SDValue
4394 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op,
4395                                                     SelectionDAG &DAG) const {
4396   bool IsVP =
4397       Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND;
4398   bool IsExtend =
4399       Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND;
4400   // RVV can only do truncate fp to types half the size as the source. We
4401   // custom-lower f64->f16 rounds via RVV's round-to-odd float
4402   // conversion instruction.
4403   SDLoc DL(Op);
4404   MVT VT = Op.getSimpleValueType();
4405 
4406   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4407 
4408   SDValue Src = Op.getOperand(0);
4409   MVT SrcVT = Src.getSimpleValueType();
4410 
4411   bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 ||
4412                                      SrcVT.getVectorElementType() != MVT::f16);
4413   bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 ||
4414                                      SrcVT.getVectorElementType() != MVT::f64);
4415 
4416   bool IsDirectConv = IsDirectExtend || IsDirectTrunc;
4417 
4418   // Prepare any fixed-length vector operands.
4419   MVT ContainerVT = VT;
4420   SDValue Mask, VL;
4421   if (IsVP) {
4422     Mask = Op.getOperand(1);
4423     VL = Op.getOperand(2);
4424   }
4425   if (VT.isFixedLengthVector()) {
4426     MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
4427     ContainerVT =
4428         SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
4429     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
4430     if (IsVP) {
4431       MVT MaskVT = getMaskTypeFor(ContainerVT);
4432       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4433     }
4434   }
4435 
4436   if (!IsVP)
4437     std::tie(Mask, VL) =
4438         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4439 
4440   unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL;
4441 
4442   if (IsDirectConv) {
4443     Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL);
4444     if (VT.isFixedLengthVector())
4445       Src = convertFromScalableVector(VT, Src, DAG, Subtarget);
4446     return Src;
4447   }
4448 
4449   unsigned InterConvOpc =
4450       IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL;
4451 
4452   MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
4453   SDValue IntermediateConv =
4454       DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL);
4455   SDValue Result =
4456       DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL);
4457   if (VT.isFixedLengthVector())
4458     return convertFromScalableVector(VT, Result, DAG, Subtarget);
4459   return Result;
4460 }
4461 
4462 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4463 // first position of a vector, and that vector is slid up to the insert index.
4464 // By limiting the active vector length to index+1 and merging with the
4465 // original vector (with an undisturbed tail policy for elements >= VL), we
4466 // achieve the desired result of leaving all elements untouched except the one
4467 // at VL-1, which is replaced with the desired value.
4468 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4469                                                     SelectionDAG &DAG) const {
4470   SDLoc DL(Op);
4471   MVT VecVT = Op.getSimpleValueType();
4472   SDValue Vec = Op.getOperand(0);
4473   SDValue Val = Op.getOperand(1);
4474   SDValue Idx = Op.getOperand(2);
4475 
4476   if (VecVT.getVectorElementType() == MVT::i1) {
4477     // FIXME: For now we just promote to an i8 vector and insert into that,
4478     // but this is probably not optimal.
4479     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4480     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4481     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4482     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4483   }
4484 
4485   MVT ContainerVT = VecVT;
4486   // If the operand is a fixed-length vector, convert to a scalable one.
4487   if (VecVT.isFixedLengthVector()) {
4488     ContainerVT = getContainerForFixedLengthVector(VecVT);
4489     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4490   }
4491 
4492   MVT XLenVT = Subtarget.getXLenVT();
4493 
4494   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4495   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4496   // Even i64-element vectors on RV32 can be lowered without scalar
4497   // legalization if the most-significant 32 bits of the value are not affected
4498   // by the sign-extension of the lower 32 bits.
4499   // TODO: We could also catch sign extensions of a 32-bit value.
4500   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4501     const auto *CVal = cast<ConstantSDNode>(Val);
4502     if (isInt<32>(CVal->getSExtValue())) {
4503       IsLegalInsert = true;
4504       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4505     }
4506   }
4507 
4508   SDValue Mask, VL;
4509   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4510 
4511   SDValue ValInVec;
4512 
4513   if (IsLegalInsert) {
4514     unsigned Opc =
4515         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4516     if (isNullConstant(Idx)) {
4517       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4518       if (!VecVT.isFixedLengthVector())
4519         return Vec;
4520       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4521     }
4522     ValInVec =
4523         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4524   } else {
4525     // On RV32, i64-element vectors must be specially handled to place the
4526     // value at element 0, by using two vslide1up instructions in sequence on
4527     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4528     // this.
4529     SDValue One = DAG.getConstant(1, DL, XLenVT);
4530     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4531     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4532     MVT I32ContainerVT =
4533         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4534     SDValue I32Mask =
4535         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4536     // Limit the active VL to two.
4537     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4538     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4539     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4540     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4541                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4542     // First slide in the hi value, then the lo in underneath it.
4543     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4544                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4545                            I32Mask, InsertI64VL);
4546     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4547                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4548                            I32Mask, InsertI64VL);
4549     // Bitcast back to the right container type.
4550     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4551   }
4552 
4553   // Now that the value is in a vector, slide it into position.
4554   SDValue InsertVL =
4555       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4556   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4557                                 ValInVec, Idx, Mask, InsertVL);
4558   if (!VecVT.isFixedLengthVector())
4559     return Slideup;
4560   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4561 }
4562 
4563 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4564 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4565 // types this is done using VMV_X_S to allow us to glean information about the
4566 // sign bits of the result.
4567 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4568                                                      SelectionDAG &DAG) const {
4569   SDLoc DL(Op);
4570   SDValue Idx = Op.getOperand(1);
4571   SDValue Vec = Op.getOperand(0);
4572   EVT EltVT = Op.getValueType();
4573   MVT VecVT = Vec.getSimpleValueType();
4574   MVT XLenVT = Subtarget.getXLenVT();
4575 
4576   if (VecVT.getVectorElementType() == MVT::i1) {
4577     if (VecVT.isFixedLengthVector()) {
4578       unsigned NumElts = VecVT.getVectorNumElements();
4579       if (NumElts >= 8) {
4580         MVT WideEltVT;
4581         unsigned WidenVecLen;
4582         SDValue ExtractElementIdx;
4583         SDValue ExtractBitIdx;
4584         unsigned MaxEEW = Subtarget.getELEN();
4585         MVT LargestEltVT = MVT::getIntegerVT(
4586             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4587         if (NumElts <= LargestEltVT.getSizeInBits()) {
4588           assert(isPowerOf2_32(NumElts) &&
4589                  "the number of elements should be power of 2");
4590           WideEltVT = MVT::getIntegerVT(NumElts);
4591           WidenVecLen = 1;
4592           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4593           ExtractBitIdx = Idx;
4594         } else {
4595           WideEltVT = LargestEltVT;
4596           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4597           // extract element index = index / element width
4598           ExtractElementIdx = DAG.getNode(
4599               ISD::SRL, DL, XLenVT, Idx,
4600               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4601           // mask bit index = index % element width
4602           ExtractBitIdx = DAG.getNode(
4603               ISD::AND, DL, XLenVT, Idx,
4604               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4605         }
4606         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4607         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4608         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4609                                          Vec, ExtractElementIdx);
4610         // Extract the bit from GPR.
4611         SDValue ShiftRight =
4612             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4613         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4614                            DAG.getConstant(1, DL, XLenVT));
4615       }
4616     }
4617     // Otherwise, promote to an i8 vector and extract from that.
4618     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4619     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4620     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4621   }
4622 
4623   // If this is a fixed vector, we need to convert it to a scalable vector.
4624   MVT ContainerVT = VecVT;
4625   if (VecVT.isFixedLengthVector()) {
4626     ContainerVT = getContainerForFixedLengthVector(VecVT);
4627     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4628   }
4629 
4630   // If the index is 0, the vector is already in the right position.
4631   if (!isNullConstant(Idx)) {
4632     // Use a VL of 1 to avoid processing more elements than we need.
4633     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4634     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
4635     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4636                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4637   }
4638 
4639   if (!EltVT.isInteger()) {
4640     // Floating-point extracts are handled in TableGen.
4641     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4642                        DAG.getConstant(0, DL, XLenVT));
4643   }
4644 
4645   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4646   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4647 }
4648 
4649 // Some RVV intrinsics may claim that they want an integer operand to be
4650 // promoted or expanded.
4651 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4652                                            const RISCVSubtarget &Subtarget) {
4653   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4654           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4655          "Unexpected opcode");
4656 
4657   if (!Subtarget.hasVInstructions())
4658     return SDValue();
4659 
4660   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4661   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4662   SDLoc DL(Op);
4663 
4664   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4665       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4666   if (!II || !II->hasScalarOperand())
4667     return SDValue();
4668 
4669   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4670   assert(SplatOp < Op.getNumOperands());
4671 
4672   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4673   SDValue &ScalarOp = Operands[SplatOp];
4674   MVT OpVT = ScalarOp.getSimpleValueType();
4675   MVT XLenVT = Subtarget.getXLenVT();
4676 
4677   // If this isn't a scalar, or its type is XLenVT we're done.
4678   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4679     return SDValue();
4680 
4681   // Simplest case is that the operand needs to be promoted to XLenVT.
4682   if (OpVT.bitsLT(XLenVT)) {
4683     // If the operand is a constant, sign extend to increase our chances
4684     // of being able to use a .vi instruction. ANY_EXTEND would become a
4685     // a zero extend and the simm5 check in isel would fail.
4686     // FIXME: Should we ignore the upper bits in isel instead?
4687     unsigned ExtOpc =
4688         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4689     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4690     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4691   }
4692 
4693   // Use the previous operand to get the vXi64 VT. The result might be a mask
4694   // VT for compares. Using the previous operand assumes that the previous
4695   // operand will never have a smaller element size than a scalar operand and
4696   // that a widening operation never uses SEW=64.
4697   // NOTE: If this fails the below assert, we can probably just find the
4698   // element count from any operand or result and use it to construct the VT.
4699   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4700   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4701 
4702   // The more complex case is when the scalar is larger than XLenVT.
4703   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4704          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4705 
4706   // If this is a sign-extended 32-bit value, we can truncate it and rely on the
4707   // instruction to sign-extend since SEW>XLEN.
4708   if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
4709     ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
4710     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4711   }
4712 
4713   switch (IntNo) {
4714   case Intrinsic::riscv_vslide1up:
4715   case Intrinsic::riscv_vslide1down:
4716   case Intrinsic::riscv_vslide1up_mask:
4717   case Intrinsic::riscv_vslide1down_mask: {
4718     // We need to special case these when the scalar is larger than XLen.
4719     unsigned NumOps = Op.getNumOperands();
4720     bool IsMasked = NumOps == 7;
4721 
4722     // Convert the vector source to the equivalent nxvXi32 vector.
4723     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4724     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4725 
4726     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4727                                    DAG.getConstant(0, DL, XLenVT));
4728     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4729                                    DAG.getConstant(1, DL, XLenVT));
4730 
4731     // Double the VL since we halved SEW.
4732     SDValue AVL = getVLOperand(Op);
4733     SDValue I32VL;
4734 
4735     // Optimize for constant AVL
4736     if (isa<ConstantSDNode>(AVL)) {
4737       unsigned EltSize = VT.getScalarSizeInBits();
4738       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4739 
4740       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4741       unsigned MaxVLMAX =
4742           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4743 
4744       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4745       unsigned MinVLMAX =
4746           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4747 
4748       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4749       if (AVLInt <= MinVLMAX) {
4750         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4751       } else if (AVLInt >= 2 * MaxVLMAX) {
4752         // Just set vl to VLMAX in this situation
4753         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4754         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4755         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4756         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4757         SDValue SETVLMAX = DAG.getTargetConstant(
4758             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4759         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4760                             LMUL);
4761       } else {
4762         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4763         // is related to the hardware implementation.
4764         // So let the following code handle
4765       }
4766     }
4767     if (!I32VL) {
4768       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4769       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4770       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4771       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4772       SDValue SETVL =
4773           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4774       // Using vsetvli instruction to get actually used length which related to
4775       // the hardware implementation
4776       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4777                                SEW, LMUL);
4778       I32VL =
4779           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4780     }
4781 
4782     SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG);
4783 
4784     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4785     // instructions.
4786     SDValue Passthru;
4787     if (IsMasked)
4788       Passthru = DAG.getUNDEF(I32VT);
4789     else
4790       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4791 
4792     if (IntNo == Intrinsic::riscv_vslide1up ||
4793         IntNo == Intrinsic::riscv_vslide1up_mask) {
4794       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4795                         ScalarHi, I32Mask, I32VL);
4796       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4797                         ScalarLo, I32Mask, I32VL);
4798     } else {
4799       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4800                         ScalarLo, I32Mask, I32VL);
4801       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4802                         ScalarHi, I32Mask, I32VL);
4803     }
4804 
4805     // Convert back to nxvXi64.
4806     Vec = DAG.getBitcast(VT, Vec);
4807 
4808     if (!IsMasked)
4809       return Vec;
4810     // Apply mask after the operation.
4811     SDValue Mask = Operands[NumOps - 3];
4812     SDValue MaskedOff = Operands[1];
4813     // Assume Policy operand is the last operand.
4814     uint64_t Policy =
4815         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4816     // We don't need to select maskedoff if it's undef.
4817     if (MaskedOff.isUndef())
4818       return Vec;
4819     // TAMU
4820     if (Policy == RISCVII::TAIL_AGNOSTIC)
4821       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4822                          AVL);
4823     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4824     // It's fine because vmerge does not care mask policy.
4825     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4826                        AVL);
4827   }
4828   }
4829 
4830   // We need to convert the scalar to a splat vector.
4831   SDValue VL = getVLOperand(Op);
4832   assert(VL.getValueType() == XLenVT);
4833   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4834   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4835 }
4836 
4837 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4838                                                      SelectionDAG &DAG) const {
4839   unsigned IntNo = Op.getConstantOperandVal(0);
4840   SDLoc DL(Op);
4841   MVT XLenVT = Subtarget.getXLenVT();
4842 
4843   switch (IntNo) {
4844   default:
4845     break; // Don't custom lower most intrinsics.
4846   case Intrinsic::thread_pointer: {
4847     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4848     return DAG.getRegister(RISCV::X4, PtrVT);
4849   }
4850   case Intrinsic::riscv_orc_b:
4851   case Intrinsic::riscv_brev8: {
4852     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4853     unsigned Opc =
4854         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4855     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4856                        DAG.getConstant(7, DL, XLenVT));
4857   }
4858   case Intrinsic::riscv_grev:
4859   case Intrinsic::riscv_gorc: {
4860     unsigned Opc =
4861         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4862     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4863   }
4864   case Intrinsic::riscv_zip:
4865   case Intrinsic::riscv_unzip: {
4866     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4867     // For i32 the immediate is 15. For i64 the immediate is 31.
4868     unsigned Opc =
4869         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4870     unsigned BitWidth = Op.getValueSizeInBits();
4871     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4872     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4873                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4874   }
4875   case Intrinsic::riscv_shfl:
4876   case Intrinsic::riscv_unshfl: {
4877     unsigned Opc =
4878         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4879     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4880   }
4881   case Intrinsic::riscv_bcompress:
4882   case Intrinsic::riscv_bdecompress: {
4883     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4884                                                        : RISCVISD::BDECOMPRESS;
4885     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4886   }
4887   case Intrinsic::riscv_bfp:
4888     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4889                        Op.getOperand(2));
4890   case Intrinsic::riscv_fsl:
4891     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4892                        Op.getOperand(2), Op.getOperand(3));
4893   case Intrinsic::riscv_fsr:
4894     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4895                        Op.getOperand(2), Op.getOperand(3));
4896   case Intrinsic::riscv_vmv_x_s:
4897     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4898     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4899                        Op.getOperand(1));
4900   case Intrinsic::riscv_vmv_v_x:
4901     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4902                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4903                             Subtarget);
4904   case Intrinsic::riscv_vfmv_v_f:
4905     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4906                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4907   case Intrinsic::riscv_vmv_s_x: {
4908     SDValue Scalar = Op.getOperand(2);
4909 
4910     if (Scalar.getValueType().bitsLE(XLenVT)) {
4911       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4912       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4913                          Op.getOperand(1), Scalar, Op.getOperand(3));
4914     }
4915 
4916     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4917 
4918     // This is an i64 value that lives in two scalar registers. We have to
4919     // insert this in a convoluted way. First we build vXi64 splat containing
4920     // the two values that we assemble using some bit math. Next we'll use
4921     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4922     // to merge element 0 from our splat into the source vector.
4923     // FIXME: This is probably not the best way to do this, but it is
4924     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4925     // point.
4926     //   sw lo, (a0)
4927     //   sw hi, 4(a0)
4928     //   vlse vX, (a0)
4929     //
4930     //   vid.v      vVid
4931     //   vmseq.vx   mMask, vVid, 0
4932     //   vmerge.vvm vDest, vSrc, vVal, mMask
4933     MVT VT = Op.getSimpleValueType();
4934     SDValue Vec = Op.getOperand(1);
4935     SDValue VL = getVLOperand(Op);
4936 
4937     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4938     if (Op.getOperand(1).isUndef())
4939       return SplattedVal;
4940     SDValue SplattedIdx =
4941         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4942                     DAG.getConstant(0, DL, MVT::i32), VL);
4943 
4944     MVT MaskVT = getMaskTypeFor(VT);
4945     SDValue Mask = getAllOnesMask(VT, VL, DL, DAG);
4946     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4947     SDValue SelectCond =
4948         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4949                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4950     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4951                        Vec, VL);
4952   }
4953   }
4954 
4955   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4956 }
4957 
4958 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4959                                                     SelectionDAG &DAG) const {
4960   unsigned IntNo = Op.getConstantOperandVal(1);
4961   switch (IntNo) {
4962   default:
4963     break;
4964   case Intrinsic::riscv_masked_strided_load: {
4965     SDLoc DL(Op);
4966     MVT XLenVT = Subtarget.getXLenVT();
4967 
4968     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4969     // the selection of the masked intrinsics doesn't do this for us.
4970     SDValue Mask = Op.getOperand(5);
4971     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4972 
4973     MVT VT = Op->getSimpleValueType(0);
4974     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4975 
4976     SDValue PassThru = Op.getOperand(2);
4977     if (!IsUnmasked) {
4978       MVT MaskVT = getMaskTypeFor(ContainerVT);
4979       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4980       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4981     }
4982 
4983     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4984 
4985     SDValue IntID = DAG.getTargetConstant(
4986         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4987         XLenVT);
4988 
4989     auto *Load = cast<MemIntrinsicSDNode>(Op);
4990     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4991     if (IsUnmasked)
4992       Ops.push_back(DAG.getUNDEF(ContainerVT));
4993     else
4994       Ops.push_back(PassThru);
4995     Ops.push_back(Op.getOperand(3)); // Ptr
4996     Ops.push_back(Op.getOperand(4)); // Stride
4997     if (!IsUnmasked)
4998       Ops.push_back(Mask);
4999     Ops.push_back(VL);
5000     if (!IsUnmasked) {
5001       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
5002       Ops.push_back(Policy);
5003     }
5004 
5005     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5006     SDValue Result =
5007         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5008                                 Load->getMemoryVT(), Load->getMemOperand());
5009     SDValue Chain = Result.getValue(1);
5010     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5011     return DAG.getMergeValues({Result, Chain}, DL);
5012   }
5013   case Intrinsic::riscv_seg2_load:
5014   case Intrinsic::riscv_seg3_load:
5015   case Intrinsic::riscv_seg4_load:
5016   case Intrinsic::riscv_seg5_load:
5017   case Intrinsic::riscv_seg6_load:
5018   case Intrinsic::riscv_seg7_load:
5019   case Intrinsic::riscv_seg8_load: {
5020     SDLoc DL(Op);
5021     static const Intrinsic::ID VlsegInts[7] = {
5022         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
5023         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
5024         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
5025         Intrinsic::riscv_vlseg8};
5026     unsigned NF = Op->getNumValues() - 1;
5027     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
5028     MVT XLenVT = Subtarget.getXLenVT();
5029     MVT VT = Op->getSimpleValueType(0);
5030     MVT ContainerVT = getContainerForFixedLengthVector(VT);
5031 
5032     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5033     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
5034     auto *Load = cast<MemIntrinsicSDNode>(Op);
5035     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
5036     ContainerVTs.push_back(MVT::Other);
5037     SDVTList VTs = DAG.getVTList(ContainerVTs);
5038     SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID};
5039     Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT));
5040     Ops.push_back(Op.getOperand(2));
5041     Ops.push_back(VL);
5042     SDValue Result =
5043         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5044                                 Load->getMemoryVT(), Load->getMemOperand());
5045     SmallVector<SDValue, 9> Results;
5046     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
5047       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
5048                                                   DAG, Subtarget));
5049     Results.push_back(Result.getValue(NF));
5050     return DAG.getMergeValues(Results, DL);
5051   }
5052   }
5053 
5054   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
5055 }
5056 
5057 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
5058                                                  SelectionDAG &DAG) const {
5059   unsigned IntNo = Op.getConstantOperandVal(1);
5060   switch (IntNo) {
5061   default:
5062     break;
5063   case Intrinsic::riscv_masked_strided_store: {
5064     SDLoc DL(Op);
5065     MVT XLenVT = Subtarget.getXLenVT();
5066 
5067     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5068     // the selection of the masked intrinsics doesn't do this for us.
5069     SDValue Mask = Op.getOperand(5);
5070     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5071 
5072     SDValue Val = Op.getOperand(2);
5073     MVT VT = Val.getSimpleValueType();
5074     MVT ContainerVT = getContainerForFixedLengthVector(VT);
5075 
5076     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5077     if (!IsUnmasked) {
5078       MVT MaskVT = getMaskTypeFor(ContainerVT);
5079       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5080     }
5081 
5082     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5083 
5084     SDValue IntID = DAG.getTargetConstant(
5085         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
5086         XLenVT);
5087 
5088     auto *Store = cast<MemIntrinsicSDNode>(Op);
5089     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
5090     Ops.push_back(Val);
5091     Ops.push_back(Op.getOperand(3)); // Ptr
5092     Ops.push_back(Op.getOperand(4)); // Stride
5093     if (!IsUnmasked)
5094       Ops.push_back(Mask);
5095     Ops.push_back(VL);
5096 
5097     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
5098                                    Ops, Store->getMemoryVT(),
5099                                    Store->getMemOperand());
5100   }
5101   }
5102 
5103   return SDValue();
5104 }
5105 
5106 static MVT getLMUL1VT(MVT VT) {
5107   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
5108          "Unexpected vector MVT");
5109   return MVT::getScalableVectorVT(
5110       VT.getVectorElementType(),
5111       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
5112 }
5113 
5114 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
5115   switch (ISDOpcode) {
5116   default:
5117     llvm_unreachable("Unhandled reduction");
5118   case ISD::VECREDUCE_ADD:
5119     return RISCVISD::VECREDUCE_ADD_VL;
5120   case ISD::VECREDUCE_UMAX:
5121     return RISCVISD::VECREDUCE_UMAX_VL;
5122   case ISD::VECREDUCE_SMAX:
5123     return RISCVISD::VECREDUCE_SMAX_VL;
5124   case ISD::VECREDUCE_UMIN:
5125     return RISCVISD::VECREDUCE_UMIN_VL;
5126   case ISD::VECREDUCE_SMIN:
5127     return RISCVISD::VECREDUCE_SMIN_VL;
5128   case ISD::VECREDUCE_AND:
5129     return RISCVISD::VECREDUCE_AND_VL;
5130   case ISD::VECREDUCE_OR:
5131     return RISCVISD::VECREDUCE_OR_VL;
5132   case ISD::VECREDUCE_XOR:
5133     return RISCVISD::VECREDUCE_XOR_VL;
5134   }
5135 }
5136 
5137 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
5138                                                          SelectionDAG &DAG,
5139                                                          bool IsVP) const {
5140   SDLoc DL(Op);
5141   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5142   MVT VecVT = Vec.getSimpleValueType();
5143   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5144           Op.getOpcode() == ISD::VECREDUCE_OR ||
5145           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5146           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5147           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5148           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5149          "Unexpected reduction lowering");
5150 
5151   MVT XLenVT = Subtarget.getXLenVT();
5152   assert(Op.getValueType() == XLenVT &&
5153          "Expected reduction output to be legalized to XLenVT");
5154 
5155   MVT ContainerVT = VecVT;
5156   if (VecVT.isFixedLengthVector()) {
5157     ContainerVT = getContainerForFixedLengthVector(VecVT);
5158     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5159   }
5160 
5161   SDValue Mask, VL;
5162   if (IsVP) {
5163     Mask = Op.getOperand(2);
5164     VL = Op.getOperand(3);
5165   } else {
5166     std::tie(Mask, VL) =
5167         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5168   }
5169 
5170   unsigned BaseOpc;
5171   ISD::CondCode CC;
5172   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5173 
5174   switch (Op.getOpcode()) {
5175   default:
5176     llvm_unreachable("Unhandled reduction");
5177   case ISD::VECREDUCE_AND:
5178   case ISD::VP_REDUCE_AND: {
5179     // vcpop ~x == 0
5180     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5181     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5182     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5183     CC = ISD::SETEQ;
5184     BaseOpc = ISD::AND;
5185     break;
5186   }
5187   case ISD::VECREDUCE_OR:
5188   case ISD::VP_REDUCE_OR:
5189     // vcpop x != 0
5190     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5191     CC = ISD::SETNE;
5192     BaseOpc = ISD::OR;
5193     break;
5194   case ISD::VECREDUCE_XOR:
5195   case ISD::VP_REDUCE_XOR: {
5196     // ((vcpop x) & 1) != 0
5197     SDValue One = DAG.getConstant(1, DL, XLenVT);
5198     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5199     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5200     CC = ISD::SETNE;
5201     BaseOpc = ISD::XOR;
5202     break;
5203   }
5204   }
5205 
5206   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5207 
5208   if (!IsVP)
5209     return SetCC;
5210 
5211   // Now include the start value in the operation.
5212   // Note that we must return the start value when no elements are operated
5213   // upon. The vcpop instructions we've emitted in each case above will return
5214   // 0 for an inactive vector, and so we've already received the neutral value:
5215   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5216   // can simply include the start value.
5217   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5218 }
5219 
5220 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5221                                             SelectionDAG &DAG) const {
5222   SDLoc DL(Op);
5223   SDValue Vec = Op.getOperand(0);
5224   EVT VecEVT = Vec.getValueType();
5225 
5226   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5227 
5228   // Due to ordering in legalize types we may have a vector type that needs to
5229   // be split. Do that manually so we can get down to a legal type.
5230   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5231          TargetLowering::TypeSplitVector) {
5232     SDValue Lo, Hi;
5233     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5234     VecEVT = Lo.getValueType();
5235     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5236   }
5237 
5238   // TODO: The type may need to be widened rather than split. Or widened before
5239   // it can be split.
5240   if (!isTypeLegal(VecEVT))
5241     return SDValue();
5242 
5243   MVT VecVT = VecEVT.getSimpleVT();
5244   MVT VecEltVT = VecVT.getVectorElementType();
5245   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5246 
5247   MVT ContainerVT = VecVT;
5248   if (VecVT.isFixedLengthVector()) {
5249     ContainerVT = getContainerForFixedLengthVector(VecVT);
5250     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5251   }
5252 
5253   MVT M1VT = getLMUL1VT(ContainerVT);
5254   MVT XLenVT = Subtarget.getXLenVT();
5255 
5256   SDValue Mask, VL;
5257   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5258 
5259   SDValue NeutralElem =
5260       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5261   SDValue IdentitySplat =
5262       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5263                        M1VT, DL, DAG, Subtarget);
5264   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5265                                   IdentitySplat, Mask, VL);
5266   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5267                              DAG.getConstant(0, DL, XLenVT));
5268   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5269 }
5270 
5271 // Given a reduction op, this function returns the matching reduction opcode,
5272 // the vector SDValue and the scalar SDValue required to lower this to a
5273 // RISCVISD node.
5274 static std::tuple<unsigned, SDValue, SDValue>
5275 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5276   SDLoc DL(Op);
5277   auto Flags = Op->getFlags();
5278   unsigned Opcode = Op.getOpcode();
5279   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5280   switch (Opcode) {
5281   default:
5282     llvm_unreachable("Unhandled reduction");
5283   case ISD::VECREDUCE_FADD: {
5284     // Use positive zero if we can. It is cheaper to materialize.
5285     SDValue Zero =
5286         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5287     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5288   }
5289   case ISD::VECREDUCE_SEQ_FADD:
5290     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5291                            Op.getOperand(0));
5292   case ISD::VECREDUCE_FMIN:
5293     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5294                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5295   case ISD::VECREDUCE_FMAX:
5296     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5297                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5298   }
5299 }
5300 
5301 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5302                                               SelectionDAG &DAG) const {
5303   SDLoc DL(Op);
5304   MVT VecEltVT = Op.getSimpleValueType();
5305 
5306   unsigned RVVOpcode;
5307   SDValue VectorVal, ScalarVal;
5308   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5309       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5310   MVT VecVT = VectorVal.getSimpleValueType();
5311 
5312   MVT ContainerVT = VecVT;
5313   if (VecVT.isFixedLengthVector()) {
5314     ContainerVT = getContainerForFixedLengthVector(VecVT);
5315     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5316   }
5317 
5318   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5319   MVT XLenVT = Subtarget.getXLenVT();
5320 
5321   SDValue Mask, VL;
5322   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5323 
5324   SDValue ScalarSplat =
5325       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5326                        M1VT, DL, DAG, Subtarget);
5327   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5328                                   VectorVal, ScalarSplat, Mask, VL);
5329   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5330                      DAG.getConstant(0, DL, XLenVT));
5331 }
5332 
5333 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5334   switch (ISDOpcode) {
5335   default:
5336     llvm_unreachable("Unhandled reduction");
5337   case ISD::VP_REDUCE_ADD:
5338     return RISCVISD::VECREDUCE_ADD_VL;
5339   case ISD::VP_REDUCE_UMAX:
5340     return RISCVISD::VECREDUCE_UMAX_VL;
5341   case ISD::VP_REDUCE_SMAX:
5342     return RISCVISD::VECREDUCE_SMAX_VL;
5343   case ISD::VP_REDUCE_UMIN:
5344     return RISCVISD::VECREDUCE_UMIN_VL;
5345   case ISD::VP_REDUCE_SMIN:
5346     return RISCVISD::VECREDUCE_SMIN_VL;
5347   case ISD::VP_REDUCE_AND:
5348     return RISCVISD::VECREDUCE_AND_VL;
5349   case ISD::VP_REDUCE_OR:
5350     return RISCVISD::VECREDUCE_OR_VL;
5351   case ISD::VP_REDUCE_XOR:
5352     return RISCVISD::VECREDUCE_XOR_VL;
5353   case ISD::VP_REDUCE_FADD:
5354     return RISCVISD::VECREDUCE_FADD_VL;
5355   case ISD::VP_REDUCE_SEQ_FADD:
5356     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5357   case ISD::VP_REDUCE_FMAX:
5358     return RISCVISD::VECREDUCE_FMAX_VL;
5359   case ISD::VP_REDUCE_FMIN:
5360     return RISCVISD::VECREDUCE_FMIN_VL;
5361   }
5362 }
5363 
5364 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5365                                            SelectionDAG &DAG) const {
5366   SDLoc DL(Op);
5367   SDValue Vec = Op.getOperand(1);
5368   EVT VecEVT = Vec.getValueType();
5369 
5370   // TODO: The type may need to be widened rather than split. Or widened before
5371   // it can be split.
5372   if (!isTypeLegal(VecEVT))
5373     return SDValue();
5374 
5375   MVT VecVT = VecEVT.getSimpleVT();
5376   MVT VecEltVT = VecVT.getVectorElementType();
5377   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5378 
5379   MVT ContainerVT = VecVT;
5380   if (VecVT.isFixedLengthVector()) {
5381     ContainerVT = getContainerForFixedLengthVector(VecVT);
5382     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5383   }
5384 
5385   SDValue VL = Op.getOperand(3);
5386   SDValue Mask = Op.getOperand(2);
5387 
5388   MVT M1VT = getLMUL1VT(ContainerVT);
5389   MVT XLenVT = Subtarget.getXLenVT();
5390   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5391 
5392   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5393                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5394                                         DL, DAG, Subtarget);
5395   SDValue Reduction =
5396       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5397   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5398                              DAG.getConstant(0, DL, XLenVT));
5399   if (!VecVT.isInteger())
5400     return Elt0;
5401   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5402 }
5403 
5404 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5405                                                    SelectionDAG &DAG) const {
5406   SDValue Vec = Op.getOperand(0);
5407   SDValue SubVec = Op.getOperand(1);
5408   MVT VecVT = Vec.getSimpleValueType();
5409   MVT SubVecVT = SubVec.getSimpleValueType();
5410 
5411   SDLoc DL(Op);
5412   MVT XLenVT = Subtarget.getXLenVT();
5413   unsigned OrigIdx = Op.getConstantOperandVal(2);
5414   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5415 
5416   // We don't have the ability to slide mask vectors up indexed by their i1
5417   // elements; the smallest we can do is i8. Often we are able to bitcast to
5418   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5419   // into a scalable one, we might not necessarily have enough scalable
5420   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5421   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5422       (OrigIdx != 0 || !Vec.isUndef())) {
5423     if (VecVT.getVectorMinNumElements() >= 8 &&
5424         SubVecVT.getVectorMinNumElements() >= 8) {
5425       assert(OrigIdx % 8 == 0 && "Invalid index");
5426       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5427              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5428              "Unexpected mask vector lowering");
5429       OrigIdx /= 8;
5430       SubVecVT =
5431           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5432                            SubVecVT.isScalableVector());
5433       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5434                                VecVT.isScalableVector());
5435       Vec = DAG.getBitcast(VecVT, Vec);
5436       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5437     } else {
5438       // We can't slide this mask vector up indexed by its i1 elements.
5439       // This poses a problem when we wish to insert a scalable vector which
5440       // can't be re-expressed as a larger type. Just choose the slow path and
5441       // extend to a larger type, then truncate back down.
5442       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5443       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5444       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5445       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5446       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5447                         Op.getOperand(2));
5448       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5449       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5450     }
5451   }
5452 
5453   // If the subvector vector is a fixed-length type, we cannot use subregister
5454   // manipulation to simplify the codegen; we don't know which register of a
5455   // LMUL group contains the specific subvector as we only know the minimum
5456   // register size. Therefore we must slide the vector group up the full
5457   // amount.
5458   if (SubVecVT.isFixedLengthVector()) {
5459     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5460       return Op;
5461     MVT ContainerVT = VecVT;
5462     if (VecVT.isFixedLengthVector()) {
5463       ContainerVT = getContainerForFixedLengthVector(VecVT);
5464       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5465     }
5466     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5467                          DAG.getUNDEF(ContainerVT), SubVec,
5468                          DAG.getConstant(0, DL, XLenVT));
5469     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5470       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5471       return DAG.getBitcast(Op.getValueType(), SubVec);
5472     }
5473     SDValue Mask =
5474         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5475     // Set the vector length to only the number of elements we care about. Note
5476     // that for slideup this includes the offset.
5477     SDValue VL =
5478         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5479     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5480     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5481                                   SubVec, SlideupAmt, Mask, VL);
5482     if (VecVT.isFixedLengthVector())
5483       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5484     return DAG.getBitcast(Op.getValueType(), Slideup);
5485   }
5486 
5487   unsigned SubRegIdx, RemIdx;
5488   std::tie(SubRegIdx, RemIdx) =
5489       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5490           VecVT, SubVecVT, OrigIdx, TRI);
5491 
5492   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5493   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5494                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5495                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5496 
5497   // 1. If the Idx has been completely eliminated and this subvector's size is
5498   // a vector register or a multiple thereof, or the surrounding elements are
5499   // undef, then this is a subvector insert which naturally aligns to a vector
5500   // register. These can easily be handled using subregister manipulation.
5501   // 2. If the subvector is smaller than a vector register, then the insertion
5502   // must preserve the undisturbed elements of the register. We do this by
5503   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5504   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5505   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5506   // LMUL=1 type back into the larger vector (resolving to another subregister
5507   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5508   // to avoid allocating a large register group to hold our subvector.
5509   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5510     return Op;
5511 
5512   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5513   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5514   // (in our case undisturbed). This means we can set up a subvector insertion
5515   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5516   // size of the subvector.
5517   MVT InterSubVT = VecVT;
5518   SDValue AlignedExtract = Vec;
5519   unsigned AlignedIdx = OrigIdx - RemIdx;
5520   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5521     InterSubVT = getLMUL1VT(VecVT);
5522     // Extract a subvector equal to the nearest full vector register type. This
5523     // should resolve to a EXTRACT_SUBREG instruction.
5524     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5525                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5526   }
5527 
5528   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5529   // For scalable vectors this must be further multiplied by vscale.
5530   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5531 
5532   SDValue Mask, VL;
5533   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5534 
5535   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5536   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5537   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5538   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5539 
5540   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5541                        DAG.getUNDEF(InterSubVT), SubVec,
5542                        DAG.getConstant(0, DL, XLenVT));
5543 
5544   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5545                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5546 
5547   // If required, insert this subvector back into the correct vector register.
5548   // This should resolve to an INSERT_SUBREG instruction.
5549   if (VecVT.bitsGT(InterSubVT))
5550     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5551                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5552 
5553   // We might have bitcast from a mask type: cast back to the original type if
5554   // required.
5555   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5556 }
5557 
5558 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5559                                                     SelectionDAG &DAG) const {
5560   SDValue Vec = Op.getOperand(0);
5561   MVT SubVecVT = Op.getSimpleValueType();
5562   MVT VecVT = Vec.getSimpleValueType();
5563 
5564   SDLoc DL(Op);
5565   MVT XLenVT = Subtarget.getXLenVT();
5566   unsigned OrigIdx = Op.getConstantOperandVal(1);
5567   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5568 
5569   // We don't have the ability to slide mask vectors down indexed by their i1
5570   // elements; the smallest we can do is i8. Often we are able to bitcast to
5571   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5572   // from a scalable one, we might not necessarily have enough scalable
5573   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5574   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5575     if (VecVT.getVectorMinNumElements() >= 8 &&
5576         SubVecVT.getVectorMinNumElements() >= 8) {
5577       assert(OrigIdx % 8 == 0 && "Invalid index");
5578       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5579              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5580              "Unexpected mask vector lowering");
5581       OrigIdx /= 8;
5582       SubVecVT =
5583           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5584                            SubVecVT.isScalableVector());
5585       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5586                                VecVT.isScalableVector());
5587       Vec = DAG.getBitcast(VecVT, Vec);
5588     } else {
5589       // We can't slide this mask vector down, indexed by its i1 elements.
5590       // This poses a problem when we wish to extract a scalable vector which
5591       // can't be re-expressed as a larger type. Just choose the slow path and
5592       // extend to a larger type, then truncate back down.
5593       // TODO: We could probably improve this when extracting certain fixed
5594       // from fixed, where we can extract as i8 and shift the correct element
5595       // right to reach the desired subvector?
5596       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5597       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5598       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5599       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5600                         Op.getOperand(1));
5601       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5602       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5603     }
5604   }
5605 
5606   // If the subvector vector is a fixed-length type, we cannot use subregister
5607   // manipulation to simplify the codegen; we don't know which register of a
5608   // LMUL group contains the specific subvector as we only know the minimum
5609   // register size. Therefore we must slide the vector group down the full
5610   // amount.
5611   if (SubVecVT.isFixedLengthVector()) {
5612     // With an index of 0 this is a cast-like subvector, which can be performed
5613     // with subregister operations.
5614     if (OrigIdx == 0)
5615       return Op;
5616     MVT ContainerVT = VecVT;
5617     if (VecVT.isFixedLengthVector()) {
5618       ContainerVT = getContainerForFixedLengthVector(VecVT);
5619       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5620     }
5621     SDValue Mask =
5622         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5623     // Set the vector length to only the number of elements we care about. This
5624     // avoids sliding down elements we're going to discard straight away.
5625     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5626     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5627     SDValue Slidedown =
5628         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5629                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5630     // Now we can use a cast-like subvector extract to get the result.
5631     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5632                             DAG.getConstant(0, DL, XLenVT));
5633     return DAG.getBitcast(Op.getValueType(), Slidedown);
5634   }
5635 
5636   unsigned SubRegIdx, RemIdx;
5637   std::tie(SubRegIdx, RemIdx) =
5638       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5639           VecVT, SubVecVT, OrigIdx, TRI);
5640 
5641   // If the Idx has been completely eliminated then this is a subvector extract
5642   // which naturally aligns to a vector register. These can easily be handled
5643   // using subregister manipulation.
5644   if (RemIdx == 0)
5645     return Op;
5646 
5647   // Else we must shift our vector register directly to extract the subvector.
5648   // Do this using VSLIDEDOWN.
5649 
5650   // If the vector type is an LMUL-group type, extract a subvector equal to the
5651   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5652   // instruction.
5653   MVT InterSubVT = VecVT;
5654   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5655     InterSubVT = getLMUL1VT(VecVT);
5656     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5657                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5658   }
5659 
5660   // Slide this vector register down by the desired number of elements in order
5661   // to place the desired subvector starting at element 0.
5662   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5663   // For scalable vectors this must be further multiplied by vscale.
5664   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5665 
5666   SDValue Mask, VL;
5667   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5668   SDValue Slidedown =
5669       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5670                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5671 
5672   // Now the vector is in the right position, extract our final subvector. This
5673   // should resolve to a COPY.
5674   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5675                           DAG.getConstant(0, DL, XLenVT));
5676 
5677   // We might have bitcast from a mask type: cast back to the original type if
5678   // required.
5679   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5680 }
5681 
5682 // Lower step_vector to the vid instruction. Any non-identity step value must
5683 // be accounted for my manual expansion.
5684 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5685                                               SelectionDAG &DAG) const {
5686   SDLoc DL(Op);
5687   MVT VT = Op.getSimpleValueType();
5688   MVT XLenVT = Subtarget.getXLenVT();
5689   SDValue Mask, VL;
5690   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5691   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5692   uint64_t StepValImm = Op.getConstantOperandVal(0);
5693   if (StepValImm != 1) {
5694     if (isPowerOf2_64(StepValImm)) {
5695       SDValue StepVal =
5696           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5697                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5698       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5699     } else {
5700       SDValue StepVal = lowerScalarSplat(
5701           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5702           VL, VT, DL, DAG, Subtarget);
5703       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5704     }
5705   }
5706   return StepVec;
5707 }
5708 
5709 // Implement vector_reverse using vrgather.vv with indices determined by
5710 // subtracting the id of each element from (VLMAX-1). This will convert
5711 // the indices like so:
5712 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5713 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5714 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5715                                                  SelectionDAG &DAG) const {
5716   SDLoc DL(Op);
5717   MVT VecVT = Op.getSimpleValueType();
5718   if (VecVT.getVectorElementType() == MVT::i1) {
5719     MVT WidenVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
5720     SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenVT, Op.getOperand(0));
5721     SDValue Op2 = DAG.getNode(ISD::VECTOR_REVERSE, DL, WidenVT, Op1);
5722     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Op2);
5723   }
5724   unsigned EltSize = VecVT.getScalarSizeInBits();
5725   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5726   unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
5727   unsigned MaxVLMAX =
5728     RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5729 
5730   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5731   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5732 
5733   // If this is SEW=8 and VLMAX is potentially more than 256, we need
5734   // to use vrgatherei16.vv.
5735   // TODO: It's also possible to use vrgatherei16.vv for other types to
5736   // decrease register width for the index calculation.
5737   if (MaxVLMAX > 256 && EltSize == 8) {
5738     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5739     // Reverse each half, then reassemble them in reverse order.
5740     // NOTE: It's also possible that after splitting that VLMAX no longer
5741     // requires vrgatherei16.vv.
5742     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5743       SDValue Lo, Hi;
5744       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5745       EVT LoVT, HiVT;
5746       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5747       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5748       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5749       // Reassemble the low and high pieces reversed.
5750       // FIXME: This is a CONCAT_VECTORS.
5751       SDValue Res =
5752           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5753                       DAG.getIntPtrConstant(0, DL));
5754       return DAG.getNode(
5755           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5756           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5757     }
5758 
5759     // Just promote the int type to i16 which will double the LMUL.
5760     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5761     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5762   }
5763 
5764   MVT XLenVT = Subtarget.getXLenVT();
5765   SDValue Mask, VL;
5766   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5767 
5768   // Calculate VLMAX-1 for the desired SEW.
5769   unsigned MinElts = VecVT.getVectorMinNumElements();
5770   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5771                               DAG.getConstant(MinElts, DL, XLenVT));
5772   SDValue VLMinus1 =
5773       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5774 
5775   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5776   bool IsRV32E64 =
5777       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5778   SDValue SplatVL;
5779   if (!IsRV32E64)
5780     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5781   else
5782     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5783                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5784 
5785   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5786   SDValue Indices =
5787       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5788 
5789   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask,
5790                      DAG.getUNDEF(VecVT), VL);
5791 }
5792 
5793 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5794                                                 SelectionDAG &DAG) const {
5795   SDLoc DL(Op);
5796   SDValue V1 = Op.getOperand(0);
5797   SDValue V2 = Op.getOperand(1);
5798   MVT XLenVT = Subtarget.getXLenVT();
5799   MVT VecVT = Op.getSimpleValueType();
5800 
5801   unsigned MinElts = VecVT.getVectorMinNumElements();
5802   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5803                               DAG.getConstant(MinElts, DL, XLenVT));
5804 
5805   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5806   SDValue DownOffset, UpOffset;
5807   if (ImmValue >= 0) {
5808     // The operand is a TargetConstant, we need to rebuild it as a regular
5809     // constant.
5810     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5811     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5812   } else {
5813     // The operand is a TargetConstant, we need to rebuild it as a regular
5814     // constant rather than negating the original operand.
5815     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5816     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5817   }
5818 
5819   SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG);
5820 
5821   SDValue SlideDown =
5822       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5823                   DownOffset, TrueMask, UpOffset);
5824   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5825                      TrueMask, DAG.getRegister(RISCV::X0, XLenVT));
5826 }
5827 
5828 SDValue
5829 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5830                                                      SelectionDAG &DAG) const {
5831   SDLoc DL(Op);
5832   auto *Load = cast<LoadSDNode>(Op);
5833 
5834   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5835                                         Load->getMemoryVT(),
5836                                         *Load->getMemOperand()) &&
5837          "Expecting a correctly-aligned load");
5838 
5839   MVT VT = Op.getSimpleValueType();
5840   MVT XLenVT = Subtarget.getXLenVT();
5841   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5842 
5843   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5844 
5845   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5846   SDValue IntID = DAG.getTargetConstant(
5847       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5848   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5849   if (!IsMaskOp)
5850     Ops.push_back(DAG.getUNDEF(ContainerVT));
5851   Ops.push_back(Load->getBasePtr());
5852   Ops.push_back(VL);
5853   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5854   SDValue NewLoad =
5855       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5856                               Load->getMemoryVT(), Load->getMemOperand());
5857 
5858   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5859   return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL);
5860 }
5861 
5862 SDValue
5863 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5864                                                       SelectionDAG &DAG) const {
5865   SDLoc DL(Op);
5866   auto *Store = cast<StoreSDNode>(Op);
5867 
5868   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5869                                         Store->getMemoryVT(),
5870                                         *Store->getMemOperand()) &&
5871          "Expecting a correctly-aligned store");
5872 
5873   SDValue StoreVal = Store->getValue();
5874   MVT VT = StoreVal.getSimpleValueType();
5875   MVT XLenVT = Subtarget.getXLenVT();
5876 
5877   // If the size less than a byte, we need to pad with zeros to make a byte.
5878   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5879     VT = MVT::v8i1;
5880     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5881                            DAG.getConstant(0, DL, VT), StoreVal,
5882                            DAG.getIntPtrConstant(0, DL));
5883   }
5884 
5885   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5886 
5887   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5888 
5889   SDValue NewValue =
5890       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5891 
5892   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5893   SDValue IntID = DAG.getTargetConstant(
5894       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5895   return DAG.getMemIntrinsicNode(
5896       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5897       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5898       Store->getMemoryVT(), Store->getMemOperand());
5899 }
5900 
5901 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5902                                              SelectionDAG &DAG) const {
5903   SDLoc DL(Op);
5904   MVT VT = Op.getSimpleValueType();
5905 
5906   const auto *MemSD = cast<MemSDNode>(Op);
5907   EVT MemVT = MemSD->getMemoryVT();
5908   MachineMemOperand *MMO = MemSD->getMemOperand();
5909   SDValue Chain = MemSD->getChain();
5910   SDValue BasePtr = MemSD->getBasePtr();
5911 
5912   SDValue Mask, PassThru, VL;
5913   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5914     Mask = VPLoad->getMask();
5915     PassThru = DAG.getUNDEF(VT);
5916     VL = VPLoad->getVectorLength();
5917   } else {
5918     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5919     Mask = MLoad->getMask();
5920     PassThru = MLoad->getPassThru();
5921   }
5922 
5923   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5924 
5925   MVT XLenVT = Subtarget.getXLenVT();
5926 
5927   MVT ContainerVT = VT;
5928   if (VT.isFixedLengthVector()) {
5929     ContainerVT = getContainerForFixedLengthVector(VT);
5930     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5931     if (!IsUnmasked) {
5932       MVT MaskVT = getMaskTypeFor(ContainerVT);
5933       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5934     }
5935   }
5936 
5937   if (!VL)
5938     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5939 
5940   unsigned IntID =
5941       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5942   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5943   if (IsUnmasked)
5944     Ops.push_back(DAG.getUNDEF(ContainerVT));
5945   else
5946     Ops.push_back(PassThru);
5947   Ops.push_back(BasePtr);
5948   if (!IsUnmasked)
5949     Ops.push_back(Mask);
5950   Ops.push_back(VL);
5951   if (!IsUnmasked)
5952     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5953 
5954   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5955 
5956   SDValue Result =
5957       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5958   Chain = Result.getValue(1);
5959 
5960   if (VT.isFixedLengthVector())
5961     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5962 
5963   return DAG.getMergeValues({Result, Chain}, DL);
5964 }
5965 
5966 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5967                                               SelectionDAG &DAG) const {
5968   SDLoc DL(Op);
5969 
5970   const auto *MemSD = cast<MemSDNode>(Op);
5971   EVT MemVT = MemSD->getMemoryVT();
5972   MachineMemOperand *MMO = MemSD->getMemOperand();
5973   SDValue Chain = MemSD->getChain();
5974   SDValue BasePtr = MemSD->getBasePtr();
5975   SDValue Val, Mask, VL;
5976 
5977   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5978     Val = VPStore->getValue();
5979     Mask = VPStore->getMask();
5980     VL = VPStore->getVectorLength();
5981   } else {
5982     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5983     Val = MStore->getValue();
5984     Mask = MStore->getMask();
5985   }
5986 
5987   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5988 
5989   MVT VT = Val.getSimpleValueType();
5990   MVT XLenVT = Subtarget.getXLenVT();
5991 
5992   MVT ContainerVT = VT;
5993   if (VT.isFixedLengthVector()) {
5994     ContainerVT = getContainerForFixedLengthVector(VT);
5995 
5996     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5997     if (!IsUnmasked) {
5998       MVT MaskVT = getMaskTypeFor(ContainerVT);
5999       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6000     }
6001   }
6002 
6003   if (!VL)
6004     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6005 
6006   unsigned IntID =
6007       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
6008   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6009   Ops.push_back(Val);
6010   Ops.push_back(BasePtr);
6011   if (!IsUnmasked)
6012     Ops.push_back(Mask);
6013   Ops.push_back(VL);
6014 
6015   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6016                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6017 }
6018 
6019 SDValue
6020 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
6021                                                       SelectionDAG &DAG) const {
6022   MVT InVT = Op.getOperand(0).getSimpleValueType();
6023   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
6024 
6025   MVT VT = Op.getSimpleValueType();
6026 
6027   SDValue Op1 =
6028       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
6029   SDValue Op2 =
6030       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6031 
6032   SDLoc DL(Op);
6033   SDValue VL =
6034       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
6035 
6036   MVT MaskVT = getMaskTypeFor(ContainerVT);
6037   SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
6038 
6039   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
6040                             Op.getOperand(2), Mask, VL);
6041 
6042   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
6043 }
6044 
6045 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
6046     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
6047   MVT VT = Op.getSimpleValueType();
6048 
6049   if (VT.getVectorElementType() == MVT::i1)
6050     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
6051 
6052   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
6053 }
6054 
6055 SDValue
6056 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
6057                                                       SelectionDAG &DAG) const {
6058   unsigned Opc;
6059   switch (Op.getOpcode()) {
6060   default: llvm_unreachable("Unexpected opcode!");
6061   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
6062   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
6063   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
6064   }
6065 
6066   return lowerToScalableOp(Op, DAG, Opc);
6067 }
6068 
6069 // Lower vector ABS to smax(X, sub(0, X)).
6070 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
6071   SDLoc DL(Op);
6072   MVT VT = Op.getSimpleValueType();
6073   SDValue X = Op.getOperand(0);
6074 
6075   assert(VT.isFixedLengthVector() && "Unexpected type");
6076 
6077   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6078   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
6079 
6080   SDValue Mask, VL;
6081   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6082 
6083   SDValue SplatZero = DAG.getNode(
6084       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
6085       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
6086   SDValue NegX =
6087       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
6088   SDValue Max =
6089       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
6090 
6091   return convertFromScalableVector(VT, Max, DAG, Subtarget);
6092 }
6093 
6094 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
6095     SDValue Op, SelectionDAG &DAG) const {
6096   SDLoc DL(Op);
6097   MVT VT = Op.getSimpleValueType();
6098   SDValue Mag = Op.getOperand(0);
6099   SDValue Sign = Op.getOperand(1);
6100   assert(Mag.getValueType() == Sign.getValueType() &&
6101          "Can only handle COPYSIGN with matching types.");
6102 
6103   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6104   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
6105   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
6106 
6107   SDValue Mask, VL;
6108   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6109 
6110   SDValue CopySign =
6111       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
6112 
6113   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
6114 }
6115 
6116 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
6117     SDValue Op, SelectionDAG &DAG) const {
6118   MVT VT = Op.getSimpleValueType();
6119   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6120 
6121   MVT I1ContainerVT =
6122       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6123 
6124   SDValue CC =
6125       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
6126   SDValue Op1 =
6127       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6128   SDValue Op2 =
6129       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
6130 
6131   SDLoc DL(Op);
6132   SDValue Mask, VL;
6133   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6134 
6135   SDValue Select =
6136       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
6137 
6138   return convertFromScalableVector(VT, Select, DAG, Subtarget);
6139 }
6140 
6141 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
6142                                                unsigned NewOpc,
6143                                                bool HasMask) const {
6144   MVT VT = Op.getSimpleValueType();
6145   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6146 
6147   // Create list of operands by converting existing ones to scalable types.
6148   SmallVector<SDValue, 6> Ops;
6149   for (const SDValue &V : Op->op_values()) {
6150     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6151 
6152     // Pass through non-vector operands.
6153     if (!V.getValueType().isVector()) {
6154       Ops.push_back(V);
6155       continue;
6156     }
6157 
6158     // "cast" fixed length vector to a scalable vector.
6159     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6160            "Only fixed length vectors are supported!");
6161     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6162   }
6163 
6164   SDLoc DL(Op);
6165   SDValue Mask, VL;
6166   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6167   if (HasMask)
6168     Ops.push_back(Mask);
6169   Ops.push_back(VL);
6170 
6171   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6172   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6173 }
6174 
6175 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6176 // * Operands of each node are assumed to be in the same order.
6177 // * The EVL operand is promoted from i32 to i64 on RV64.
6178 // * Fixed-length vectors are converted to their scalable-vector container
6179 //   types.
6180 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6181                                        unsigned RISCVISDOpc) const {
6182   SDLoc DL(Op);
6183   MVT VT = Op.getSimpleValueType();
6184   SmallVector<SDValue, 4> Ops;
6185 
6186   for (const auto &OpIdx : enumerate(Op->ops())) {
6187     SDValue V = OpIdx.value();
6188     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6189     // Pass through operands which aren't fixed-length vectors.
6190     if (!V.getValueType().isFixedLengthVector()) {
6191       Ops.push_back(V);
6192       continue;
6193     }
6194     // "cast" fixed length vector to a scalable vector.
6195     MVT OpVT = V.getSimpleValueType();
6196     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6197     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6198            "Only fixed length vectors are supported!");
6199     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6200   }
6201 
6202   if (!VT.isFixedLengthVector())
6203     return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags());
6204 
6205   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6206 
6207   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags());
6208 
6209   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6210 }
6211 
6212 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op,
6213                                               SelectionDAG &DAG) const {
6214   SDLoc DL(Op);
6215   MVT VT = Op.getSimpleValueType();
6216 
6217   SDValue Src = Op.getOperand(0);
6218   // NOTE: Mask is dropped.
6219   SDValue VL = Op.getOperand(2);
6220 
6221   MVT ContainerVT = VT;
6222   if (VT.isFixedLengthVector()) {
6223     ContainerVT = getContainerForFixedLengthVector(VT);
6224     MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6225     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6226   }
6227 
6228   MVT XLenVT = Subtarget.getXLenVT();
6229   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6230   SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6231                                   DAG.getUNDEF(ContainerVT), Zero, VL);
6232 
6233   SDValue SplatValue = DAG.getConstant(
6234       Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT);
6235   SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6236                               DAG.getUNDEF(ContainerVT), SplatValue, VL);
6237 
6238   SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src,
6239                                Splat, ZeroSplat, VL);
6240   if (!VT.isFixedLengthVector())
6241     return Result;
6242   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6243 }
6244 
6245 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op,
6246                                                 SelectionDAG &DAG) const {
6247   SDLoc DL(Op);
6248   MVT VT = Op.getSimpleValueType();
6249 
6250   SDValue Op1 = Op.getOperand(0);
6251   SDValue Op2 = Op.getOperand(1);
6252   ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6253   // NOTE: Mask is dropped.
6254   SDValue VL = Op.getOperand(4);
6255 
6256   MVT ContainerVT = VT;
6257   if (VT.isFixedLengthVector()) {
6258     ContainerVT = getContainerForFixedLengthVector(VT);
6259     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6260     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6261   }
6262 
6263   SDValue Result;
6264   SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
6265 
6266   switch (Condition) {
6267   default:
6268     break;
6269   // X != Y  --> (X^Y)
6270   case ISD::SETNE:
6271     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6272     break;
6273   // X == Y  --> ~(X^Y)
6274   case ISD::SETEQ: {
6275     SDValue Temp =
6276         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
6277     Result =
6278         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL);
6279     break;
6280   }
6281   // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
6282   // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
6283   case ISD::SETGT:
6284   case ISD::SETULT: {
6285     SDValue Temp =
6286         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6287     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL);
6288     break;
6289   }
6290   // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
6291   // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
6292   case ISD::SETLT:
6293   case ISD::SETUGT: {
6294     SDValue Temp =
6295         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6296     Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL);
6297     break;
6298   }
6299   // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
6300   // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
6301   case ISD::SETGE:
6302   case ISD::SETULE: {
6303     SDValue Temp =
6304         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
6305     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL);
6306     break;
6307   }
6308   // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
6309   // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
6310   case ISD::SETLE:
6311   case ISD::SETUGE: {
6312     SDValue Temp =
6313         DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
6314     Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL);
6315     break;
6316   }
6317   }
6318 
6319   if (!VT.isFixedLengthVector())
6320     return Result;
6321   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6322 }
6323 
6324 // Lower Floating-Point/Integer Type-Convert VP SDNodes
6325 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
6326                                                 unsigned RISCVISDOpc) const {
6327   SDLoc DL(Op);
6328 
6329   SDValue Src = Op.getOperand(0);
6330   SDValue Mask = Op.getOperand(1);
6331   SDValue VL = Op.getOperand(2);
6332 
6333   MVT DstVT = Op.getSimpleValueType();
6334   MVT SrcVT = Src.getSimpleValueType();
6335   if (DstVT.isFixedLengthVector()) {
6336     DstVT = getContainerForFixedLengthVector(DstVT);
6337     SrcVT = getContainerForFixedLengthVector(SrcVT);
6338     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6339     MVT MaskVT = getMaskTypeFor(DstVT);
6340     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6341   }
6342 
6343   unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL ||
6344                              RISCVISDOpc == RISCVISD::FP_TO_SINT_VL)
6345                                 ? RISCVISD::VSEXT_VL
6346                                 : RISCVISD::VZEXT_VL;
6347 
6348   unsigned DstEltSize = DstVT.getScalarSizeInBits();
6349   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
6350 
6351   SDValue Result;
6352   if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
6353     if (SrcVT.isInteger()) {
6354       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6355 
6356       // Do we need to do any pre-widening before converting?
6357       if (SrcEltSize == 1) {
6358         MVT IntVT = DstVT.changeVectorElementTypeToInteger();
6359         MVT XLenVT = Subtarget.getXLenVT();
6360         SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6361         SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6362                                         DAG.getUNDEF(IntVT), Zero, VL);
6363         SDValue One = DAG.getConstant(
6364             RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
6365         SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6366                                        DAG.getUNDEF(IntVT), One, VL);
6367         Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
6368                           ZeroSplat, VL);
6369       } else if (DstEltSize > (2 * SrcEltSize)) {
6370         // Widen before converting.
6371         MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
6372                                      DstVT.getVectorElementCount());
6373         Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL);
6374       }
6375 
6376       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6377     } else {
6378       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6379              "Wrong input/output vector types");
6380 
6381       // Convert f16 to f32 then convert f32 to i64.
6382       if (DstEltSize > (2 * SrcEltSize)) {
6383         assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6384         MVT InterimFVT =
6385             MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6386         Src =
6387             DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL);
6388       }
6389 
6390       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6391     }
6392   } else { // Narrowing + Conversion
6393     if (SrcVT.isInteger()) {
6394       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6395       // First do a narrowing convert to an FP type half the size, then round
6396       // the FP type to a small FP type if needed.
6397 
6398       MVT InterimFVT = DstVT;
6399       if (SrcEltSize > (2 * DstEltSize)) {
6400         assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
6401         assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6402         InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6403       }
6404 
6405       Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL);
6406 
6407       if (InterimFVT != DstVT) {
6408         Src = Result;
6409         Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL);
6410       }
6411     } else {
6412       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6413              "Wrong input/output vector types");
6414       // First do a narrowing conversion to an integer half the size, then
6415       // truncate if needed.
6416 
6417       if (DstEltSize == 1) {
6418         // First convert to the same size integer, then convert to mask using
6419         // setcc.
6420         assert(SrcEltSize >= 16 && "Unexpected FP type!");
6421         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize),
6422                                           DstVT.getVectorElementCount());
6423         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6424 
6425         // Compare the integer result to 0. The integer should be 0 or 1/-1,
6426         // otherwise the conversion was undefined.
6427         MVT XLenVT = Subtarget.getXLenVT();
6428         SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
6429         SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT,
6430                                 DAG.getUNDEF(InterimIVT), SplatZero);
6431         Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero,
6432                              DAG.getCondCode(ISD::SETNE), Mask, VL);
6433       } else {
6434         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6435                                           DstVT.getVectorElementCount());
6436 
6437         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6438 
6439         while (InterimIVT != DstVT) {
6440           SrcEltSize /= 2;
6441           Src = Result;
6442           InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6443                                         DstVT.getVectorElementCount());
6444           Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
6445                                Src, Mask, VL);
6446         }
6447       }
6448     }
6449   }
6450 
6451   MVT VT = Op.getSimpleValueType();
6452   if (!VT.isFixedLengthVector())
6453     return Result;
6454   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6455 }
6456 
6457 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6458                                             unsigned MaskOpc,
6459                                             unsigned VecOpc) const {
6460   MVT VT = Op.getSimpleValueType();
6461   if (VT.getVectorElementType() != MVT::i1)
6462     return lowerVPOp(Op, DAG, VecOpc);
6463 
6464   // It is safe to drop mask parameter as masked-off elements are undef.
6465   SDValue Op1 = Op->getOperand(0);
6466   SDValue Op2 = Op->getOperand(1);
6467   SDValue VL = Op->getOperand(3);
6468 
6469   MVT ContainerVT = VT;
6470   const bool IsFixed = VT.isFixedLengthVector();
6471   if (IsFixed) {
6472     ContainerVT = getContainerForFixedLengthVector(VT);
6473     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6474     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6475   }
6476 
6477   SDLoc DL(Op);
6478   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6479   if (!IsFixed)
6480     return Val;
6481   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6482 }
6483 
6484 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6485 // matched to a RVV indexed load. The RVV indexed load instructions only
6486 // support the "unsigned unscaled" addressing mode; indices are implicitly
6487 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6488 // signed or scaled indexing is extended to the XLEN value type and scaled
6489 // accordingly.
6490 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6491                                                SelectionDAG &DAG) const {
6492   SDLoc DL(Op);
6493   MVT VT = Op.getSimpleValueType();
6494 
6495   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6496   EVT MemVT = MemSD->getMemoryVT();
6497   MachineMemOperand *MMO = MemSD->getMemOperand();
6498   SDValue Chain = MemSD->getChain();
6499   SDValue BasePtr = MemSD->getBasePtr();
6500 
6501   ISD::LoadExtType LoadExtType;
6502   SDValue Index, Mask, PassThru, VL;
6503 
6504   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6505     Index = VPGN->getIndex();
6506     Mask = VPGN->getMask();
6507     PassThru = DAG.getUNDEF(VT);
6508     VL = VPGN->getVectorLength();
6509     // VP doesn't support extending loads.
6510     LoadExtType = ISD::NON_EXTLOAD;
6511   } else {
6512     // Else it must be a MGATHER.
6513     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6514     Index = MGN->getIndex();
6515     Mask = MGN->getMask();
6516     PassThru = MGN->getPassThru();
6517     LoadExtType = MGN->getExtensionType();
6518   }
6519 
6520   MVT IndexVT = Index.getSimpleValueType();
6521   MVT XLenVT = Subtarget.getXLenVT();
6522 
6523   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6524          "Unexpected VTs!");
6525   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6526   // Targets have to explicitly opt-in for extending vector loads.
6527   assert(LoadExtType == ISD::NON_EXTLOAD &&
6528          "Unexpected extending MGATHER/VP_GATHER");
6529   (void)LoadExtType;
6530 
6531   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6532   // the selection of the masked intrinsics doesn't do this for us.
6533   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6534 
6535   MVT ContainerVT = VT;
6536   if (VT.isFixedLengthVector()) {
6537     ContainerVT = getContainerForFixedLengthVector(VT);
6538     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6539                                ContainerVT.getVectorElementCount());
6540 
6541     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6542 
6543     if (!IsUnmasked) {
6544       MVT MaskVT = getMaskTypeFor(ContainerVT);
6545       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6546       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6547     }
6548   }
6549 
6550   if (!VL)
6551     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6552 
6553   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6554     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6555     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6556                                    VL);
6557     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6558                         TrueMask, VL);
6559   }
6560 
6561   unsigned IntID =
6562       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6563   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6564   if (IsUnmasked)
6565     Ops.push_back(DAG.getUNDEF(ContainerVT));
6566   else
6567     Ops.push_back(PassThru);
6568   Ops.push_back(BasePtr);
6569   Ops.push_back(Index);
6570   if (!IsUnmasked)
6571     Ops.push_back(Mask);
6572   Ops.push_back(VL);
6573   if (!IsUnmasked)
6574     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6575 
6576   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6577   SDValue Result =
6578       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6579   Chain = Result.getValue(1);
6580 
6581   if (VT.isFixedLengthVector())
6582     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6583 
6584   return DAG.getMergeValues({Result, Chain}, DL);
6585 }
6586 
6587 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6588 // matched to a RVV indexed store. The RVV indexed store instructions only
6589 // support the "unsigned unscaled" addressing mode; indices are implicitly
6590 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6591 // signed or scaled indexing is extended to the XLEN value type and scaled
6592 // accordingly.
6593 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6594                                                 SelectionDAG &DAG) const {
6595   SDLoc DL(Op);
6596   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6597   EVT MemVT = MemSD->getMemoryVT();
6598   MachineMemOperand *MMO = MemSD->getMemOperand();
6599   SDValue Chain = MemSD->getChain();
6600   SDValue BasePtr = MemSD->getBasePtr();
6601 
6602   bool IsTruncatingStore = false;
6603   SDValue Index, Mask, Val, VL;
6604 
6605   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6606     Index = VPSN->getIndex();
6607     Mask = VPSN->getMask();
6608     Val = VPSN->getValue();
6609     VL = VPSN->getVectorLength();
6610     // VP doesn't support truncating stores.
6611     IsTruncatingStore = false;
6612   } else {
6613     // Else it must be a MSCATTER.
6614     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6615     Index = MSN->getIndex();
6616     Mask = MSN->getMask();
6617     Val = MSN->getValue();
6618     IsTruncatingStore = MSN->isTruncatingStore();
6619   }
6620 
6621   MVT VT = Val.getSimpleValueType();
6622   MVT IndexVT = Index.getSimpleValueType();
6623   MVT XLenVT = Subtarget.getXLenVT();
6624 
6625   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6626          "Unexpected VTs!");
6627   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6628   // Targets have to explicitly opt-in for extending vector loads and
6629   // truncating vector stores.
6630   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6631   (void)IsTruncatingStore;
6632 
6633   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6634   // the selection of the masked intrinsics doesn't do this for us.
6635   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6636 
6637   MVT ContainerVT = VT;
6638   if (VT.isFixedLengthVector()) {
6639     ContainerVT = getContainerForFixedLengthVector(VT);
6640     IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6641                                ContainerVT.getVectorElementCount());
6642 
6643     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6644     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6645 
6646     if (!IsUnmasked) {
6647       MVT MaskVT = getMaskTypeFor(ContainerVT);
6648       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6649     }
6650   }
6651 
6652   if (!VL)
6653     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6654 
6655   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6656     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6657     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6658                                    VL);
6659     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6660                         TrueMask, VL);
6661   }
6662 
6663   unsigned IntID =
6664       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6665   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6666   Ops.push_back(Val);
6667   Ops.push_back(BasePtr);
6668   Ops.push_back(Index);
6669   if (!IsUnmasked)
6670     Ops.push_back(Mask);
6671   Ops.push_back(VL);
6672 
6673   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6674                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6675 }
6676 
6677 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6678                                                SelectionDAG &DAG) const {
6679   const MVT XLenVT = Subtarget.getXLenVT();
6680   SDLoc DL(Op);
6681   SDValue Chain = Op->getOperand(0);
6682   SDValue SysRegNo = DAG.getTargetConstant(
6683       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6684   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6685   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6686 
6687   // Encoding used for rounding mode in RISCV differs from that used in
6688   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6689   // table, which consists of a sequence of 4-bit fields, each representing
6690   // corresponding FLT_ROUNDS mode.
6691   static const int Table =
6692       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6693       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6694       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6695       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6696       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6697 
6698   SDValue Shift =
6699       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6700   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6701                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6702   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6703                                DAG.getConstant(7, DL, XLenVT));
6704 
6705   return DAG.getMergeValues({Masked, Chain}, DL);
6706 }
6707 
6708 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6709                                                SelectionDAG &DAG) const {
6710   const MVT XLenVT = Subtarget.getXLenVT();
6711   SDLoc DL(Op);
6712   SDValue Chain = Op->getOperand(0);
6713   SDValue RMValue = Op->getOperand(1);
6714   SDValue SysRegNo = DAG.getTargetConstant(
6715       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6716 
6717   // Encoding used for rounding mode in RISCV differs from that used in
6718   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6719   // a table, which consists of a sequence of 4-bit fields, each representing
6720   // corresponding RISCV mode.
6721   static const unsigned Table =
6722       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6723       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6724       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6725       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6726       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6727 
6728   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6729                               DAG.getConstant(2, DL, XLenVT));
6730   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6731                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6732   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6733                         DAG.getConstant(0x7, DL, XLenVT));
6734   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6735                      RMValue);
6736 }
6737 
6738 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
6739                                                SelectionDAG &DAG) const {
6740   MachineFunction &MF = DAG.getMachineFunction();
6741 
6742   bool isRISCV64 = Subtarget.is64Bit();
6743   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6744 
6745   int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false);
6746   return DAG.getFrameIndex(FI, PtrVT);
6747 }
6748 
6749 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6750   switch (IntNo) {
6751   default:
6752     llvm_unreachable("Unexpected Intrinsic");
6753   case Intrinsic::riscv_bcompress:
6754     return RISCVISD::BCOMPRESSW;
6755   case Intrinsic::riscv_bdecompress:
6756     return RISCVISD::BDECOMPRESSW;
6757   case Intrinsic::riscv_bfp:
6758     return RISCVISD::BFPW;
6759   case Intrinsic::riscv_fsl:
6760     return RISCVISD::FSLW;
6761   case Intrinsic::riscv_fsr:
6762     return RISCVISD::FSRW;
6763   }
6764 }
6765 
6766 // Converts the given intrinsic to a i64 operation with any extension.
6767 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6768                                          unsigned IntNo) {
6769   SDLoc DL(N);
6770   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6771   // Deal with the Instruction Operands
6772   SmallVector<SDValue, 3> NewOps;
6773   for (SDValue Op : drop_begin(N->ops()))
6774     // Promote the operand to i64 type
6775     NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op));
6776   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps);
6777   // ReplaceNodeResults requires we maintain the same type for the return value.
6778   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6779 }
6780 
6781 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6782 // form of the given Opcode.
6783 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6784   switch (Opcode) {
6785   default:
6786     llvm_unreachable("Unexpected opcode");
6787   case ISD::SHL:
6788     return RISCVISD::SLLW;
6789   case ISD::SRA:
6790     return RISCVISD::SRAW;
6791   case ISD::SRL:
6792     return RISCVISD::SRLW;
6793   case ISD::SDIV:
6794     return RISCVISD::DIVW;
6795   case ISD::UDIV:
6796     return RISCVISD::DIVUW;
6797   case ISD::UREM:
6798     return RISCVISD::REMUW;
6799   case ISD::ROTL:
6800     return RISCVISD::ROLW;
6801   case ISD::ROTR:
6802     return RISCVISD::RORW;
6803   }
6804 }
6805 
6806 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6807 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6808 // otherwise be promoted to i64, making it difficult to select the
6809 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6810 // type i8/i16/i32 is lost.
6811 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6812                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6813   SDLoc DL(N);
6814   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6815   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6816   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6817   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6818   // ReplaceNodeResults requires we maintain the same type for the return value.
6819   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6820 }
6821 
6822 // Converts the given 32-bit operation to a i64 operation with signed extension
6823 // semantic to reduce the signed extension instructions.
6824 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6825   SDLoc DL(N);
6826   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6827   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6828   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6829   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6830                                DAG.getValueType(MVT::i32));
6831   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6832 }
6833 
6834 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6835                                              SmallVectorImpl<SDValue> &Results,
6836                                              SelectionDAG &DAG) const {
6837   SDLoc DL(N);
6838   switch (N->getOpcode()) {
6839   default:
6840     llvm_unreachable("Don't know how to custom type legalize this operation!");
6841   case ISD::STRICT_FP_TO_SINT:
6842   case ISD::STRICT_FP_TO_UINT:
6843   case ISD::FP_TO_SINT:
6844   case ISD::FP_TO_UINT: {
6845     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6846            "Unexpected custom legalisation");
6847     bool IsStrict = N->isStrictFPOpcode();
6848     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6849                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6850     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6851     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6852         TargetLowering::TypeSoftenFloat) {
6853       if (!isTypeLegal(Op0.getValueType()))
6854         return;
6855       if (IsStrict) {
6856         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6857                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6858         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6859         SDValue Res = DAG.getNode(
6860             Opc, DL, VTs, N->getOperand(0), Op0,
6861             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6862         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6863         Results.push_back(Res.getValue(1));
6864         return;
6865       }
6866       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6867       SDValue Res =
6868           DAG.getNode(Opc, DL, MVT::i64, Op0,
6869                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6870       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6871       return;
6872     }
6873     // If the FP type needs to be softened, emit a library call using the 'si'
6874     // version. If we left it to default legalization we'd end up with 'di'. If
6875     // the FP type doesn't need to be softened just let generic type
6876     // legalization promote the result type.
6877     RTLIB::Libcall LC;
6878     if (IsSigned)
6879       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6880     else
6881       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6882     MakeLibCallOptions CallOptions;
6883     EVT OpVT = Op0.getValueType();
6884     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6885     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6886     SDValue Result;
6887     std::tie(Result, Chain) =
6888         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6889     Results.push_back(Result);
6890     if (IsStrict)
6891       Results.push_back(Chain);
6892     break;
6893   }
6894   case ISD::READCYCLECOUNTER: {
6895     assert(!Subtarget.is64Bit() &&
6896            "READCYCLECOUNTER only has custom type legalization on riscv32");
6897 
6898     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6899     SDValue RCW =
6900         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6901 
6902     Results.push_back(
6903         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6904     Results.push_back(RCW.getValue(2));
6905     break;
6906   }
6907   case ISD::MUL: {
6908     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6909     unsigned XLen = Subtarget.getXLen();
6910     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6911     if (Size > XLen) {
6912       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6913       SDValue LHS = N->getOperand(0);
6914       SDValue RHS = N->getOperand(1);
6915       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6916 
6917       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6918       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6919       // We need exactly one side to be unsigned.
6920       if (LHSIsU == RHSIsU)
6921         return;
6922 
6923       auto MakeMULPair = [&](SDValue S, SDValue U) {
6924         MVT XLenVT = Subtarget.getXLenVT();
6925         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6926         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6927         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6928         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6929         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6930       };
6931 
6932       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6933       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6934 
6935       // The other operand should be signed, but still prefer MULH when
6936       // possible.
6937       if (RHSIsU && LHSIsS && !RHSIsS)
6938         Results.push_back(MakeMULPair(LHS, RHS));
6939       else if (LHSIsU && RHSIsS && !LHSIsS)
6940         Results.push_back(MakeMULPair(RHS, LHS));
6941 
6942       return;
6943     }
6944     LLVM_FALLTHROUGH;
6945   }
6946   case ISD::ADD:
6947   case ISD::SUB:
6948     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6949            "Unexpected custom legalisation");
6950     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6951     break;
6952   case ISD::SHL:
6953   case ISD::SRA:
6954   case ISD::SRL:
6955     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6956            "Unexpected custom legalisation");
6957     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6958       // If we can use a BSET instruction, allow default promotion to apply.
6959       if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() &&
6960           isOneConstant(N->getOperand(0)))
6961         break;
6962       Results.push_back(customLegalizeToWOp(N, DAG));
6963       break;
6964     }
6965 
6966     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6967     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6968     // shift amount.
6969     if (N->getOpcode() == ISD::SHL) {
6970       SDLoc DL(N);
6971       SDValue NewOp0 =
6972           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6973       SDValue NewOp1 =
6974           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6975       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6976       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6977                                    DAG.getValueType(MVT::i32));
6978       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6979     }
6980 
6981     break;
6982   case ISD::ROTL:
6983   case ISD::ROTR:
6984     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6985            "Unexpected custom legalisation");
6986     Results.push_back(customLegalizeToWOp(N, DAG));
6987     break;
6988   case ISD::CTTZ:
6989   case ISD::CTTZ_ZERO_UNDEF:
6990   case ISD::CTLZ:
6991   case ISD::CTLZ_ZERO_UNDEF: {
6992     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6993            "Unexpected custom legalisation");
6994 
6995     SDValue NewOp0 =
6996         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6997     bool IsCTZ =
6998         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6999     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
7000     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
7001     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7002     return;
7003   }
7004   case ISD::SDIV:
7005   case ISD::UDIV:
7006   case ISD::UREM: {
7007     MVT VT = N->getSimpleValueType(0);
7008     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
7009            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
7010            "Unexpected custom legalisation");
7011     // Don't promote division/remainder by constant since we should expand those
7012     // to multiply by magic constant.
7013     // FIXME: What if the expansion is disabled for minsize.
7014     if (N->getOperand(1).getOpcode() == ISD::Constant)
7015       return;
7016 
7017     // If the input is i32, use ANY_EXTEND since the W instructions don't read
7018     // the upper 32 bits. For other types we need to sign or zero extend
7019     // based on the opcode.
7020     unsigned ExtOpc = ISD::ANY_EXTEND;
7021     if (VT != MVT::i32)
7022       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
7023                                            : ISD::ZERO_EXTEND;
7024 
7025     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
7026     break;
7027   }
7028   case ISD::UADDO:
7029   case ISD::USUBO: {
7030     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7031            "Unexpected custom legalisation");
7032     bool IsAdd = N->getOpcode() == ISD::UADDO;
7033     // Create an ADDW or SUBW.
7034     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7035     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7036     SDValue Res =
7037         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
7038     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
7039                       DAG.getValueType(MVT::i32));
7040 
7041     SDValue Overflow;
7042     if (IsAdd && isOneConstant(RHS)) {
7043       // Special case uaddo X, 1 overflowed if the addition result is 0.
7044       // The general case (X + C) < C is not necessarily beneficial. Although we
7045       // reduce the live range of X, we may introduce the materialization of
7046       // constant C, especially when the setcc result is used by branch. We have
7047       // no compare with constant and branch instructions.
7048       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res,
7049                               DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ);
7050     } else {
7051       // Sign extend the LHS and perform an unsigned compare with the ADDW
7052       // result. Since the inputs are sign extended from i32, this is equivalent
7053       // to comparing the lower 32 bits.
7054       LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
7055       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
7056                               IsAdd ? ISD::SETULT : ISD::SETUGT);
7057     }
7058 
7059     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7060     Results.push_back(Overflow);
7061     return;
7062   }
7063   case ISD::UADDSAT:
7064   case ISD::USUBSAT: {
7065     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7066            "Unexpected custom legalisation");
7067     if (Subtarget.hasStdExtZbb()) {
7068       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
7069       // sign extend allows overflow of the lower 32 bits to be detected on
7070       // the promoted size.
7071       SDValue LHS =
7072           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
7073       SDValue RHS =
7074           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
7075       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
7076       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7077       return;
7078     }
7079 
7080     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
7081     // promotion for UADDO/USUBO.
7082     Results.push_back(expandAddSubSat(N, DAG));
7083     return;
7084   }
7085   case ISD::ABS: {
7086     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7087            "Unexpected custom legalisation");
7088 
7089     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
7090 
7091     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7092 
7093     // Freeze the source so we can increase it's use count.
7094     Src = DAG.getFreeze(Src);
7095 
7096     // Copy sign bit to all bits using the sraiw pattern.
7097     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
7098                                    DAG.getValueType(MVT::i32));
7099     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
7100                            DAG.getConstant(31, DL, MVT::i64));
7101 
7102     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
7103     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
7104 
7105     // NOTE: The result is only required to be anyextended, but sext is
7106     // consistent with type legalization of sub.
7107     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
7108                          DAG.getValueType(MVT::i32));
7109     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
7110     return;
7111   }
7112   case ISD::BITCAST: {
7113     EVT VT = N->getValueType(0);
7114     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
7115     SDValue Op0 = N->getOperand(0);
7116     EVT Op0VT = Op0.getValueType();
7117     MVT XLenVT = Subtarget.getXLenVT();
7118     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
7119       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
7120       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
7121     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
7122                Subtarget.hasStdExtF()) {
7123       SDValue FPConv =
7124           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
7125       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
7126     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
7127                isTypeLegal(Op0VT)) {
7128       // Custom-legalize bitcasts from fixed-length vector types to illegal
7129       // scalar types in order to improve codegen. Bitcast the vector to a
7130       // one-element vector type whose element type is the same as the result
7131       // type, and extract the first element.
7132       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
7133       if (isTypeLegal(BVT)) {
7134         SDValue BVec = DAG.getBitcast(BVT, Op0);
7135         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
7136                                       DAG.getConstant(0, DL, XLenVT)));
7137       }
7138     }
7139     break;
7140   }
7141   case RISCVISD::GREV:
7142   case RISCVISD::GORC:
7143   case RISCVISD::SHFL: {
7144     MVT VT = N->getSimpleValueType(0);
7145     MVT XLenVT = Subtarget.getXLenVT();
7146     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
7147            "Unexpected custom legalisation");
7148     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
7149     assert((Subtarget.hasStdExtZbp() ||
7150             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
7151              N->getConstantOperandVal(1) == 7)) &&
7152            "Unexpected extension");
7153     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7154     SDValue NewOp1 =
7155         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
7156     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
7157     // ReplaceNodeResults requires we maintain the same type for the return
7158     // value.
7159     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
7160     break;
7161   }
7162   case ISD::BSWAP:
7163   case ISD::BITREVERSE: {
7164     MVT VT = N->getSimpleValueType(0);
7165     MVT XLenVT = Subtarget.getXLenVT();
7166     assert((VT == MVT::i8 || VT == MVT::i16 ||
7167             (VT == MVT::i32 && Subtarget.is64Bit())) &&
7168            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
7169     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7170     unsigned Imm = VT.getSizeInBits() - 1;
7171     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
7172     if (N->getOpcode() == ISD::BSWAP)
7173       Imm &= ~0x7U;
7174     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
7175                                 DAG.getConstant(Imm, DL, XLenVT));
7176     // ReplaceNodeResults requires we maintain the same type for the return
7177     // value.
7178     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
7179     break;
7180   }
7181   case ISD::FSHL:
7182   case ISD::FSHR: {
7183     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7184            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
7185     SDValue NewOp0 =
7186         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7187     SDValue NewOp1 =
7188         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7189     SDValue NewShAmt =
7190         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7191     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
7192     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
7193     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
7194                            DAG.getConstant(0x1f, DL, MVT::i64));
7195     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
7196     // instruction use different orders. fshl will return its first operand for
7197     // shift of zero, fshr will return its second operand. fsl and fsr both
7198     // return rs1 so the ISD nodes need to have different operand orders.
7199     // Shift amount is in rs2.
7200     unsigned Opc = RISCVISD::FSLW;
7201     if (N->getOpcode() == ISD::FSHR) {
7202       std::swap(NewOp0, NewOp1);
7203       Opc = RISCVISD::FSRW;
7204     }
7205     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
7206     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
7207     break;
7208   }
7209   case ISD::EXTRACT_VECTOR_ELT: {
7210     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
7211     // type is illegal (currently only vXi64 RV32).
7212     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
7213     // transferred to the destination register. We issue two of these from the
7214     // upper- and lower- halves of the SEW-bit vector element, slid down to the
7215     // first element.
7216     SDValue Vec = N->getOperand(0);
7217     SDValue Idx = N->getOperand(1);
7218 
7219     // The vector type hasn't been legalized yet so we can't issue target
7220     // specific nodes if it needs legalization.
7221     // FIXME: We would manually legalize if it's important.
7222     if (!isTypeLegal(Vec.getValueType()))
7223       return;
7224 
7225     MVT VecVT = Vec.getSimpleValueType();
7226 
7227     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7228            VecVT.getVectorElementType() == MVT::i64 &&
7229            "Unexpected EXTRACT_VECTOR_ELT legalization");
7230 
7231     // If this is a fixed vector, we need to convert it to a scalable vector.
7232     MVT ContainerVT = VecVT;
7233     if (VecVT.isFixedLengthVector()) {
7234       ContainerVT = getContainerForFixedLengthVector(VecVT);
7235       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7236     }
7237 
7238     MVT XLenVT = Subtarget.getXLenVT();
7239 
7240     // Use a VL of 1 to avoid processing more elements than we need.
7241     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7242     SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
7243 
7244     // Unless the index is known to be 0, we must slide the vector down to get
7245     // the desired element into index 0.
7246     if (!isNullConstant(Idx)) {
7247       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7248                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7249     }
7250 
7251     // Extract the lower XLEN bits of the correct vector element.
7252     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7253 
7254     // To extract the upper XLEN bits of the vector element, shift the first
7255     // element right by 32 bits and re-extract the lower XLEN bits.
7256     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7257                                      DAG.getUNDEF(ContainerVT),
7258                                      DAG.getConstant(32, DL, XLenVT), VL);
7259     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7260                                  ThirtyTwoV, Mask, VL);
7261 
7262     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7263 
7264     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7265     break;
7266   }
7267   case ISD::INTRINSIC_WO_CHAIN: {
7268     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7269     switch (IntNo) {
7270     default:
7271       llvm_unreachable(
7272           "Don't know how to custom type legalize this intrinsic!");
7273     case Intrinsic::riscv_grev:
7274     case Intrinsic::riscv_gorc: {
7275       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7276              "Unexpected custom legalisation");
7277       SDValue NewOp1 =
7278           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7279       SDValue NewOp2 =
7280           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7281       unsigned Opc =
7282           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7283       // If the control is a constant, promote the node by clearing any extra
7284       // bits bits in the control. isel will form greviw/gorciw if the result is
7285       // sign extended.
7286       if (isa<ConstantSDNode>(NewOp2)) {
7287         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7288                              DAG.getConstant(0x1f, DL, MVT::i64));
7289         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7290       }
7291       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7292       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7293       break;
7294     }
7295     case Intrinsic::riscv_bcompress:
7296     case Intrinsic::riscv_bdecompress:
7297     case Intrinsic::riscv_bfp:
7298     case Intrinsic::riscv_fsl:
7299     case Intrinsic::riscv_fsr: {
7300       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7301              "Unexpected custom legalisation");
7302       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7303       break;
7304     }
7305     case Intrinsic::riscv_orc_b: {
7306       // Lower to the GORCI encoding for orc.b with the operand extended.
7307       SDValue NewOp =
7308           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7309       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7310                                 DAG.getConstant(7, DL, MVT::i64));
7311       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7312       return;
7313     }
7314     case Intrinsic::riscv_shfl:
7315     case Intrinsic::riscv_unshfl: {
7316       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7317              "Unexpected custom legalisation");
7318       SDValue NewOp1 =
7319           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7320       SDValue NewOp2 =
7321           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7322       unsigned Opc =
7323           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7324       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7325       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7326       // will be shuffled the same way as the lower 32 bit half, but the two
7327       // halves won't cross.
7328       if (isa<ConstantSDNode>(NewOp2)) {
7329         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7330                              DAG.getConstant(0xf, DL, MVT::i64));
7331         Opc =
7332             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7333       }
7334       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7335       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7336       break;
7337     }
7338     case Intrinsic::riscv_vmv_x_s: {
7339       EVT VT = N->getValueType(0);
7340       MVT XLenVT = Subtarget.getXLenVT();
7341       if (VT.bitsLT(XLenVT)) {
7342         // Simple case just extract using vmv.x.s and truncate.
7343         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7344                                       Subtarget.getXLenVT(), N->getOperand(1));
7345         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7346         return;
7347       }
7348 
7349       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7350              "Unexpected custom legalization");
7351 
7352       // We need to do the move in two steps.
7353       SDValue Vec = N->getOperand(1);
7354       MVT VecVT = Vec.getSimpleValueType();
7355 
7356       // First extract the lower XLEN bits of the element.
7357       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7358 
7359       // To extract the upper XLEN bits of the vector element, shift the first
7360       // element right by 32 bits and re-extract the lower XLEN bits.
7361       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7362       SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG);
7363 
7364       SDValue ThirtyTwoV =
7365           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7366                       DAG.getConstant(32, DL, XLenVT), VL);
7367       SDValue LShr32 =
7368           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7369       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7370 
7371       Results.push_back(
7372           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7373       break;
7374     }
7375     }
7376     break;
7377   }
7378   case ISD::VECREDUCE_ADD:
7379   case ISD::VECREDUCE_AND:
7380   case ISD::VECREDUCE_OR:
7381   case ISD::VECREDUCE_XOR:
7382   case ISD::VECREDUCE_SMAX:
7383   case ISD::VECREDUCE_UMAX:
7384   case ISD::VECREDUCE_SMIN:
7385   case ISD::VECREDUCE_UMIN:
7386     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7387       Results.push_back(V);
7388     break;
7389   case ISD::VP_REDUCE_ADD:
7390   case ISD::VP_REDUCE_AND:
7391   case ISD::VP_REDUCE_OR:
7392   case ISD::VP_REDUCE_XOR:
7393   case ISD::VP_REDUCE_SMAX:
7394   case ISD::VP_REDUCE_UMAX:
7395   case ISD::VP_REDUCE_SMIN:
7396   case ISD::VP_REDUCE_UMIN:
7397     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7398       Results.push_back(V);
7399     break;
7400   case ISD::FLT_ROUNDS_: {
7401     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7402     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7403     Results.push_back(Res.getValue(0));
7404     Results.push_back(Res.getValue(1));
7405     break;
7406   }
7407   }
7408 }
7409 
7410 // A structure to hold one of the bit-manipulation patterns below. Together, a
7411 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7412 //   (or (and (shl x, 1), 0xAAAAAAAA),
7413 //       (and (srl x, 1), 0x55555555))
7414 struct RISCVBitmanipPat {
7415   SDValue Op;
7416   unsigned ShAmt;
7417   bool IsSHL;
7418 
7419   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7420     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7421   }
7422 };
7423 
7424 // Matches patterns of the form
7425 //   (and (shl x, C2), (C1 << C2))
7426 //   (and (srl x, C2), C1)
7427 //   (shl (and x, C1), C2)
7428 //   (srl (and x, (C1 << C2)), C2)
7429 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7430 // The expected masks for each shift amount are specified in BitmanipMasks where
7431 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7432 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7433 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7434 // XLen is 64.
7435 static Optional<RISCVBitmanipPat>
7436 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7437   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7438          "Unexpected number of masks");
7439   Optional<uint64_t> Mask;
7440   // Optionally consume a mask around the shift operation.
7441   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7442     Mask = Op.getConstantOperandVal(1);
7443     Op = Op.getOperand(0);
7444   }
7445   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7446     return None;
7447   bool IsSHL = Op.getOpcode() == ISD::SHL;
7448 
7449   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7450     return None;
7451   uint64_t ShAmt = Op.getConstantOperandVal(1);
7452 
7453   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7454   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7455     return None;
7456   // If we don't have enough masks for 64 bit, then we must be trying to
7457   // match SHFL so we're only allowed to shift 1/4 of the width.
7458   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7459     return None;
7460 
7461   SDValue Src = Op.getOperand(0);
7462 
7463   // The expected mask is shifted left when the AND is found around SHL
7464   // patterns.
7465   //   ((x >> 1) & 0x55555555)
7466   //   ((x << 1) & 0xAAAAAAAA)
7467   bool SHLExpMask = IsSHL;
7468 
7469   if (!Mask) {
7470     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7471     // the mask is all ones: consume that now.
7472     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7473       Mask = Src.getConstantOperandVal(1);
7474       Src = Src.getOperand(0);
7475       // The expected mask is now in fact shifted left for SRL, so reverse the
7476       // decision.
7477       //   ((x & 0xAAAAAAAA) >> 1)
7478       //   ((x & 0x55555555) << 1)
7479       SHLExpMask = !SHLExpMask;
7480     } else {
7481       // Use a default shifted mask of all-ones if there's no AND, truncated
7482       // down to the expected width. This simplifies the logic later on.
7483       Mask = maskTrailingOnes<uint64_t>(Width);
7484       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7485     }
7486   }
7487 
7488   unsigned MaskIdx = Log2_32(ShAmt);
7489   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7490 
7491   if (SHLExpMask)
7492     ExpMask <<= ShAmt;
7493 
7494   if (Mask != ExpMask)
7495     return None;
7496 
7497   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7498 }
7499 
7500 // Matches any of the following bit-manipulation patterns:
7501 //   (and (shl x, 1), (0x55555555 << 1))
7502 //   (and (srl x, 1), 0x55555555)
7503 //   (shl (and x, 0x55555555), 1)
7504 //   (srl (and x, (0x55555555 << 1)), 1)
7505 // where the shift amount and mask may vary thus:
7506 //   [1]  = 0x55555555 / 0xAAAAAAAA
7507 //   [2]  = 0x33333333 / 0xCCCCCCCC
7508 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7509 //   [8]  = 0x00FF00FF / 0xFF00FF00
7510 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7511 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7512 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7513   // These are the unshifted masks which we use to match bit-manipulation
7514   // patterns. They may be shifted left in certain circumstances.
7515   static const uint64_t BitmanipMasks[] = {
7516       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7517       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7518 
7519   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7520 }
7521 
7522 // Try to fold (<bop> x, (reduction.<bop> vec, start))
7523 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) {
7524   auto BinOpToRVVReduce = [](unsigned Opc) {
7525     switch (Opc) {
7526     default:
7527       llvm_unreachable("Unhandled binary to transfrom reduction");
7528     case ISD::ADD:
7529       return RISCVISD::VECREDUCE_ADD_VL;
7530     case ISD::UMAX:
7531       return RISCVISD::VECREDUCE_UMAX_VL;
7532     case ISD::SMAX:
7533       return RISCVISD::VECREDUCE_SMAX_VL;
7534     case ISD::UMIN:
7535       return RISCVISD::VECREDUCE_UMIN_VL;
7536     case ISD::SMIN:
7537       return RISCVISD::VECREDUCE_SMIN_VL;
7538     case ISD::AND:
7539       return RISCVISD::VECREDUCE_AND_VL;
7540     case ISD::OR:
7541       return RISCVISD::VECREDUCE_OR_VL;
7542     case ISD::XOR:
7543       return RISCVISD::VECREDUCE_XOR_VL;
7544     case ISD::FADD:
7545       return RISCVISD::VECREDUCE_FADD_VL;
7546     case ISD::FMAXNUM:
7547       return RISCVISD::VECREDUCE_FMAX_VL;
7548     case ISD::FMINNUM:
7549       return RISCVISD::VECREDUCE_FMIN_VL;
7550     }
7551   };
7552 
7553   auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) {
7554     return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7555            isNullConstant(V.getOperand(1)) &&
7556            V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc);
7557   };
7558 
7559   unsigned Opc = N->getOpcode();
7560   unsigned ReduceIdx;
7561   if (IsReduction(N->getOperand(0), Opc))
7562     ReduceIdx = 0;
7563   else if (IsReduction(N->getOperand(1), Opc))
7564     ReduceIdx = 1;
7565   else
7566     return SDValue();
7567 
7568   // Skip if FADD disallows reassociation but the combiner needs.
7569   if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation())
7570     return SDValue();
7571 
7572   SDValue Extract = N->getOperand(ReduceIdx);
7573   SDValue Reduce = Extract.getOperand(0);
7574   if (!Reduce.hasOneUse())
7575     return SDValue();
7576 
7577   SDValue ScalarV = Reduce.getOperand(2);
7578 
7579   // Make sure that ScalarV is a splat with VL=1.
7580   if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL &&
7581       ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL &&
7582       ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL)
7583     return SDValue();
7584 
7585   if (!isOneConstant(ScalarV.getOperand(2)))
7586     return SDValue();
7587 
7588   // TODO: Deal with value other than neutral element.
7589   auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) {
7590     if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() &&
7591         isNullFPConstant(V))
7592       return true;
7593     return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(),
7594                                  N->getFlags()) == V;
7595   };
7596 
7597   // Check the scalar of ScalarV is neutral element
7598   if (!IsRVVNeutralElement(N, ScalarV.getOperand(1)))
7599     return SDValue();
7600 
7601   if (!ScalarV.hasOneUse())
7602     return SDValue();
7603 
7604   EVT SplatVT = ScalarV.getValueType();
7605   SDValue NewStart = N->getOperand(1 - ReduceIdx);
7606   unsigned SplatOpc = RISCVISD::VFMV_S_F_VL;
7607   if (SplatVT.isInteger()) {
7608     auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode());
7609     if (!C || C->isZero() || !isInt<5>(C->getSExtValue()))
7610       SplatOpc = RISCVISD::VMV_S_X_VL;
7611     else
7612       SplatOpc = RISCVISD::VMV_V_X_VL;
7613   }
7614 
7615   SDValue NewScalarV =
7616       DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart,
7617                   ScalarV.getOperand(2));
7618   SDValue NewReduce =
7619       DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(),
7620                   Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV,
7621                   Reduce.getOperand(3), Reduce.getOperand(4));
7622   return DAG.getNode(Extract.getOpcode(), SDLoc(Extract),
7623                      Extract.getValueType(), NewReduce, Extract.getOperand(1));
7624 }
7625 
7626 // Match the following pattern as a GREVI(W) operation
7627 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7628 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7629                                const RISCVSubtarget &Subtarget) {
7630   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7631   EVT VT = Op.getValueType();
7632 
7633   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7634     auto LHS = matchGREVIPat(Op.getOperand(0));
7635     auto RHS = matchGREVIPat(Op.getOperand(1));
7636     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7637       SDLoc DL(Op);
7638       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7639                          DAG.getConstant(LHS->ShAmt, DL, VT));
7640     }
7641   }
7642   return SDValue();
7643 }
7644 
7645 // Matches any the following pattern as a GORCI(W) operation
7646 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7647 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7648 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7649 // Note that with the variant of 3.,
7650 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7651 // the inner pattern will first be matched as GREVI and then the outer
7652 // pattern will be matched to GORC via the first rule above.
7653 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7654 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7655                                const RISCVSubtarget &Subtarget) {
7656   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7657   EVT VT = Op.getValueType();
7658 
7659   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7660     SDLoc DL(Op);
7661     SDValue Op0 = Op.getOperand(0);
7662     SDValue Op1 = Op.getOperand(1);
7663 
7664     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7665       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7666           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7667           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7668         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7669       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7670       if ((Reverse.getOpcode() == ISD::ROTL ||
7671            Reverse.getOpcode() == ISD::ROTR) &&
7672           Reverse.getOperand(0) == X &&
7673           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7674         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7675         if (RotAmt == (VT.getSizeInBits() / 2))
7676           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7677                              DAG.getConstant(RotAmt, DL, VT));
7678       }
7679       return SDValue();
7680     };
7681 
7682     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7683     if (SDValue V = MatchOROfReverse(Op0, Op1))
7684       return V;
7685     if (SDValue V = MatchOROfReverse(Op1, Op0))
7686       return V;
7687 
7688     // OR is commutable so canonicalize its OR operand to the left
7689     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7690       std::swap(Op0, Op1);
7691     if (Op0.getOpcode() != ISD::OR)
7692       return SDValue();
7693     SDValue OrOp0 = Op0.getOperand(0);
7694     SDValue OrOp1 = Op0.getOperand(1);
7695     auto LHS = matchGREVIPat(OrOp0);
7696     // OR is commutable so swap the operands and try again: x might have been
7697     // on the left
7698     if (!LHS) {
7699       std::swap(OrOp0, OrOp1);
7700       LHS = matchGREVIPat(OrOp0);
7701     }
7702     auto RHS = matchGREVIPat(Op1);
7703     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7704       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7705                          DAG.getConstant(LHS->ShAmt, DL, VT));
7706     }
7707   }
7708   return SDValue();
7709 }
7710 
7711 // Matches any of the following bit-manipulation patterns:
7712 //   (and (shl x, 1), (0x22222222 << 1))
7713 //   (and (srl x, 1), 0x22222222)
7714 //   (shl (and x, 0x22222222), 1)
7715 //   (srl (and x, (0x22222222 << 1)), 1)
7716 // where the shift amount and mask may vary thus:
7717 //   [1]  = 0x22222222 / 0x44444444
7718 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7719 //   [4]  = 0x00F000F0 / 0x0F000F00
7720 //   [8]  = 0x0000FF00 / 0x00FF0000
7721 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7722 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7723   // These are the unshifted masks which we use to match bit-manipulation
7724   // patterns. They may be shifted left in certain circumstances.
7725   static const uint64_t BitmanipMasks[] = {
7726       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7727       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7728 
7729   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7730 }
7731 
7732 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7733 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7734                                const RISCVSubtarget &Subtarget) {
7735   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7736   EVT VT = Op.getValueType();
7737 
7738   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7739     return SDValue();
7740 
7741   SDValue Op0 = Op.getOperand(0);
7742   SDValue Op1 = Op.getOperand(1);
7743 
7744   // Or is commutable so canonicalize the second OR to the LHS.
7745   if (Op0.getOpcode() != ISD::OR)
7746     std::swap(Op0, Op1);
7747   if (Op0.getOpcode() != ISD::OR)
7748     return SDValue();
7749 
7750   // We found an inner OR, so our operands are the operands of the inner OR
7751   // and the other operand of the outer OR.
7752   SDValue A = Op0.getOperand(0);
7753   SDValue B = Op0.getOperand(1);
7754   SDValue C = Op1;
7755 
7756   auto Match1 = matchSHFLPat(A);
7757   auto Match2 = matchSHFLPat(B);
7758 
7759   // If neither matched, we failed.
7760   if (!Match1 && !Match2)
7761     return SDValue();
7762 
7763   // We had at least one match. if one failed, try the remaining C operand.
7764   if (!Match1) {
7765     std::swap(A, C);
7766     Match1 = matchSHFLPat(A);
7767     if (!Match1)
7768       return SDValue();
7769   } else if (!Match2) {
7770     std::swap(B, C);
7771     Match2 = matchSHFLPat(B);
7772     if (!Match2)
7773       return SDValue();
7774   }
7775   assert(Match1 && Match2);
7776 
7777   // Make sure our matches pair up.
7778   if (!Match1->formsPairWith(*Match2))
7779     return SDValue();
7780 
7781   // All the remains is to make sure C is an AND with the same input, that masks
7782   // out the bits that are being shuffled.
7783   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7784       C.getOperand(0) != Match1->Op)
7785     return SDValue();
7786 
7787   uint64_t Mask = C.getConstantOperandVal(1);
7788 
7789   static const uint64_t BitmanipMasks[] = {
7790       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7791       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7792   };
7793 
7794   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7795   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7796   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7797 
7798   if (Mask != ExpMask)
7799     return SDValue();
7800 
7801   SDLoc DL(Op);
7802   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7803                      DAG.getConstant(Match1->ShAmt, DL, VT));
7804 }
7805 
7806 // Optimize (add (shl x, c0), (shl y, c1)) ->
7807 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7808 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7809                                   const RISCVSubtarget &Subtarget) {
7810   // Perform this optimization only in the zba extension.
7811   if (!Subtarget.hasStdExtZba())
7812     return SDValue();
7813 
7814   // Skip for vector types and larger types.
7815   EVT VT = N->getValueType(0);
7816   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7817     return SDValue();
7818 
7819   // The two operand nodes must be SHL and have no other use.
7820   SDValue N0 = N->getOperand(0);
7821   SDValue N1 = N->getOperand(1);
7822   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7823       !N0->hasOneUse() || !N1->hasOneUse())
7824     return SDValue();
7825 
7826   // Check c0 and c1.
7827   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7828   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7829   if (!N0C || !N1C)
7830     return SDValue();
7831   int64_t C0 = N0C->getSExtValue();
7832   int64_t C1 = N1C->getSExtValue();
7833   if (C0 <= 0 || C1 <= 0)
7834     return SDValue();
7835 
7836   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7837   int64_t Bits = std::min(C0, C1);
7838   int64_t Diff = std::abs(C0 - C1);
7839   if (Diff != 1 && Diff != 2 && Diff != 3)
7840     return SDValue();
7841 
7842   // Build nodes.
7843   SDLoc DL(N);
7844   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7845   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7846   SDValue NA0 =
7847       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7848   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7849   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7850 }
7851 
7852 // Combine
7853 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7854 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7855 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7856 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7857 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7858 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7859 // The grev patterns represents BSWAP.
7860 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7861 // off the grev.
7862 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7863                                           const RISCVSubtarget &Subtarget) {
7864   bool IsWInstruction =
7865       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7866   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7867           IsWInstruction) &&
7868          "Unexpected opcode!");
7869   SDValue Src = N->getOperand(0);
7870   EVT VT = N->getValueType(0);
7871   SDLoc DL(N);
7872 
7873   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7874     return SDValue();
7875 
7876   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7877       !isa<ConstantSDNode>(Src.getOperand(1)))
7878     return SDValue();
7879 
7880   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7881   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7882 
7883   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7884   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7885   unsigned ShAmt1 = N->getConstantOperandVal(1);
7886   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7887   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7888     return SDValue();
7889 
7890   Src = Src.getOperand(0);
7891 
7892   // Toggle bit the MSB of the shift.
7893   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7894   if (CombinedShAmt == 0)
7895     return Src;
7896 
7897   SDValue Res = DAG.getNode(
7898       RISCVISD::GREV, DL, VT, Src,
7899       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7900   if (!IsWInstruction)
7901     return Res;
7902 
7903   // Sign extend the result to match the behavior of the rotate. This will be
7904   // selected to GREVIW in isel.
7905   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7906                      DAG.getValueType(MVT::i32));
7907 }
7908 
7909 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7910 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7911 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7912 // not undo itself, but they are redundant.
7913 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7914   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7915   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7916   SDValue Src = N->getOperand(0);
7917 
7918   if (Src.getOpcode() != N->getOpcode())
7919     return SDValue();
7920 
7921   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7922       !isa<ConstantSDNode>(Src.getOperand(1)))
7923     return SDValue();
7924 
7925   unsigned ShAmt1 = N->getConstantOperandVal(1);
7926   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7927   Src = Src.getOperand(0);
7928 
7929   unsigned CombinedShAmt;
7930   if (IsGORC)
7931     CombinedShAmt = ShAmt1 | ShAmt2;
7932   else
7933     CombinedShAmt = ShAmt1 ^ ShAmt2;
7934 
7935   if (CombinedShAmt == 0)
7936     return Src;
7937 
7938   SDLoc DL(N);
7939   return DAG.getNode(
7940       N->getOpcode(), DL, N->getValueType(0), Src,
7941       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7942 }
7943 
7944 // Combine a constant select operand into its use:
7945 //
7946 // (and (select cond, -1, c), x)
7947 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7948 // (or  (select cond, 0, c), x)
7949 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7950 // (xor (select cond, 0, c), x)
7951 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7952 // (add (select cond, 0, c), x)
7953 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7954 // (sub x, (select cond, 0, c))
7955 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7956 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7957                                    SelectionDAG &DAG, bool AllOnes) {
7958   EVT VT = N->getValueType(0);
7959 
7960   // Skip vectors.
7961   if (VT.isVector())
7962     return SDValue();
7963 
7964   if ((Slct.getOpcode() != ISD::SELECT &&
7965        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7966       !Slct.hasOneUse())
7967     return SDValue();
7968 
7969   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7970     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7971   };
7972 
7973   bool SwapSelectOps;
7974   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7975   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7976   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7977   SDValue NonConstantVal;
7978   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7979     SwapSelectOps = false;
7980     NonConstantVal = FalseVal;
7981   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7982     SwapSelectOps = true;
7983     NonConstantVal = TrueVal;
7984   } else
7985     return SDValue();
7986 
7987   // Slct is now know to be the desired identity constant when CC is true.
7988   TrueVal = OtherOp;
7989   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7990   // Unless SwapSelectOps says the condition should be false.
7991   if (SwapSelectOps)
7992     std::swap(TrueVal, FalseVal);
7993 
7994   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7995     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7996                        {Slct.getOperand(0), Slct.getOperand(1),
7997                         Slct.getOperand(2), TrueVal, FalseVal});
7998 
7999   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8000                      {Slct.getOperand(0), TrueVal, FalseVal});
8001 }
8002 
8003 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8004 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
8005                                               bool AllOnes) {
8006   SDValue N0 = N->getOperand(0);
8007   SDValue N1 = N->getOperand(1);
8008   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
8009     return Result;
8010   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
8011     return Result;
8012   return SDValue();
8013 }
8014 
8015 // Transform (add (mul x, c0), c1) ->
8016 //           (add (mul (add x, c1/c0), c0), c1%c0).
8017 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
8018 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
8019 // to an infinite loop in DAGCombine if transformed.
8020 // Or transform (add (mul x, c0), c1) ->
8021 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
8022 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
8023 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
8024 // lead to an infinite loop in DAGCombine if transformed.
8025 // Or transform (add (mul x, c0), c1) ->
8026 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
8027 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
8028 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
8029 // lead to an infinite loop in DAGCombine if transformed.
8030 // Or transform (add (mul x, c0), c1) ->
8031 //              (mul (add x, c1/c0), c0).
8032 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
8033 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
8034                                      const RISCVSubtarget &Subtarget) {
8035   // Skip for vector types and larger types.
8036   EVT VT = N->getValueType(0);
8037   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
8038     return SDValue();
8039   // The first operand node must be a MUL and has no other use.
8040   SDValue N0 = N->getOperand(0);
8041   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
8042     return SDValue();
8043   // Check if c0 and c1 match above conditions.
8044   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8045   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8046   if (!N0C || !N1C)
8047     return SDValue();
8048   // If N0C has multiple uses it's possible one of the cases in
8049   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
8050   // in an infinite loop.
8051   if (!N0C->hasOneUse())
8052     return SDValue();
8053   int64_t C0 = N0C->getSExtValue();
8054   int64_t C1 = N1C->getSExtValue();
8055   int64_t CA, CB;
8056   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
8057     return SDValue();
8058   // Search for proper CA (non-zero) and CB that both are simm12.
8059   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
8060       !isInt<12>(C0 * (C1 / C0))) {
8061     CA = C1 / C0;
8062     CB = C1 % C0;
8063   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
8064              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
8065     CA = C1 / C0 + 1;
8066     CB = C1 % C0 - C0;
8067   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
8068              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
8069     CA = C1 / C0 - 1;
8070     CB = C1 % C0 + C0;
8071   } else
8072     return SDValue();
8073   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
8074   SDLoc DL(N);
8075   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
8076                              DAG.getConstant(CA, DL, VT));
8077   SDValue New1 =
8078       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
8079   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
8080 }
8081 
8082 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
8083                                  const RISCVSubtarget &Subtarget) {
8084   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
8085     return V;
8086   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
8087     return V;
8088   if (SDValue V = combineBinOpToReduce(N, DAG))
8089     return V;
8090   // fold (add (select lhs, rhs, cc, 0, y), x) ->
8091   //      (select lhs, rhs, cc, x, (add x, y))
8092   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8093 }
8094 
8095 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
8096   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
8097   //      (select lhs, rhs, cc, x, (sub x, y))
8098   SDValue N0 = N->getOperand(0);
8099   SDValue N1 = N->getOperand(1);
8100   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
8101 }
8102 
8103 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
8104                                  const RISCVSubtarget &Subtarget) {
8105   SDValue N0 = N->getOperand(0);
8106   // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero
8107   // extending X. This is safe since we only need the LSB after the shift and
8108   // shift amounts larger than 31 would produce poison. If we wait until
8109   // type legalization, we'll create RISCVISD::SRLW and we can't recover it
8110   // to use a BEXT instruction.
8111   if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() &&
8112       N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) &&
8113       N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) &&
8114       N0.hasOneUse()) {
8115     SDLoc DL(N);
8116     SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0));
8117     SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1));
8118     SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1);
8119     SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl,
8120                               DAG.getConstant(1, DL, MVT::i64));
8121     return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And);
8122   }
8123 
8124   if (SDValue V = combineBinOpToReduce(N, DAG))
8125     return V;
8126 
8127   // fold (and (select lhs, rhs, cc, -1, y), x) ->
8128   //      (select lhs, rhs, cc, x, (and x, y))
8129   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
8130 }
8131 
8132 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
8133                                 const RISCVSubtarget &Subtarget) {
8134   if (Subtarget.hasStdExtZbp()) {
8135     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
8136       return GREV;
8137     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
8138       return GORC;
8139     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
8140       return SHFL;
8141   }
8142 
8143   if (SDValue V = combineBinOpToReduce(N, DAG))
8144     return V;
8145   // fold (or (select cond, 0, y), x) ->
8146   //      (select cond, x, (or x, y))
8147   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8148 }
8149 
8150 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
8151   SDValue N0 = N->getOperand(0);
8152   SDValue N1 = N->getOperand(1);
8153 
8154   // fold (xor (sllw 1, x), -1) -> (rolw ~1, x)
8155   // NOTE: Assumes ROL being legal means ROLW is legal.
8156   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8157   if (N0.getOpcode() == RISCVISD::SLLW &&
8158       isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) &&
8159       TLI.isOperationLegal(ISD::ROTL, MVT::i64)) {
8160     SDLoc DL(N);
8161     return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64,
8162                        DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1));
8163   }
8164 
8165   if (SDValue V = combineBinOpToReduce(N, DAG))
8166     return V;
8167   // fold (xor (select cond, 0, y), x) ->
8168   //      (select cond, x, (xor x, y))
8169   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
8170 }
8171 
8172 // Replace (seteq (i64 (and X, 0xffffffff)), C1) with
8173 // (seteq (i64 (sext_inreg (X, i32)), C1')) where C1' is C1 sign extended from
8174 // bit 31. Same for setne. C1' may be cheaper to materialize and the sext_inreg
8175 // can become a sext.w instead of a shift pair.
8176 static SDValue performSETCCCombine(SDNode *N, SelectionDAG &DAG,
8177                                    const RISCVSubtarget &Subtarget) {
8178   SDValue N0 = N->getOperand(0);
8179   SDValue N1 = N->getOperand(1);
8180   EVT VT = N->getValueType(0);
8181   EVT OpVT = N0.getValueType();
8182 
8183   if (OpVT != MVT::i64 || !Subtarget.is64Bit())
8184     return SDValue();
8185 
8186   // RHS needs to be a constant.
8187   auto *N1C = dyn_cast<ConstantSDNode>(N1);
8188   if (!N1C)
8189     return SDValue();
8190 
8191   // LHS needs to be (and X, 0xffffffff).
8192   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse() ||
8193       !isa<ConstantSDNode>(N0.getOperand(1)) ||
8194       N0.getConstantOperandVal(1) != UINT64_C(0xffffffff))
8195     return SDValue();
8196 
8197   // Looking for an equality compare.
8198   ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get();
8199   if (!isIntEqualitySetCC(Cond))
8200     return SDValue();
8201 
8202   // Don't do this if the sign bit is provably zero, it will be turned back into
8203   // an AND.
8204   APInt SignMask = APInt::getOneBitSet(64, 31);
8205   if (DAG.MaskedValueIsZero(N0.getOperand(0), SignMask))
8206     return SDValue();
8207 
8208   const APInt &C1 = N1C->getAPIntValue();
8209 
8210   SDLoc dl(N);
8211   // If the constant is larger than 2^32 - 1 it is impossible for both sides
8212   // to be equal.
8213   if (C1.getActiveBits() > 32)
8214     return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
8215 
8216   SDValue SExtOp = DAG.getNode(ISD::SIGN_EXTEND_INREG, N, OpVT,
8217                                N0.getOperand(0), DAG.getValueType(MVT::i32));
8218   return DAG.getSetCC(dl, VT, SExtOp, DAG.getConstant(C1.trunc(32).sext(64),
8219                                                       dl, OpVT), Cond);
8220 }
8221 
8222 static SDValue
8223 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
8224                                 const RISCVSubtarget &Subtarget) {
8225   SDValue Src = N->getOperand(0);
8226   EVT VT = N->getValueType(0);
8227 
8228   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
8229   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8230       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
8231     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
8232                        Src.getOperand(0));
8233 
8234   // Fold (i64 (sext_inreg (abs X), i32)) ->
8235   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
8236   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
8237   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
8238   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
8239   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
8240   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
8241   // may get combined into an earlier operation so we need to use
8242   // ComputeNumSignBits.
8243   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
8244   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
8245   // we can't assume that X has 33 sign bits. We must check.
8246   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
8247       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
8248       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
8249       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
8250     SDLoc DL(N);
8251     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
8252     SDValue Neg =
8253         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
8254     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
8255                       DAG.getValueType(MVT::i32));
8256     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
8257   }
8258 
8259   return SDValue();
8260 }
8261 
8262 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
8263 // vwadd(u).vv/vx or vwsub(u).vv/vx.
8264 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
8265                                              bool Commute = false) {
8266   assert((N->getOpcode() == RISCVISD::ADD_VL ||
8267           N->getOpcode() == RISCVISD::SUB_VL) &&
8268          "Unexpected opcode");
8269   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
8270   SDValue Op0 = N->getOperand(0);
8271   SDValue Op1 = N->getOperand(1);
8272   if (Commute)
8273     std::swap(Op0, Op1);
8274 
8275   MVT VT = N->getSimpleValueType(0);
8276 
8277   // Determine the narrow size for a widening add/sub.
8278   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8279   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8280                                   VT.getVectorElementCount());
8281 
8282   SDValue Mask = N->getOperand(2);
8283   SDValue VL = N->getOperand(3);
8284 
8285   SDLoc DL(N);
8286 
8287   // If the RHS is a sext or zext, we can form a widening op.
8288   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
8289        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
8290       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
8291     unsigned ExtOpc = Op1.getOpcode();
8292     Op1 = Op1.getOperand(0);
8293     // Re-introduce narrower extends if needed.
8294     if (Op1.getValueType() != NarrowVT)
8295       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8296 
8297     unsigned WOpc;
8298     if (ExtOpc == RISCVISD::VSEXT_VL)
8299       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
8300     else
8301       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
8302 
8303     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
8304   }
8305 
8306   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
8307   // sext/zext?
8308 
8309   return SDValue();
8310 }
8311 
8312 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
8313 // vwsub(u).vv/vx.
8314 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
8315   SDValue Op0 = N->getOperand(0);
8316   SDValue Op1 = N->getOperand(1);
8317   SDValue Mask = N->getOperand(2);
8318   SDValue VL = N->getOperand(3);
8319 
8320   MVT VT = N->getSimpleValueType(0);
8321   MVT NarrowVT = Op1.getSimpleValueType();
8322   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
8323 
8324   unsigned VOpc;
8325   switch (N->getOpcode()) {
8326   default: llvm_unreachable("Unexpected opcode");
8327   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
8328   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
8329   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
8330   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
8331   }
8332 
8333   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8334                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
8335 
8336   SDLoc DL(N);
8337 
8338   // If the LHS is a sext or zext, we can narrow this op to the same size as
8339   // the RHS.
8340   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
8341        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
8342       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
8343     unsigned ExtOpc = Op0.getOpcode();
8344     Op0 = Op0.getOperand(0);
8345     // Re-introduce narrower extends if needed.
8346     if (Op0.getValueType() != NarrowVT)
8347       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8348     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
8349   }
8350 
8351   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8352                N->getOpcode() == RISCVISD::VWADDU_W_VL;
8353 
8354   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
8355   // to commute and use a vwadd(u).vx instead.
8356   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
8357       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
8358     Op0 = Op0.getOperand(1);
8359 
8360     // See if have enough sign bits or zero bits in the scalar to use a
8361     // widening add/sub by splatting to smaller element size.
8362     unsigned EltBits = VT.getScalarSizeInBits();
8363     unsigned ScalarBits = Op0.getValueSizeInBits();
8364     // Make sure we're getting all element bits from the scalar register.
8365     // FIXME: Support implicit sign extension of vmv.v.x?
8366     if (ScalarBits < EltBits)
8367       return SDValue();
8368 
8369     if (IsSigned) {
8370       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
8371         return SDValue();
8372     } else {
8373       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8374       if (!DAG.MaskedValueIsZero(Op0, Mask))
8375         return SDValue();
8376     }
8377 
8378     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8379                       DAG.getUNDEF(NarrowVT), Op0, VL);
8380     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
8381   }
8382 
8383   return SDValue();
8384 }
8385 
8386 // Try to form VWMUL, VWMULU or VWMULSU.
8387 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
8388 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
8389                                        bool Commute) {
8390   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
8391   SDValue Op0 = N->getOperand(0);
8392   SDValue Op1 = N->getOperand(1);
8393   if (Commute)
8394     std::swap(Op0, Op1);
8395 
8396   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
8397   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
8398   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
8399   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
8400     return SDValue();
8401 
8402   SDValue Mask = N->getOperand(2);
8403   SDValue VL = N->getOperand(3);
8404 
8405   // Make sure the mask and VL match.
8406   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8407     return SDValue();
8408 
8409   MVT VT = N->getSimpleValueType(0);
8410 
8411   // Determine the narrow size for a widening multiply.
8412   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8413   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8414                                   VT.getVectorElementCount());
8415 
8416   SDLoc DL(N);
8417 
8418   // See if the other operand is the same opcode.
8419   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8420     if (!Op1.hasOneUse())
8421       return SDValue();
8422 
8423     // Make sure the mask and VL match.
8424     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8425       return SDValue();
8426 
8427     Op1 = Op1.getOperand(0);
8428   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8429     // The operand is a splat of a scalar.
8430 
8431     // The pasthru must be undef for tail agnostic
8432     if (!Op1.getOperand(0).isUndef())
8433       return SDValue();
8434     // The VL must be the same.
8435     if (Op1.getOperand(2) != VL)
8436       return SDValue();
8437 
8438     // Get the scalar value.
8439     Op1 = Op1.getOperand(1);
8440 
8441     // See if have enough sign bits or zero bits in the scalar to use a
8442     // widening multiply by splatting to smaller element size.
8443     unsigned EltBits = VT.getScalarSizeInBits();
8444     unsigned ScalarBits = Op1.getValueSizeInBits();
8445     // Make sure we're getting all element bits from the scalar register.
8446     // FIXME: Support implicit sign extension of vmv.v.x?
8447     if (ScalarBits < EltBits)
8448       return SDValue();
8449 
8450     // If the LHS is a sign extend, try to use vwmul.
8451     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8452       // Can use vwmul.
8453     } else {
8454       // Otherwise try to use vwmulu or vwmulsu.
8455       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8456       if (DAG.MaskedValueIsZero(Op1, Mask))
8457         IsVWMULSU = IsSignExt;
8458       else
8459         return SDValue();
8460     }
8461 
8462     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8463                       DAG.getUNDEF(NarrowVT), Op1, VL);
8464   } else
8465     return SDValue();
8466 
8467   Op0 = Op0.getOperand(0);
8468 
8469   // Re-introduce narrower extends if needed.
8470   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8471   if (Op0.getValueType() != NarrowVT)
8472     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8473   // vwmulsu requires second operand to be zero extended.
8474   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8475   if (Op1.getValueType() != NarrowVT)
8476     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8477 
8478   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8479   if (!IsVWMULSU)
8480     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8481   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8482 }
8483 
8484 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8485   switch (Op.getOpcode()) {
8486   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8487   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8488   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8489   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8490   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8491   }
8492 
8493   return RISCVFPRndMode::Invalid;
8494 }
8495 
8496 // Fold
8497 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8498 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8499 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8500 //   (fp_to_int (fceil X))      -> fcvt X, rup
8501 //   (fp_to_int (fround X))     -> fcvt X, rmm
8502 static SDValue performFP_TO_INTCombine(SDNode *N,
8503                                        TargetLowering::DAGCombinerInfo &DCI,
8504                                        const RISCVSubtarget &Subtarget) {
8505   SelectionDAG &DAG = DCI.DAG;
8506   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8507   MVT XLenVT = Subtarget.getXLenVT();
8508 
8509   // Only handle XLen or i32 types. Other types narrower than XLen will
8510   // eventually be legalized to XLenVT.
8511   EVT VT = N->getValueType(0);
8512   if (VT != MVT::i32 && VT != XLenVT)
8513     return SDValue();
8514 
8515   SDValue Src = N->getOperand(0);
8516 
8517   // Ensure the FP type is also legal.
8518   if (!TLI.isTypeLegal(Src.getValueType()))
8519     return SDValue();
8520 
8521   // Don't do this for f16 with Zfhmin and not Zfh.
8522   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8523     return SDValue();
8524 
8525   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8526   if (FRM == RISCVFPRndMode::Invalid)
8527     return SDValue();
8528 
8529   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8530 
8531   unsigned Opc;
8532   if (VT == XLenVT)
8533     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8534   else
8535     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8536 
8537   SDLoc DL(N);
8538   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8539                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8540   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8541 }
8542 
8543 // Fold
8544 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8545 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8546 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8547 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8548 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8549 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8550                                        TargetLowering::DAGCombinerInfo &DCI,
8551                                        const RISCVSubtarget &Subtarget) {
8552   SelectionDAG &DAG = DCI.DAG;
8553   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8554   MVT XLenVT = Subtarget.getXLenVT();
8555 
8556   // Only handle XLen types. Other types narrower than XLen will eventually be
8557   // legalized to XLenVT.
8558   EVT DstVT = N->getValueType(0);
8559   if (DstVT != XLenVT)
8560     return SDValue();
8561 
8562   SDValue Src = N->getOperand(0);
8563 
8564   // Ensure the FP type is also legal.
8565   if (!TLI.isTypeLegal(Src.getValueType()))
8566     return SDValue();
8567 
8568   // Don't do this for f16 with Zfhmin and not Zfh.
8569   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8570     return SDValue();
8571 
8572   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8573 
8574   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8575   if (FRM == RISCVFPRndMode::Invalid)
8576     return SDValue();
8577 
8578   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8579 
8580   unsigned Opc;
8581   if (SatVT == DstVT)
8582     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8583   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8584     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8585   else
8586     return SDValue();
8587   // FIXME: Support other SatVTs by clamping before or after the conversion.
8588 
8589   Src = Src.getOperand(0);
8590 
8591   SDLoc DL(N);
8592   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8593                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8594 
8595   // RISCV FP-to-int conversions saturate to the destination register size, but
8596   // don't produce 0 for nan.
8597   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8598   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8599 }
8600 
8601 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8602 // smaller than XLenVT.
8603 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8604                                         const RISCVSubtarget &Subtarget) {
8605   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8606 
8607   SDValue Src = N->getOperand(0);
8608   if (Src.getOpcode() != ISD::BSWAP)
8609     return SDValue();
8610 
8611   EVT VT = N->getValueType(0);
8612   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8613       !isPowerOf2_32(VT.getSizeInBits()))
8614     return SDValue();
8615 
8616   SDLoc DL(N);
8617   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8618                      DAG.getConstant(7, DL, VT));
8619 }
8620 
8621 // Convert from one FMA opcode to another based on whether we are negating the
8622 // multiply result and/or the accumulator.
8623 // NOTE: Only supports RVV operations with VL.
8624 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) {
8625   assert((NegMul || NegAcc) && "Not negating anything?");
8626 
8627   // Negating the multiply result changes ADD<->SUB and toggles 'N'.
8628   if (NegMul) {
8629     // clang-format off
8630     switch (Opcode) {
8631     default: llvm_unreachable("Unexpected opcode");
8632     case RISCVISD::VFMADD_VL:  Opcode = RISCVISD::VFNMSUB_VL; break;
8633     case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFMADD_VL;  break;
8634     case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFMSUB_VL;  break;
8635     case RISCVISD::VFMSUB_VL:  Opcode = RISCVISD::VFNMADD_VL; break;
8636     }
8637     // clang-format on
8638   }
8639 
8640   // Negating the accumulator changes ADD<->SUB.
8641   if (NegAcc) {
8642     // clang-format off
8643     switch (Opcode) {
8644     default: llvm_unreachable("Unexpected opcode");
8645     case RISCVISD::VFMADD_VL:  Opcode = RISCVISD::VFMSUB_VL;  break;
8646     case RISCVISD::VFMSUB_VL:  Opcode = RISCVISD::VFMADD_VL;  break;
8647     case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break;
8648     case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break;
8649     }
8650     // clang-format on
8651   }
8652 
8653   return Opcode;
8654 }
8655 
8656 static SDValue performSRACombine(SDNode *N, SelectionDAG &DAG,
8657                                  const RISCVSubtarget &Subtarget) {
8658   assert(N->getOpcode() == ISD::SRA && "Unexpected opcode");
8659 
8660   if (N->getValueType(0) != MVT::i64 || !Subtarget.is64Bit())
8661     return SDValue();
8662 
8663   if (!isa<ConstantSDNode>(N->getOperand(1)))
8664     return SDValue();
8665   uint64_t ShAmt = N->getConstantOperandVal(1);
8666   if (ShAmt > 32)
8667     return SDValue();
8668 
8669   SDValue N0 = N->getOperand(0);
8670 
8671   // Combine (sra (sext_inreg (shl X, C1), i32), C2) ->
8672   // (sra (shl X, C1+32), C2+32) so it gets selected as SLLI+SRAI instead of
8673   // SLLIW+SRAIW. SLLI+SRAI have compressed forms.
8674   if (ShAmt < 32 &&
8675       N0.getOpcode() == ISD::SIGN_EXTEND_INREG && N0.hasOneUse() &&
8676       cast<VTSDNode>(N0.getOperand(1))->getVT() == MVT::i32 &&
8677       N0.getOperand(0).getOpcode() == ISD::SHL && N0.getOperand(0).hasOneUse() &&
8678       isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
8679     uint64_t LShAmt = N0.getOperand(0).getConstantOperandVal(1);
8680     if (LShAmt < 32) {
8681       SDLoc ShlDL(N0.getOperand(0));
8682       SDValue Shl = DAG.getNode(ISD::SHL, ShlDL, MVT::i64,
8683                                 N0.getOperand(0).getOperand(0),
8684                                 DAG.getConstant(LShAmt + 32, ShlDL, MVT::i64));
8685       SDLoc DL(N);
8686       return DAG.getNode(ISD::SRA, DL, MVT::i64, Shl,
8687                          DAG.getConstant(ShAmt + 32, DL, MVT::i64));
8688     }
8689   }
8690 
8691   // Combine (sra (shl X, 32), 32 - C) -> (shl (sext_inreg X, i32), C)
8692   // FIXME: Should this be a generic combine? There's a similar combine on X86.
8693   //
8694   // Also try these folds where an add or sub is in the middle.
8695   // (sra (add (shl X, 32), C1), 32 - C) -> (shl (sext_inreg (add X, C1), C)
8696   // (sra (sub C1, (shl X, 32)), 32 - C) -> (shl (sext_inreg (sub C1, X), C)
8697   SDValue Shl;
8698   ConstantSDNode *AddC = nullptr;
8699 
8700   // We might have an ADD or SUB between the SRA and SHL.
8701   bool IsAdd = N0.getOpcode() == ISD::ADD;
8702   if ((IsAdd || N0.getOpcode() == ISD::SUB)) {
8703     if (!N0.hasOneUse())
8704       return SDValue();
8705     // Other operand needs to be a constant we can modify.
8706     AddC = dyn_cast<ConstantSDNode>(N0.getOperand(IsAdd ? 1 : 0));
8707     if (!AddC)
8708       return SDValue();
8709 
8710     // AddC needs to have at least 32 trailing zeros.
8711     if (AddC->getAPIntValue().countTrailingZeros() < 32)
8712       return SDValue();
8713 
8714     Shl = N0.getOperand(IsAdd ? 0 : 1);
8715   } else {
8716     // Not an ADD or SUB.
8717     Shl = N0;
8718   }
8719 
8720   // Look for a shift left by 32.
8721   if (Shl.getOpcode() != ISD::SHL || !Shl.hasOneUse() ||
8722       !isa<ConstantSDNode>(Shl.getOperand(1)) ||
8723       Shl.getConstantOperandVal(1) != 32)
8724     return SDValue();
8725 
8726   SDLoc DL(N);
8727   SDValue In = Shl.getOperand(0);
8728 
8729   // If we looked through an ADD or SUB, we need to rebuild it with the shifted
8730   // constant.
8731   if (AddC) {
8732     SDValue ShiftedAddC =
8733         DAG.getConstant(AddC->getAPIntValue().lshr(32), DL, MVT::i64);
8734     if (IsAdd)
8735       In = DAG.getNode(ISD::ADD, DL, MVT::i64, In, ShiftedAddC);
8736     else
8737       In = DAG.getNode(ISD::SUB, DL, MVT::i64, ShiftedAddC, In);
8738   }
8739 
8740   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, In,
8741                              DAG.getValueType(MVT::i32));
8742   if (ShAmt == 32)
8743     return SExt;
8744 
8745   return DAG.getNode(
8746       ISD::SHL, DL, MVT::i64, SExt,
8747       DAG.getConstant(32 - ShAmt, DL, MVT::i64));
8748 }
8749 
8750 // Perform common combines for BR_CC and SELECT_CC condtions.
8751 static bool combine_CC(SDValue &LHS, SDValue &RHS, SDValue &CC, const SDLoc &DL,
8752                        SelectionDAG &DAG, const RISCVSubtarget &Subtarget) {
8753   ISD::CondCode CCVal = cast<CondCodeSDNode>(CC)->get();
8754   if (!ISD::isIntEqualitySetCC(CCVal))
8755     return false;
8756 
8757   // Fold ((setlt X, Y), 0, ne) -> (X, Y, lt)
8758   // Sometimes the setcc is introduced after br_cc/select_cc has been formed.
8759   if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8760       LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8761     // If we're looking for eq 0 instead of ne 0, we need to invert the
8762     // condition.
8763     bool Invert = CCVal == ISD::SETEQ;
8764     CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8765     if (Invert)
8766       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8767 
8768     RHS = LHS.getOperand(1);
8769     LHS = LHS.getOperand(0);
8770     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8771 
8772     CC = DAG.getCondCode(CCVal);
8773     return true;
8774   }
8775 
8776   // Fold ((xor X, Y), 0, eq/ne) -> (X, Y, eq/ne)
8777   if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) {
8778     RHS = LHS.getOperand(1);
8779     LHS = LHS.getOperand(0);
8780     return true;
8781   }
8782 
8783   // Fold ((srl (and X, 1<<C), C), 0, eq/ne) -> ((shl X, XLen-1-C), 0, ge/lt)
8784   if (isNullConstant(RHS) && LHS.getOpcode() == ISD::SRL && LHS.hasOneUse() &&
8785       LHS.getOperand(1).getOpcode() == ISD::Constant) {
8786     SDValue LHS0 = LHS.getOperand(0);
8787     if (LHS0.getOpcode() == ISD::AND &&
8788         LHS0.getOperand(1).getOpcode() == ISD::Constant) {
8789       uint64_t Mask = LHS0.getConstantOperandVal(1);
8790       uint64_t ShAmt = LHS.getConstantOperandVal(1);
8791       if (isPowerOf2_64(Mask) && Log2_64(Mask) == ShAmt) {
8792         CCVal = CCVal == ISD::SETEQ ? ISD::SETGE : ISD::SETLT;
8793         CC = DAG.getCondCode(CCVal);
8794 
8795         ShAmt = LHS.getValueSizeInBits() - 1 - ShAmt;
8796         LHS = LHS0.getOperand(0);
8797         if (ShAmt != 0)
8798           LHS =
8799               DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS0.getOperand(0),
8800                           DAG.getConstant(ShAmt, DL, LHS.getValueType()));
8801         return true;
8802       }
8803     }
8804   }
8805 
8806   // (X, 1, setne) -> // (X, 0, seteq) if we can prove X is 0/1.
8807   // This can occur when legalizing some floating point comparisons.
8808   APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8809   if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8810     CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8811     CC = DAG.getCondCode(CCVal);
8812     RHS = DAG.getConstant(0, DL, LHS.getValueType());
8813     return true;
8814   }
8815 
8816   return false;
8817 }
8818 
8819 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8820                                                DAGCombinerInfo &DCI) const {
8821   SelectionDAG &DAG = DCI.DAG;
8822 
8823   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8824   // bits are demanded. N will be added to the Worklist if it was not deleted.
8825   // Caller should return SDValue(N, 0) if this returns true.
8826   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8827     SDValue Op = N->getOperand(OpNo);
8828     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8829     if (!SimplifyDemandedBits(Op, Mask, DCI))
8830       return false;
8831 
8832     if (N->getOpcode() != ISD::DELETED_NODE)
8833       DCI.AddToWorklist(N);
8834     return true;
8835   };
8836 
8837   switch (N->getOpcode()) {
8838   default:
8839     break;
8840   case RISCVISD::SplitF64: {
8841     SDValue Op0 = N->getOperand(0);
8842     // If the input to SplitF64 is just BuildPairF64 then the operation is
8843     // redundant. Instead, use BuildPairF64's operands directly.
8844     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8845       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8846 
8847     if (Op0->isUndef()) {
8848       SDValue Lo = DAG.getUNDEF(MVT::i32);
8849       SDValue Hi = DAG.getUNDEF(MVT::i32);
8850       return DCI.CombineTo(N, Lo, Hi);
8851     }
8852 
8853     SDLoc DL(N);
8854 
8855     // It's cheaper to materialise two 32-bit integers than to load a double
8856     // from the constant pool and transfer it to integer registers through the
8857     // stack.
8858     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8859       APInt V = C->getValueAPF().bitcastToAPInt();
8860       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8861       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8862       return DCI.CombineTo(N, Lo, Hi);
8863     }
8864 
8865     // This is a target-specific version of a DAGCombine performed in
8866     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8867     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8868     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8869     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8870         !Op0.getNode()->hasOneUse())
8871       break;
8872     SDValue NewSplitF64 =
8873         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8874                     Op0.getOperand(0));
8875     SDValue Lo = NewSplitF64.getValue(0);
8876     SDValue Hi = NewSplitF64.getValue(1);
8877     APInt SignBit = APInt::getSignMask(32);
8878     if (Op0.getOpcode() == ISD::FNEG) {
8879       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8880                                   DAG.getConstant(SignBit, DL, MVT::i32));
8881       return DCI.CombineTo(N, Lo, NewHi);
8882     }
8883     assert(Op0.getOpcode() == ISD::FABS);
8884     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8885                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8886     return DCI.CombineTo(N, Lo, NewHi);
8887   }
8888   case RISCVISD::SLLW:
8889   case RISCVISD::SRAW:
8890   case RISCVISD::SRLW: {
8891     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8892     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8893         SimplifyDemandedLowBitsHelper(1, 5))
8894       return SDValue(N, 0);
8895 
8896     break;
8897   }
8898   case ISD::ROTR:
8899   case ISD::ROTL:
8900   case RISCVISD::RORW:
8901   case RISCVISD::ROLW: {
8902     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8903       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8904       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8905           SimplifyDemandedLowBitsHelper(1, 5))
8906         return SDValue(N, 0);
8907     }
8908 
8909     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8910   }
8911   case RISCVISD::CLZW:
8912   case RISCVISD::CTZW: {
8913     // Only the lower 32 bits of the first operand are read
8914     if (SimplifyDemandedLowBitsHelper(0, 32))
8915       return SDValue(N, 0);
8916     break;
8917   }
8918   case RISCVISD::GREV:
8919   case RISCVISD::GORC: {
8920     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8921     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8922     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8923     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8924       return SDValue(N, 0);
8925 
8926     return combineGREVI_GORCI(N, DAG);
8927   }
8928   case RISCVISD::GREVW:
8929   case RISCVISD::GORCW: {
8930     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8931     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8932         SimplifyDemandedLowBitsHelper(1, 5))
8933       return SDValue(N, 0);
8934 
8935     break;
8936   }
8937   case RISCVISD::SHFL:
8938   case RISCVISD::UNSHFL: {
8939     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8940     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8941     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8942     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8943       return SDValue(N, 0);
8944 
8945     break;
8946   }
8947   case RISCVISD::SHFLW:
8948   case RISCVISD::UNSHFLW: {
8949     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8950     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8951         SimplifyDemandedLowBitsHelper(1, 4))
8952       return SDValue(N, 0);
8953 
8954     break;
8955   }
8956   case RISCVISD::BCOMPRESSW:
8957   case RISCVISD::BDECOMPRESSW: {
8958     // Only the lower 32 bits of LHS and RHS are read.
8959     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8960         SimplifyDemandedLowBitsHelper(1, 32))
8961       return SDValue(N, 0);
8962 
8963     break;
8964   }
8965   case RISCVISD::FSR:
8966   case RISCVISD::FSL:
8967   case RISCVISD::FSRW:
8968   case RISCVISD::FSLW: {
8969     bool IsWInstruction =
8970         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8971     unsigned BitWidth =
8972         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8973     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8974     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8975     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8976       return SDValue(N, 0);
8977 
8978     break;
8979   }
8980   case RISCVISD::FMV_X_ANYEXTH:
8981   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8982     SDLoc DL(N);
8983     SDValue Op0 = N->getOperand(0);
8984     MVT VT = N->getSimpleValueType(0);
8985     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8986     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8987     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8988     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8989          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8990         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8991          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8992       assert(Op0.getOperand(0).getValueType() == VT &&
8993              "Unexpected value type!");
8994       return Op0.getOperand(0);
8995     }
8996 
8997     // This is a target-specific version of a DAGCombine performed in
8998     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8999     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
9000     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
9001     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
9002         !Op0.getNode()->hasOneUse())
9003       break;
9004     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
9005     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
9006     APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits());
9007     if (Op0.getOpcode() == ISD::FNEG)
9008       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
9009                          DAG.getConstant(SignBit, DL, VT));
9010 
9011     assert(Op0.getOpcode() == ISD::FABS);
9012     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
9013                        DAG.getConstant(~SignBit, DL, VT));
9014   }
9015   case ISD::ADD:
9016     return performADDCombine(N, DAG, Subtarget);
9017   case ISD::SUB:
9018     return performSUBCombine(N, DAG);
9019   case ISD::AND:
9020     return performANDCombine(N, DAG, Subtarget);
9021   case ISD::OR:
9022     return performORCombine(N, DAG, Subtarget);
9023   case ISD::XOR:
9024     return performXORCombine(N, DAG);
9025   case ISD::FADD:
9026   case ISD::UMAX:
9027   case ISD::UMIN:
9028   case ISD::SMAX:
9029   case ISD::SMIN:
9030   case ISD::FMAXNUM:
9031   case ISD::FMINNUM:
9032     return combineBinOpToReduce(N, DAG);
9033   case ISD::SETCC:
9034     return performSETCCCombine(N, DAG, Subtarget);
9035   case ISD::SIGN_EXTEND_INREG:
9036     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
9037   case ISD::ZERO_EXTEND:
9038     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
9039     // type legalization. This is safe because fp_to_uint produces poison if
9040     // it overflows.
9041     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
9042       SDValue Src = N->getOperand(0);
9043       if (Src.getOpcode() == ISD::FP_TO_UINT &&
9044           isTypeLegal(Src.getOperand(0).getValueType()))
9045         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
9046                            Src.getOperand(0));
9047       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
9048           isTypeLegal(Src.getOperand(1).getValueType())) {
9049         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
9050         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
9051                                   Src.getOperand(0), Src.getOperand(1));
9052         DCI.CombineTo(N, Res);
9053         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
9054         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
9055         return SDValue(N, 0); // Return N so it doesn't get rechecked.
9056       }
9057     }
9058     return SDValue();
9059   case RISCVISD::SELECT_CC: {
9060     // Transform
9061     SDValue LHS = N->getOperand(0);
9062     SDValue RHS = N->getOperand(1);
9063     SDValue CC = N->getOperand(2);
9064     SDValue TrueV = N->getOperand(3);
9065     SDValue FalseV = N->getOperand(4);
9066     SDLoc DL(N);
9067 
9068     // If the True and False values are the same, we don't need a select_cc.
9069     if (TrueV == FalseV)
9070       return TrueV;
9071 
9072     if (combine_CC(LHS, RHS, CC, DL, DAG, Subtarget))
9073       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
9074                          {LHS, RHS, CC, TrueV, FalseV});
9075 
9076     return SDValue();
9077   }
9078   case RISCVISD::BR_CC: {
9079     SDValue LHS = N->getOperand(1);
9080     SDValue RHS = N->getOperand(2);
9081     SDValue CC = N->getOperand(3);
9082     SDLoc DL(N);
9083 
9084     if (combine_CC(LHS, RHS, CC, DL, DAG, Subtarget))
9085       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
9086                          N->getOperand(0), LHS, RHS, CC, N->getOperand(4));
9087 
9088     return SDValue();
9089   }
9090   case ISD::BITREVERSE:
9091     return performBITREVERSECombine(N, DAG, Subtarget);
9092   case ISD::FP_TO_SINT:
9093   case ISD::FP_TO_UINT:
9094     return performFP_TO_INTCombine(N, DCI, Subtarget);
9095   case ISD::FP_TO_SINT_SAT:
9096   case ISD::FP_TO_UINT_SAT:
9097     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
9098   case ISD::FCOPYSIGN: {
9099     EVT VT = N->getValueType(0);
9100     if (!VT.isVector())
9101       break;
9102     // There is a form of VFSGNJ which injects the negated sign of its second
9103     // operand. Try and bubble any FNEG up after the extend/round to produce
9104     // this optimized pattern. Avoid modifying cases where FP_ROUND and
9105     // TRUNC=1.
9106     SDValue In2 = N->getOperand(1);
9107     // Avoid cases where the extend/round has multiple uses, as duplicating
9108     // those is typically more expensive than removing a fneg.
9109     if (!In2.hasOneUse())
9110       break;
9111     if (In2.getOpcode() != ISD::FP_EXTEND &&
9112         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
9113       break;
9114     In2 = In2.getOperand(0);
9115     if (In2.getOpcode() != ISD::FNEG)
9116       break;
9117     SDLoc DL(N);
9118     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
9119     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
9120                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
9121   }
9122   case ISD::MGATHER:
9123   case ISD::MSCATTER:
9124   case ISD::VP_GATHER:
9125   case ISD::VP_SCATTER: {
9126     if (!DCI.isBeforeLegalize())
9127       break;
9128     SDValue Index, ScaleOp;
9129     bool IsIndexScaled = false;
9130     bool IsIndexSigned = false;
9131     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
9132       Index = VPGSN->getIndex();
9133       ScaleOp = VPGSN->getScale();
9134       IsIndexScaled = VPGSN->isIndexScaled();
9135       IsIndexSigned = VPGSN->isIndexSigned();
9136     } else {
9137       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
9138       Index = MGSN->getIndex();
9139       ScaleOp = MGSN->getScale();
9140       IsIndexScaled = MGSN->isIndexScaled();
9141       IsIndexSigned = MGSN->isIndexSigned();
9142     }
9143     EVT IndexVT = Index.getValueType();
9144     MVT XLenVT = Subtarget.getXLenVT();
9145     // RISCV indexed loads only support the "unsigned unscaled" addressing
9146     // mode, so anything else must be manually legalized.
9147     bool NeedsIdxLegalization =
9148         IsIndexScaled ||
9149         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
9150     if (!NeedsIdxLegalization)
9151       break;
9152 
9153     SDLoc DL(N);
9154 
9155     // Any index legalization should first promote to XLenVT, so we don't lose
9156     // bits when scaling. This may create an illegal index type so we let
9157     // LLVM's legalization take care of the splitting.
9158     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
9159     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
9160       IndexVT = IndexVT.changeVectorElementType(XLenVT);
9161       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9162                           DL, IndexVT, Index);
9163     }
9164 
9165     if (IsIndexScaled) {
9166       // Manually scale the indices.
9167       // TODO: Sanitize the scale operand here?
9168       // TODO: For VP nodes, should we use VP_SHL here?
9169       unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
9170       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
9171       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
9172       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
9173       ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType());
9174     }
9175 
9176     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED;
9177     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
9178       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
9179                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
9180                               ScaleOp, VPGN->getMask(),
9181                               VPGN->getVectorLength()},
9182                              VPGN->getMemOperand(), NewIndexTy);
9183     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
9184       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
9185                               {VPSN->getChain(), VPSN->getValue(),
9186                                VPSN->getBasePtr(), Index, ScaleOp,
9187                                VPSN->getMask(), VPSN->getVectorLength()},
9188                               VPSN->getMemOperand(), NewIndexTy);
9189     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
9190       return DAG.getMaskedGather(
9191           N->getVTList(), MGN->getMemoryVT(), DL,
9192           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
9193            MGN->getBasePtr(), Index, ScaleOp},
9194           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
9195     const auto *MSN = cast<MaskedScatterSDNode>(N);
9196     return DAG.getMaskedScatter(
9197         N->getVTList(), MSN->getMemoryVT(), DL,
9198         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
9199          Index, ScaleOp},
9200         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
9201   }
9202   case RISCVISD::SRA_VL:
9203   case RISCVISD::SRL_VL:
9204   case RISCVISD::SHL_VL: {
9205     SDValue ShAmt = N->getOperand(1);
9206     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
9207       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
9208       SDLoc DL(N);
9209       SDValue VL = N->getOperand(3);
9210       EVT VT = N->getValueType(0);
9211       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
9212                           ShAmt.getOperand(1), VL);
9213       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
9214                          N->getOperand(2), N->getOperand(3));
9215     }
9216     break;
9217   }
9218   case ISD::SRA:
9219     if (SDValue V = performSRACombine(N, DAG, Subtarget))
9220       return V;
9221     LLVM_FALLTHROUGH;
9222   case ISD::SRL:
9223   case ISD::SHL: {
9224     SDValue ShAmt = N->getOperand(1);
9225     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
9226       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
9227       SDLoc DL(N);
9228       EVT VT = N->getValueType(0);
9229       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
9230                           ShAmt.getOperand(1),
9231                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
9232       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
9233     }
9234     break;
9235   }
9236   case RISCVISD::ADD_VL:
9237     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
9238       return V;
9239     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
9240   case RISCVISD::SUB_VL:
9241     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
9242   case RISCVISD::VWADD_W_VL:
9243   case RISCVISD::VWADDU_W_VL:
9244   case RISCVISD::VWSUB_W_VL:
9245   case RISCVISD::VWSUBU_W_VL:
9246     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
9247   case RISCVISD::MUL_VL:
9248     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
9249       return V;
9250     // Mul is commutative.
9251     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
9252   case RISCVISD::VFMADD_VL:
9253   case RISCVISD::VFNMADD_VL:
9254   case RISCVISD::VFMSUB_VL:
9255   case RISCVISD::VFNMSUB_VL: {
9256     // Fold FNEG_VL into FMA opcodes.
9257     SDValue A = N->getOperand(0);
9258     SDValue B = N->getOperand(1);
9259     SDValue C = N->getOperand(2);
9260     SDValue Mask = N->getOperand(3);
9261     SDValue VL = N->getOperand(4);
9262 
9263     auto invertIfNegative = [&Mask, &VL](SDValue &V) {
9264       if (V.getOpcode() == RISCVISD::FNEG_VL && V.getOperand(1) == Mask &&
9265           V.getOperand(2) == VL) {
9266         // Return the negated input.
9267         V = V.getOperand(0);
9268         return true;
9269       }
9270 
9271       return false;
9272     };
9273 
9274     bool NegA = invertIfNegative(A);
9275     bool NegB = invertIfNegative(B);
9276     bool NegC = invertIfNegative(C);
9277 
9278     // If no operands are negated, we're done.
9279     if (!NegA && !NegB && !NegC)
9280       return SDValue();
9281 
9282     unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC);
9283     return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), A, B, C, Mask,
9284                        VL);
9285   }
9286   case ISD::STORE: {
9287     auto *Store = cast<StoreSDNode>(N);
9288     SDValue Val = Store->getValue();
9289     // Combine store of vmv.x.s to vse with VL of 1.
9290     // FIXME: Support FP.
9291     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
9292       SDValue Src = Val.getOperand(0);
9293       MVT VecVT = Src.getSimpleValueType();
9294       EVT MemVT = Store->getMemoryVT();
9295       // The memory VT and the element type must match.
9296       if (MemVT == VecVT.getVectorElementType()) {
9297         SDLoc DL(N);
9298         MVT MaskVT = getMaskTypeFor(VecVT);
9299         return DAG.getStoreVP(
9300             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
9301             DAG.getConstant(1, DL, MaskVT),
9302             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
9303             Store->getMemOperand(), Store->getAddressingMode(),
9304             Store->isTruncatingStore(), /*IsCompress*/ false);
9305       }
9306     }
9307 
9308     break;
9309   }
9310   case ISD::SPLAT_VECTOR: {
9311     EVT VT = N->getValueType(0);
9312     // Only perform this combine on legal MVT types.
9313     if (!isTypeLegal(VT))
9314       break;
9315     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
9316                                          DAG, Subtarget))
9317       return Gather;
9318     break;
9319   }
9320   case RISCVISD::VMV_V_X_VL: {
9321     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
9322     // scalar input.
9323     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
9324     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
9325     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
9326       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
9327         return SDValue(N, 0);
9328 
9329     break;
9330   }
9331   case ISD::INTRINSIC_WO_CHAIN: {
9332     unsigned IntNo = N->getConstantOperandVal(0);
9333     switch (IntNo) {
9334       // By default we do not combine any intrinsic.
9335     default:
9336       return SDValue();
9337     case Intrinsic::riscv_vcpop:
9338     case Intrinsic::riscv_vcpop_mask:
9339     case Intrinsic::riscv_vfirst:
9340     case Intrinsic::riscv_vfirst_mask: {
9341       SDValue VL = N->getOperand(2);
9342       if (IntNo == Intrinsic::riscv_vcpop_mask ||
9343           IntNo == Intrinsic::riscv_vfirst_mask)
9344         VL = N->getOperand(3);
9345       if (!isNullConstant(VL))
9346         return SDValue();
9347       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
9348       SDLoc DL(N);
9349       EVT VT = N->getValueType(0);
9350       if (IntNo == Intrinsic::riscv_vfirst ||
9351           IntNo == Intrinsic::riscv_vfirst_mask)
9352         return DAG.getConstant(-1, DL, VT);
9353       return DAG.getConstant(0, DL, VT);
9354     }
9355     }
9356   }
9357   case ISD::BITCAST: {
9358     assert(Subtarget.useRVVForFixedLengthVectors());
9359     SDValue N0 = N->getOperand(0);
9360     EVT VT = N->getValueType(0);
9361     EVT SrcVT = N0.getValueType();
9362     // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer
9363     // type, widen both sides to avoid a trip through memory.
9364     if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) &&
9365         VT.isScalarInteger()) {
9366       unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
9367       SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
9368       Ops[0] = N0;
9369       SDLoc DL(N);
9370       N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops);
9371       N0 = DAG.getBitcast(MVT::i8, N0);
9372       return DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
9373     }
9374 
9375     return SDValue();
9376   }
9377   }
9378 
9379   return SDValue();
9380 }
9381 
9382 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
9383     const SDNode *N, CombineLevel Level) const {
9384   assert((N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA ||
9385           N->getOpcode() == ISD::SRL) &&
9386          "Expected shift op");
9387 
9388   // The following folds are only desirable if `(OP _, c1 << c2)` can be
9389   // materialised in fewer instructions than `(OP _, c1)`:
9390   //
9391   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
9392   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
9393   SDValue N0 = N->getOperand(0);
9394   EVT Ty = N0.getValueType();
9395   if (Ty.isScalarInteger() &&
9396       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
9397     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9398     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
9399     if (C1 && C2) {
9400       const APInt &C1Int = C1->getAPIntValue();
9401       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
9402 
9403       // We can materialise `c1 << c2` into an add immediate, so it's "free",
9404       // and the combine should happen, to potentially allow further combines
9405       // later.
9406       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
9407           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
9408         return true;
9409 
9410       // We can materialise `c1` in an add immediate, so it's "free", and the
9411       // combine should be prevented.
9412       if (C1Int.getMinSignedBits() <= 64 &&
9413           isLegalAddImmediate(C1Int.getSExtValue()))
9414         return false;
9415 
9416       // Neither constant will fit into an immediate, so find materialisation
9417       // costs.
9418       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
9419                                               Subtarget.getFeatureBits(),
9420                                               /*CompressionCost*/true);
9421       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
9422           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
9423           /*CompressionCost*/true);
9424 
9425       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
9426       // combine should be prevented.
9427       if (C1Cost < ShiftedC1Cost)
9428         return false;
9429     }
9430   }
9431   return true;
9432 }
9433 
9434 bool RISCVTargetLowering::targetShrinkDemandedConstant(
9435     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
9436     TargetLoweringOpt &TLO) const {
9437   // Delay this optimization as late as possible.
9438   if (!TLO.LegalOps)
9439     return false;
9440 
9441   EVT VT = Op.getValueType();
9442   if (VT.isVector())
9443     return false;
9444 
9445   // Only handle AND for now.
9446   unsigned Opcode = Op.getOpcode();
9447   if (Opcode != ISD::AND && Opcode != ISD::OR && Opcode != ISD::XOR)
9448     return false;
9449 
9450   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9451   if (!C)
9452     return false;
9453 
9454   const APInt &Mask = C->getAPIntValue();
9455 
9456   // Clear all non-demanded bits initially.
9457   APInt ShrunkMask = Mask & DemandedBits;
9458 
9459   // Try to make a smaller immediate by setting undemanded bits.
9460 
9461   APInt ExpandedMask = Mask | ~DemandedBits;
9462 
9463   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
9464     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
9465   };
9466   auto UseMask = [Mask, Op, &TLO](const APInt &NewMask) -> bool {
9467     if (NewMask == Mask)
9468       return true;
9469     SDLoc DL(Op);
9470     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, Op.getValueType());
9471     SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), DL, Op.getValueType(),
9472                                     Op.getOperand(0), NewC);
9473     return TLO.CombineTo(Op, NewOp);
9474   };
9475 
9476   // If the shrunk mask fits in sign extended 12 bits, let the target
9477   // independent code apply it.
9478   if (ShrunkMask.isSignedIntN(12))
9479     return false;
9480 
9481   // And has a few special cases for zext.
9482   if (Opcode == ISD::AND) {
9483     // Preserve (and X, 0xffff) when zext.h is supported.
9484     if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
9485       APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
9486       if (IsLegalMask(NewMask))
9487         return UseMask(NewMask);
9488     }
9489 
9490     // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
9491     if (VT == MVT::i64) {
9492       APInt NewMask = APInt(64, 0xffffffff);
9493       if (IsLegalMask(NewMask))
9494         return UseMask(NewMask);
9495     }
9496   }
9497 
9498   // For the remaining optimizations, we need to be able to make a negative
9499   // number through a combination of mask and undemanded bits.
9500   if (!ExpandedMask.isNegative())
9501     return false;
9502 
9503   // What is the fewest number of bits we need to represent the negative number.
9504   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
9505 
9506   // Try to make a 12 bit negative immediate. If that fails try to make a 32
9507   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
9508   // If we can't create a simm12, we shouldn't change opaque constants.
9509   APInt NewMask = ShrunkMask;
9510   if (MinSignedBits <= 12)
9511     NewMask.setBitsFrom(11);
9512   else if (!C->isOpaque() && MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
9513     NewMask.setBitsFrom(31);
9514   else
9515     return false;
9516 
9517   // Check that our new mask is a subset of the demanded mask.
9518   assert(IsLegalMask(NewMask));
9519   return UseMask(NewMask);
9520 }
9521 
9522 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
9523   static const uint64_t GREVMasks[] = {
9524       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
9525       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
9526 
9527   for (unsigned Stage = 0; Stage != 6; ++Stage) {
9528     unsigned Shift = 1 << Stage;
9529     if (ShAmt & Shift) {
9530       uint64_t Mask = GREVMasks[Stage];
9531       uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
9532       if (IsGORC)
9533         Res |= x;
9534       x = Res;
9535     }
9536   }
9537 
9538   return x;
9539 }
9540 
9541 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9542                                                         KnownBits &Known,
9543                                                         const APInt &DemandedElts,
9544                                                         const SelectionDAG &DAG,
9545                                                         unsigned Depth) const {
9546   unsigned BitWidth = Known.getBitWidth();
9547   unsigned Opc = Op.getOpcode();
9548   assert((Opc >= ISD::BUILTIN_OP_END ||
9549           Opc == ISD::INTRINSIC_WO_CHAIN ||
9550           Opc == ISD::INTRINSIC_W_CHAIN ||
9551           Opc == ISD::INTRINSIC_VOID) &&
9552          "Should use MaskedValueIsZero if you don't know whether Op"
9553          " is a target node!");
9554 
9555   Known.resetAll();
9556   switch (Opc) {
9557   default: break;
9558   case RISCVISD::SELECT_CC: {
9559     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
9560     // If we don't know any bits, early out.
9561     if (Known.isUnknown())
9562       break;
9563     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
9564 
9565     // Only known if known in both the LHS and RHS.
9566     Known = KnownBits::commonBits(Known, Known2);
9567     break;
9568   }
9569   case RISCVISD::REMUW: {
9570     KnownBits Known2;
9571     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9572     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9573     // We only care about the lower 32 bits.
9574     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
9575     // Restore the original width by sign extending.
9576     Known = Known.sext(BitWidth);
9577     break;
9578   }
9579   case RISCVISD::DIVUW: {
9580     KnownBits Known2;
9581     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9582     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9583     // We only care about the lower 32 bits.
9584     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
9585     // Restore the original width by sign extending.
9586     Known = Known.sext(BitWidth);
9587     break;
9588   }
9589   case RISCVISD::CTZW: {
9590     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9591     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
9592     unsigned LowBits = Log2_32(PossibleTZ) + 1;
9593     Known.Zero.setBitsFrom(LowBits);
9594     break;
9595   }
9596   case RISCVISD::CLZW: {
9597     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9598     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
9599     unsigned LowBits = Log2_32(PossibleLZ) + 1;
9600     Known.Zero.setBitsFrom(LowBits);
9601     break;
9602   }
9603   case RISCVISD::GREV:
9604   case RISCVISD::GORC: {
9605     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9606       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9607       unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1);
9608       bool IsGORC = Op.getOpcode() == RISCVISD::GORC;
9609       // To compute zeros, we need to invert the value and invert it back after.
9610       Known.Zero =
9611           ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC);
9612       Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC);
9613     }
9614     break;
9615   }
9616   case RISCVISD::READ_VLENB: {
9617     // We can use the minimum and maximum VLEN values to bound VLENB.  We
9618     // know VLEN must be a power of two.
9619     const unsigned MinVLenB = Subtarget.getRealMinVLen() / 8;
9620     const unsigned MaxVLenB = Subtarget.getRealMaxVLen() / 8;
9621     assert(MinVLenB > 0 && "READ_VLENB without vector extension enabled?");
9622     Known.Zero.setLowBits(Log2_32(MinVLenB));
9623     Known.Zero.setBitsFrom(Log2_32(MaxVLenB)+1);
9624     if (MaxVLenB == MinVLenB)
9625       Known.One.setBit(Log2_32(MinVLenB));
9626     break;
9627   }
9628   case ISD::INTRINSIC_W_CHAIN:
9629   case ISD::INTRINSIC_WO_CHAIN: {
9630     unsigned IntNo =
9631         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9632     switch (IntNo) {
9633     default:
9634       // We can't do anything for most intrinsics.
9635       break;
9636     case Intrinsic::riscv_vsetvli:
9637     case Intrinsic::riscv_vsetvlimax:
9638     case Intrinsic::riscv_vsetvli_opt:
9639     case Intrinsic::riscv_vsetvlimax_opt:
9640       // Assume that VL output is positive and would fit in an int32_t.
9641       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9642       if (BitWidth >= 32)
9643         Known.Zero.setBitsFrom(31);
9644       break;
9645     }
9646     break;
9647   }
9648   }
9649 }
9650 
9651 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9652     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9653     unsigned Depth) const {
9654   switch (Op.getOpcode()) {
9655   default:
9656     break;
9657   case RISCVISD::SELECT_CC: {
9658     unsigned Tmp =
9659         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9660     if (Tmp == 1) return 1;  // Early out.
9661     unsigned Tmp2 =
9662         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9663     return std::min(Tmp, Tmp2);
9664   }
9665   case RISCVISD::SLLW:
9666   case RISCVISD::SRAW:
9667   case RISCVISD::SRLW:
9668   case RISCVISD::DIVW:
9669   case RISCVISD::DIVUW:
9670   case RISCVISD::REMUW:
9671   case RISCVISD::ROLW:
9672   case RISCVISD::RORW:
9673   case RISCVISD::GREVW:
9674   case RISCVISD::GORCW:
9675   case RISCVISD::FSLW:
9676   case RISCVISD::FSRW:
9677   case RISCVISD::SHFLW:
9678   case RISCVISD::UNSHFLW:
9679   case RISCVISD::BCOMPRESSW:
9680   case RISCVISD::BDECOMPRESSW:
9681   case RISCVISD::BFPW:
9682   case RISCVISD::FCVT_W_RV64:
9683   case RISCVISD::FCVT_WU_RV64:
9684   case RISCVISD::STRICT_FCVT_W_RV64:
9685   case RISCVISD::STRICT_FCVT_WU_RV64:
9686     // TODO: As the result is sign-extended, this is conservatively correct. A
9687     // more precise answer could be calculated for SRAW depending on known
9688     // bits in the shift amount.
9689     return 33;
9690   case RISCVISD::SHFL:
9691   case RISCVISD::UNSHFL: {
9692     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9693     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9694     // will stay within the upper 32 bits. If there were more than 32 sign bits
9695     // before there will be at least 33 sign bits after.
9696     if (Op.getValueType() == MVT::i64 &&
9697         isa<ConstantSDNode>(Op.getOperand(1)) &&
9698         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9699       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9700       if (Tmp > 32)
9701         return 33;
9702     }
9703     break;
9704   }
9705   case RISCVISD::VMV_X_S: {
9706     // The number of sign bits of the scalar result is computed by obtaining the
9707     // element type of the input vector operand, subtracting its width from the
9708     // XLEN, and then adding one (sign bit within the element type). If the
9709     // element type is wider than XLen, the least-significant XLEN bits are
9710     // taken.
9711     unsigned XLen = Subtarget.getXLen();
9712     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9713     if (EltBits <= XLen)
9714       return XLen - EltBits + 1;
9715     break;
9716   }
9717   }
9718 
9719   return 1;
9720 }
9721 
9722 const Constant *
9723 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const {
9724   assert(Ld && "Unexpected null LoadSDNode");
9725   if (!ISD::isNormalLoad(Ld))
9726     return nullptr;
9727 
9728   SDValue Ptr = Ld->getBasePtr();
9729 
9730   // Only constant pools with no offset are supported.
9731   auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * {
9732     auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
9733     if (!CNode || CNode->isMachineConstantPoolEntry() ||
9734         CNode->getOffset() != 0)
9735       return nullptr;
9736 
9737     return CNode;
9738   };
9739 
9740   // Simple case, LLA.
9741   if (Ptr.getOpcode() == RISCVISD::LLA) {
9742     auto *CNode = GetSupportedConstantPool(Ptr);
9743     if (!CNode || CNode->getTargetFlags() != 0)
9744       return nullptr;
9745 
9746     return CNode->getConstVal();
9747   }
9748 
9749   // Look for a HI and ADD_LO pair.
9750   if (Ptr.getOpcode() != RISCVISD::ADD_LO ||
9751       Ptr.getOperand(0).getOpcode() != RISCVISD::HI)
9752     return nullptr;
9753 
9754   auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1));
9755   auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0));
9756 
9757   if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO ||
9758       !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI)
9759     return nullptr;
9760 
9761   if (CNodeLo->getConstVal() != CNodeHi->getConstVal())
9762     return nullptr;
9763 
9764   return CNodeLo->getConstVal();
9765 }
9766 
9767 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9768                                                   MachineBasicBlock *BB) {
9769   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9770 
9771   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9772   // Should the count have wrapped while it was being read, we need to try
9773   // again.
9774   // ...
9775   // read:
9776   // rdcycleh x3 # load high word of cycle
9777   // rdcycle  x2 # load low word of cycle
9778   // rdcycleh x4 # load high word of cycle
9779   // bne x3, x4, read # check if high word reads match, otherwise try again
9780   // ...
9781 
9782   MachineFunction &MF = *BB->getParent();
9783   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9784   MachineFunction::iterator It = ++BB->getIterator();
9785 
9786   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9787   MF.insert(It, LoopMBB);
9788 
9789   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9790   MF.insert(It, DoneMBB);
9791 
9792   // Transfer the remainder of BB and its successor edges to DoneMBB.
9793   DoneMBB->splice(DoneMBB->begin(), BB,
9794                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9795   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9796 
9797   BB->addSuccessor(LoopMBB);
9798 
9799   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9800   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9801   Register LoReg = MI.getOperand(0).getReg();
9802   Register HiReg = MI.getOperand(1).getReg();
9803   DebugLoc DL = MI.getDebugLoc();
9804 
9805   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9806   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9807       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9808       .addReg(RISCV::X0);
9809   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9810       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9811       .addReg(RISCV::X0);
9812   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9813       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9814       .addReg(RISCV::X0);
9815 
9816   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9817       .addReg(HiReg)
9818       .addReg(ReadAgainReg)
9819       .addMBB(LoopMBB);
9820 
9821   LoopMBB->addSuccessor(LoopMBB);
9822   LoopMBB->addSuccessor(DoneMBB);
9823 
9824   MI.eraseFromParent();
9825 
9826   return DoneMBB;
9827 }
9828 
9829 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9830                                              MachineBasicBlock *BB) {
9831   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9832 
9833   MachineFunction &MF = *BB->getParent();
9834   DebugLoc DL = MI.getDebugLoc();
9835   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9836   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9837   Register LoReg = MI.getOperand(0).getReg();
9838   Register HiReg = MI.getOperand(1).getReg();
9839   Register SrcReg = MI.getOperand(2).getReg();
9840   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9841   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9842 
9843   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9844                           RI);
9845   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9846   MachineMemOperand *MMOLo =
9847       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9848   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9849       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9850   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9851       .addFrameIndex(FI)
9852       .addImm(0)
9853       .addMemOperand(MMOLo);
9854   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9855       .addFrameIndex(FI)
9856       .addImm(4)
9857       .addMemOperand(MMOHi);
9858   MI.eraseFromParent(); // The pseudo instruction is gone now.
9859   return BB;
9860 }
9861 
9862 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9863                                                  MachineBasicBlock *BB) {
9864   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9865          "Unexpected instruction");
9866 
9867   MachineFunction &MF = *BB->getParent();
9868   DebugLoc DL = MI.getDebugLoc();
9869   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9870   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9871   Register DstReg = MI.getOperand(0).getReg();
9872   Register LoReg = MI.getOperand(1).getReg();
9873   Register HiReg = MI.getOperand(2).getReg();
9874   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9875   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9876 
9877   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9878   MachineMemOperand *MMOLo =
9879       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9880   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9881       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9882   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9883       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9884       .addFrameIndex(FI)
9885       .addImm(0)
9886       .addMemOperand(MMOLo);
9887   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9888       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9889       .addFrameIndex(FI)
9890       .addImm(4)
9891       .addMemOperand(MMOHi);
9892   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9893   MI.eraseFromParent(); // The pseudo instruction is gone now.
9894   return BB;
9895 }
9896 
9897 static bool isSelectPseudo(MachineInstr &MI) {
9898   switch (MI.getOpcode()) {
9899   default:
9900     return false;
9901   case RISCV::Select_GPR_Using_CC_GPR:
9902   case RISCV::Select_FPR16_Using_CC_GPR:
9903   case RISCV::Select_FPR32_Using_CC_GPR:
9904   case RISCV::Select_FPR64_Using_CC_GPR:
9905     return true;
9906   }
9907 }
9908 
9909 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9910                                         unsigned RelOpcode, unsigned EqOpcode,
9911                                         const RISCVSubtarget &Subtarget) {
9912   DebugLoc DL = MI.getDebugLoc();
9913   Register DstReg = MI.getOperand(0).getReg();
9914   Register Src1Reg = MI.getOperand(1).getReg();
9915   Register Src2Reg = MI.getOperand(2).getReg();
9916   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9917   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9918   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9919 
9920   // Save the current FFLAGS.
9921   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9922 
9923   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9924                  .addReg(Src1Reg)
9925                  .addReg(Src2Reg);
9926   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9927     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9928 
9929   // Restore the FFLAGS.
9930   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9931       .addReg(SavedFFlags, RegState::Kill);
9932 
9933   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9934   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9935                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9936                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9937   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9938     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9939 
9940   // Erase the pseudoinstruction.
9941   MI.eraseFromParent();
9942   return BB;
9943 }
9944 
9945 static MachineBasicBlock *
9946 EmitLoweredCascadedSelect(MachineInstr &First, MachineInstr &Second,
9947                           MachineBasicBlock *ThisMBB,
9948                           const RISCVSubtarget &Subtarget) {
9949   // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5)
9950   // Without this, custom-inserter would have generated:
9951   //
9952   //   A
9953   //   | \
9954   //   |  B
9955   //   | /
9956   //   C
9957   //   | \
9958   //   |  D
9959   //   | /
9960   //   E
9961   //
9962   // A: X = ...; Y = ...
9963   // B: empty
9964   // C: Z = PHI [X, A], [Y, B]
9965   // D: empty
9966   // E: PHI [X, C], [Z, D]
9967   //
9968   // If we lower both Select_FPRX_ in a single step, we can instead generate:
9969   //
9970   //   A
9971   //   | \
9972   //   |  C
9973   //   | /|
9974   //   |/ |
9975   //   |  |
9976   //   |  D
9977   //   | /
9978   //   E
9979   //
9980   // A: X = ...; Y = ...
9981   // D: empty
9982   // E: PHI [X, A], [X, C], [Y, D]
9983 
9984   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9985   const DebugLoc &DL = First.getDebugLoc();
9986   const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
9987   MachineFunction *F = ThisMBB->getParent();
9988   MachineBasicBlock *FirstMBB = F->CreateMachineBasicBlock(LLVM_BB);
9989   MachineBasicBlock *SecondMBB = F->CreateMachineBasicBlock(LLVM_BB);
9990   MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9991   MachineFunction::iterator It = ++ThisMBB->getIterator();
9992   F->insert(It, FirstMBB);
9993   F->insert(It, SecondMBB);
9994   F->insert(It, SinkMBB);
9995 
9996   // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
9997   SinkMBB->splice(SinkMBB->begin(), ThisMBB,
9998                   std::next(MachineBasicBlock::iterator(First)),
9999                   ThisMBB->end());
10000   SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
10001 
10002   // Fallthrough block for ThisMBB.
10003   ThisMBB->addSuccessor(FirstMBB);
10004   // Fallthrough block for FirstMBB.
10005   FirstMBB->addSuccessor(SecondMBB);
10006   ThisMBB->addSuccessor(SinkMBB);
10007   FirstMBB->addSuccessor(SinkMBB);
10008   // This is fallthrough.
10009   SecondMBB->addSuccessor(SinkMBB);
10010 
10011   auto FirstCC = static_cast<RISCVCC::CondCode>(First.getOperand(3).getImm());
10012   Register FLHS = First.getOperand(1).getReg();
10013   Register FRHS = First.getOperand(2).getReg();
10014   // Insert appropriate branch.
10015   BuildMI(FirstMBB, DL, TII.getBrCond(FirstCC))
10016       .addReg(FLHS)
10017       .addReg(FRHS)
10018       .addMBB(SinkMBB);
10019 
10020   Register SLHS = Second.getOperand(1).getReg();
10021   Register SRHS = Second.getOperand(2).getReg();
10022   Register Op1Reg4 = First.getOperand(4).getReg();
10023   Register Op1Reg5 = First.getOperand(5).getReg();
10024 
10025   auto SecondCC = static_cast<RISCVCC::CondCode>(Second.getOperand(3).getImm());
10026   // Insert appropriate branch.
10027   BuildMI(ThisMBB, DL, TII.getBrCond(SecondCC))
10028       .addReg(SLHS)
10029       .addReg(SRHS)
10030       .addMBB(SinkMBB);
10031 
10032   Register DestReg = Second.getOperand(0).getReg();
10033   Register Op2Reg4 = Second.getOperand(4).getReg();
10034   BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII.get(RISCV::PHI), DestReg)
10035       .addReg(Op2Reg4)
10036       .addMBB(ThisMBB)
10037       .addReg(Op1Reg4)
10038       .addMBB(FirstMBB)
10039       .addReg(Op1Reg5)
10040       .addMBB(SecondMBB);
10041 
10042   // Now remove the Select_FPRX_s.
10043   First.eraseFromParent();
10044   Second.eraseFromParent();
10045   return SinkMBB;
10046 }
10047 
10048 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
10049                                            MachineBasicBlock *BB,
10050                                            const RISCVSubtarget &Subtarget) {
10051   // To "insert" Select_* instructions, we actually have to insert the triangle
10052   // control-flow pattern.  The incoming instructions know the destination vreg
10053   // to set, the condition code register to branch on, the true/false values to
10054   // select between, and the condcode to use to select the appropriate branch.
10055   //
10056   // We produce the following control flow:
10057   //     HeadMBB
10058   //     |  \
10059   //     |  IfFalseMBB
10060   //     | /
10061   //    TailMBB
10062   //
10063   // When we find a sequence of selects we attempt to optimize their emission
10064   // by sharing the control flow. Currently we only handle cases where we have
10065   // multiple selects with the exact same condition (same LHS, RHS and CC).
10066   // The selects may be interleaved with other instructions if the other
10067   // instructions meet some requirements we deem safe:
10068   // - They are debug instructions. Otherwise,
10069   // - They do not have side-effects, do not access memory and their inputs do
10070   //   not depend on the results of the select pseudo-instructions.
10071   // The TrueV/FalseV operands of the selects cannot depend on the result of
10072   // previous selects in the sequence.
10073   // These conditions could be further relaxed. See the X86 target for a
10074   // related approach and more information.
10075   //
10076   // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5))
10077   // is checked here and handled by a separate function -
10078   // EmitLoweredCascadedSelect.
10079   Register LHS = MI.getOperand(1).getReg();
10080   Register RHS = MI.getOperand(2).getReg();
10081   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
10082 
10083   SmallVector<MachineInstr *, 4> SelectDebugValues;
10084   SmallSet<Register, 4> SelectDests;
10085   SelectDests.insert(MI.getOperand(0).getReg());
10086 
10087   MachineInstr *LastSelectPseudo = &MI;
10088   auto Next = next_nodbg(MI.getIterator(), BB->instr_end());
10089   if (MI.getOpcode() != RISCV::Select_GPR_Using_CC_GPR && Next != BB->end() &&
10090       Next->getOpcode() == MI.getOpcode() &&
10091       Next->getOperand(5).getReg() == MI.getOperand(0).getReg() &&
10092       Next->getOperand(5).isKill()) {
10093     return EmitLoweredCascadedSelect(MI, *Next, BB, Subtarget);
10094   }
10095 
10096   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
10097        SequenceMBBI != E; ++SequenceMBBI) {
10098     if (SequenceMBBI->isDebugInstr())
10099       continue;
10100     if (isSelectPseudo(*SequenceMBBI)) {
10101       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
10102           SequenceMBBI->getOperand(2).getReg() != RHS ||
10103           SequenceMBBI->getOperand(3).getImm() != CC ||
10104           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
10105           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
10106         break;
10107       LastSelectPseudo = &*SequenceMBBI;
10108       SequenceMBBI->collectDebugValues(SelectDebugValues);
10109       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
10110       continue;
10111     }
10112     if (SequenceMBBI->hasUnmodeledSideEffects() ||
10113         SequenceMBBI->mayLoadOrStore())
10114       break;
10115     if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
10116           return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
10117         }))
10118       break;
10119   }
10120 
10121   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
10122   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10123   DebugLoc DL = MI.getDebugLoc();
10124   MachineFunction::iterator I = ++BB->getIterator();
10125 
10126   MachineBasicBlock *HeadMBB = BB;
10127   MachineFunction *F = BB->getParent();
10128   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
10129   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
10130 
10131   F->insert(I, IfFalseMBB);
10132   F->insert(I, TailMBB);
10133 
10134   // Transfer debug instructions associated with the selects to TailMBB.
10135   for (MachineInstr *DebugInstr : SelectDebugValues) {
10136     TailMBB->push_back(DebugInstr->removeFromParent());
10137   }
10138 
10139   // Move all instructions after the sequence to TailMBB.
10140   TailMBB->splice(TailMBB->end(), HeadMBB,
10141                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
10142   // Update machine-CFG edges by transferring all successors of the current
10143   // block to the new block which will contain the Phi nodes for the selects.
10144   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
10145   // Set the successors for HeadMBB.
10146   HeadMBB->addSuccessor(IfFalseMBB);
10147   HeadMBB->addSuccessor(TailMBB);
10148 
10149   // Insert appropriate branch.
10150   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
10151     .addReg(LHS)
10152     .addReg(RHS)
10153     .addMBB(TailMBB);
10154 
10155   // IfFalseMBB just falls through to TailMBB.
10156   IfFalseMBB->addSuccessor(TailMBB);
10157 
10158   // Create PHIs for all of the select pseudo-instructions.
10159   auto SelectMBBI = MI.getIterator();
10160   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
10161   auto InsertionPoint = TailMBB->begin();
10162   while (SelectMBBI != SelectEnd) {
10163     auto Next = std::next(SelectMBBI);
10164     if (isSelectPseudo(*SelectMBBI)) {
10165       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
10166       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
10167               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
10168           .addReg(SelectMBBI->getOperand(4).getReg())
10169           .addMBB(HeadMBB)
10170           .addReg(SelectMBBI->getOperand(5).getReg())
10171           .addMBB(IfFalseMBB);
10172       SelectMBBI->eraseFromParent();
10173     }
10174     SelectMBBI = Next;
10175   }
10176 
10177   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
10178   return TailMBB;
10179 }
10180 
10181 MachineBasicBlock *
10182 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10183                                                  MachineBasicBlock *BB) const {
10184   switch (MI.getOpcode()) {
10185   default:
10186     llvm_unreachable("Unexpected instr type to insert");
10187   case RISCV::ReadCycleWide:
10188     assert(!Subtarget.is64Bit() &&
10189            "ReadCycleWrite is only to be used on riscv32");
10190     return emitReadCycleWidePseudo(MI, BB);
10191   case RISCV::Select_GPR_Using_CC_GPR:
10192   case RISCV::Select_FPR16_Using_CC_GPR:
10193   case RISCV::Select_FPR32_Using_CC_GPR:
10194   case RISCV::Select_FPR64_Using_CC_GPR:
10195     return emitSelectPseudo(MI, BB, Subtarget);
10196   case RISCV::BuildPairF64Pseudo:
10197     return emitBuildPairF64Pseudo(MI, BB);
10198   case RISCV::SplitF64Pseudo:
10199     return emitSplitF64Pseudo(MI, BB);
10200   case RISCV::PseudoQuietFLE_H:
10201     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
10202   case RISCV::PseudoQuietFLT_H:
10203     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
10204   case RISCV::PseudoQuietFLE_S:
10205     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
10206   case RISCV::PseudoQuietFLT_S:
10207     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
10208   case RISCV::PseudoQuietFLE_D:
10209     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
10210   case RISCV::PseudoQuietFLT_D:
10211     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
10212   }
10213 }
10214 
10215 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10216                                                         SDNode *Node) const {
10217   // Add FRM dependency to any instructions with dynamic rounding mode.
10218   unsigned Opc = MI.getOpcode();
10219   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
10220   if (Idx < 0)
10221     return;
10222   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
10223     return;
10224   // If the instruction already reads FRM, don't add another read.
10225   if (MI.readsRegister(RISCV::FRM))
10226     return;
10227   MI.addOperand(
10228       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
10229 }
10230 
10231 // Calling Convention Implementation.
10232 // The expectations for frontend ABI lowering vary from target to target.
10233 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
10234 // details, but this is a longer term goal. For now, we simply try to keep the
10235 // role of the frontend as simple and well-defined as possible. The rules can
10236 // be summarised as:
10237 // * Never split up large scalar arguments. We handle them here.
10238 // * If a hardfloat calling convention is being used, and the struct may be
10239 // passed in a pair of registers (fp+fp, int+fp), and both registers are
10240 // available, then pass as two separate arguments. If either the GPRs or FPRs
10241 // are exhausted, then pass according to the rule below.
10242 // * If a struct could never be passed in registers or directly in a stack
10243 // slot (as it is larger than 2*XLEN and the floating point rules don't
10244 // apply), then pass it using a pointer with the byval attribute.
10245 // * If a struct is less than 2*XLEN, then coerce to either a two-element
10246 // word-sized array or a 2*XLEN scalar (depending on alignment).
10247 // * The frontend can determine whether a struct is returned by reference or
10248 // not based on its size and fields. If it will be returned by reference, the
10249 // frontend must modify the prototype so a pointer with the sret annotation is
10250 // passed as the first argument. This is not necessary for large scalar
10251 // returns.
10252 // * Struct return values and varargs should be coerced to structs containing
10253 // register-size fields in the same situations they would be for fixed
10254 // arguments.
10255 
10256 static const MCPhysReg ArgGPRs[] = {
10257   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
10258   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
10259 };
10260 static const MCPhysReg ArgFPR16s[] = {
10261   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
10262   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
10263 };
10264 static const MCPhysReg ArgFPR32s[] = {
10265   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
10266   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
10267 };
10268 static const MCPhysReg ArgFPR64s[] = {
10269   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
10270   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
10271 };
10272 // This is an interim calling convention and it may be changed in the future.
10273 static const MCPhysReg ArgVRs[] = {
10274     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
10275     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
10276     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
10277 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
10278                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
10279                                      RISCV::V20M2, RISCV::V22M2};
10280 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
10281                                      RISCV::V20M4};
10282 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
10283 
10284 // Pass a 2*XLEN argument that has been split into two XLEN values through
10285 // registers or the stack as necessary.
10286 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
10287                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
10288                                 MVT ValVT2, MVT LocVT2,
10289                                 ISD::ArgFlagsTy ArgFlags2) {
10290   unsigned XLenInBytes = XLen / 8;
10291   if (Register Reg = State.AllocateReg(ArgGPRs)) {
10292     // At least one half can be passed via register.
10293     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
10294                                      VA1.getLocVT(), CCValAssign::Full));
10295   } else {
10296     // Both halves must be passed on the stack, with proper alignment.
10297     Align StackAlign =
10298         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
10299     State.addLoc(
10300         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
10301                             State.AllocateStack(XLenInBytes, StackAlign),
10302                             VA1.getLocVT(), CCValAssign::Full));
10303     State.addLoc(CCValAssign::getMem(
10304         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
10305         LocVT2, CCValAssign::Full));
10306     return false;
10307   }
10308 
10309   if (Register Reg = State.AllocateReg(ArgGPRs)) {
10310     // The second half can also be passed via register.
10311     State.addLoc(
10312         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
10313   } else {
10314     // The second half is passed via the stack, without additional alignment.
10315     State.addLoc(CCValAssign::getMem(
10316         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
10317         LocVT2, CCValAssign::Full));
10318   }
10319 
10320   return false;
10321 }
10322 
10323 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
10324                                Optional<unsigned> FirstMaskArgument,
10325                                CCState &State, const RISCVTargetLowering &TLI) {
10326   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
10327   if (RC == &RISCV::VRRegClass) {
10328     // Assign the first mask argument to V0.
10329     // This is an interim calling convention and it may be changed in the
10330     // future.
10331     if (FirstMaskArgument && ValNo == *FirstMaskArgument)
10332       return State.AllocateReg(RISCV::V0);
10333     return State.AllocateReg(ArgVRs);
10334   }
10335   if (RC == &RISCV::VRM2RegClass)
10336     return State.AllocateReg(ArgVRM2s);
10337   if (RC == &RISCV::VRM4RegClass)
10338     return State.AllocateReg(ArgVRM4s);
10339   if (RC == &RISCV::VRM8RegClass)
10340     return State.AllocateReg(ArgVRM8s);
10341   llvm_unreachable("Unhandled register class for ValueType");
10342 }
10343 
10344 // Implements the RISC-V calling convention. Returns true upon failure.
10345 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
10346                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
10347                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
10348                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
10349                      Optional<unsigned> FirstMaskArgument) {
10350   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
10351   assert(XLen == 32 || XLen == 64);
10352   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
10353 
10354   // Any return value split in to more than two values can't be returned
10355   // directly. Vectors are returned via the available vector registers.
10356   if (!LocVT.isVector() && IsRet && ValNo > 1)
10357     return true;
10358 
10359   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
10360   // variadic argument, or if no F16/F32 argument registers are available.
10361   bool UseGPRForF16_F32 = true;
10362   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
10363   // variadic argument, or if no F64 argument registers are available.
10364   bool UseGPRForF64 = true;
10365 
10366   switch (ABI) {
10367   default:
10368     llvm_unreachable("Unexpected ABI");
10369   case RISCVABI::ABI_ILP32:
10370   case RISCVABI::ABI_LP64:
10371     break;
10372   case RISCVABI::ABI_ILP32F:
10373   case RISCVABI::ABI_LP64F:
10374     UseGPRForF16_F32 = !IsFixed;
10375     break;
10376   case RISCVABI::ABI_ILP32D:
10377   case RISCVABI::ABI_LP64D:
10378     UseGPRForF16_F32 = !IsFixed;
10379     UseGPRForF64 = !IsFixed;
10380     break;
10381   }
10382 
10383   // FPR16, FPR32, and FPR64 alias each other.
10384   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
10385     UseGPRForF16_F32 = true;
10386     UseGPRForF64 = true;
10387   }
10388 
10389   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
10390   // similar local variables rather than directly checking against the target
10391   // ABI.
10392 
10393   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
10394     LocVT = XLenVT;
10395     LocInfo = CCValAssign::BCvt;
10396   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
10397     LocVT = MVT::i64;
10398     LocInfo = CCValAssign::BCvt;
10399   }
10400 
10401   // If this is a variadic argument, the RISC-V calling convention requires
10402   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
10403   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
10404   // be used regardless of whether the original argument was split during
10405   // legalisation or not. The argument will not be passed by registers if the
10406   // original type is larger than 2*XLEN, so the register alignment rule does
10407   // not apply.
10408   unsigned TwoXLenInBytes = (2 * XLen) / 8;
10409   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
10410       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
10411     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
10412     // Skip 'odd' register if necessary.
10413     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
10414       State.AllocateReg(ArgGPRs);
10415   }
10416 
10417   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
10418   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
10419       State.getPendingArgFlags();
10420 
10421   assert(PendingLocs.size() == PendingArgFlags.size() &&
10422          "PendingLocs and PendingArgFlags out of sync");
10423 
10424   // Handle passing f64 on RV32D with a soft float ABI or when floating point
10425   // registers are exhausted.
10426   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
10427     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
10428            "Can't lower f64 if it is split");
10429     // Depending on available argument GPRS, f64 may be passed in a pair of
10430     // GPRs, split between a GPR and the stack, or passed completely on the
10431     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
10432     // cases.
10433     Register Reg = State.AllocateReg(ArgGPRs);
10434     LocVT = MVT::i32;
10435     if (!Reg) {
10436       unsigned StackOffset = State.AllocateStack(8, Align(8));
10437       State.addLoc(
10438           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10439       return false;
10440     }
10441     if (!State.AllocateReg(ArgGPRs))
10442       State.AllocateStack(4, Align(4));
10443     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10444     return false;
10445   }
10446 
10447   // Fixed-length vectors are located in the corresponding scalable-vector
10448   // container types.
10449   if (ValVT.isFixedLengthVector())
10450     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10451 
10452   // Split arguments might be passed indirectly, so keep track of the pending
10453   // values. Split vectors are passed via a mix of registers and indirectly, so
10454   // treat them as we would any other argument.
10455   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
10456     LocVT = XLenVT;
10457     LocInfo = CCValAssign::Indirect;
10458     PendingLocs.push_back(
10459         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
10460     PendingArgFlags.push_back(ArgFlags);
10461     if (!ArgFlags.isSplitEnd()) {
10462       return false;
10463     }
10464   }
10465 
10466   // If the split argument only had two elements, it should be passed directly
10467   // in registers or on the stack.
10468   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
10469       PendingLocs.size() <= 2) {
10470     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
10471     // Apply the normal calling convention rules to the first half of the
10472     // split argument.
10473     CCValAssign VA = PendingLocs[0];
10474     ISD::ArgFlagsTy AF = PendingArgFlags[0];
10475     PendingLocs.clear();
10476     PendingArgFlags.clear();
10477     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
10478                                ArgFlags);
10479   }
10480 
10481   // Allocate to a register if possible, or else a stack slot.
10482   Register Reg;
10483   unsigned StoreSizeBytes = XLen / 8;
10484   Align StackAlign = Align(XLen / 8);
10485 
10486   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
10487     Reg = State.AllocateReg(ArgFPR16s);
10488   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
10489     Reg = State.AllocateReg(ArgFPR32s);
10490   else if (ValVT == MVT::f64 && !UseGPRForF64)
10491     Reg = State.AllocateReg(ArgFPR64s);
10492   else if (ValVT.isVector()) {
10493     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
10494     if (!Reg) {
10495       // For return values, the vector must be passed fully via registers or
10496       // via the stack.
10497       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
10498       // but we're using all of them.
10499       if (IsRet)
10500         return true;
10501       // Try using a GPR to pass the address
10502       if ((Reg = State.AllocateReg(ArgGPRs))) {
10503         LocVT = XLenVT;
10504         LocInfo = CCValAssign::Indirect;
10505       } else if (ValVT.isScalableVector()) {
10506         LocVT = XLenVT;
10507         LocInfo = CCValAssign::Indirect;
10508       } else {
10509         // Pass fixed-length vectors on the stack.
10510         LocVT = ValVT;
10511         StoreSizeBytes = ValVT.getStoreSize();
10512         // Align vectors to their element sizes, being careful for vXi1
10513         // vectors.
10514         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10515       }
10516     }
10517   } else {
10518     Reg = State.AllocateReg(ArgGPRs);
10519   }
10520 
10521   unsigned StackOffset =
10522       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
10523 
10524   // If we reach this point and PendingLocs is non-empty, we must be at the
10525   // end of a split argument that must be passed indirectly.
10526   if (!PendingLocs.empty()) {
10527     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
10528     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
10529 
10530     for (auto &It : PendingLocs) {
10531       if (Reg)
10532         It.convertToReg(Reg);
10533       else
10534         It.convertToMem(StackOffset);
10535       State.addLoc(It);
10536     }
10537     PendingLocs.clear();
10538     PendingArgFlags.clear();
10539     return false;
10540   }
10541 
10542   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
10543           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
10544          "Expected an XLenVT or vector types at this stage");
10545 
10546   if (Reg) {
10547     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10548     return false;
10549   }
10550 
10551   // When a floating-point value is passed on the stack, no bit-conversion is
10552   // needed.
10553   if (ValVT.isFloatingPoint()) {
10554     LocVT = ValVT;
10555     LocInfo = CCValAssign::Full;
10556   }
10557   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10558   return false;
10559 }
10560 
10561 template <typename ArgTy>
10562 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
10563   for (const auto &ArgIdx : enumerate(Args)) {
10564     MVT ArgVT = ArgIdx.value().VT;
10565     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
10566       return ArgIdx.index();
10567   }
10568   return None;
10569 }
10570 
10571 void RISCVTargetLowering::analyzeInputArgs(
10572     MachineFunction &MF, CCState &CCInfo,
10573     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
10574     RISCVCCAssignFn Fn) const {
10575   unsigned NumArgs = Ins.size();
10576   FunctionType *FType = MF.getFunction().getFunctionType();
10577 
10578   Optional<unsigned> FirstMaskArgument;
10579   if (Subtarget.hasVInstructions())
10580     FirstMaskArgument = preAssignMask(Ins);
10581 
10582   for (unsigned i = 0; i != NumArgs; ++i) {
10583     MVT ArgVT = Ins[i].VT;
10584     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
10585 
10586     Type *ArgTy = nullptr;
10587     if (IsRet)
10588       ArgTy = FType->getReturnType();
10589     else if (Ins[i].isOrigArg())
10590       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
10591 
10592     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10593     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10594            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
10595            FirstMaskArgument)) {
10596       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
10597                         << EVT(ArgVT).getEVTString() << '\n');
10598       llvm_unreachable(nullptr);
10599     }
10600   }
10601 }
10602 
10603 void RISCVTargetLowering::analyzeOutputArgs(
10604     MachineFunction &MF, CCState &CCInfo,
10605     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
10606     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
10607   unsigned NumArgs = Outs.size();
10608 
10609   Optional<unsigned> FirstMaskArgument;
10610   if (Subtarget.hasVInstructions())
10611     FirstMaskArgument = preAssignMask(Outs);
10612 
10613   for (unsigned i = 0; i != NumArgs; i++) {
10614     MVT ArgVT = Outs[i].VT;
10615     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10616     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
10617 
10618     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10619     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10620            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
10621            FirstMaskArgument)) {
10622       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
10623                         << EVT(ArgVT).getEVTString() << "\n");
10624       llvm_unreachable(nullptr);
10625     }
10626   }
10627 }
10628 
10629 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
10630 // values.
10631 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
10632                                    const CCValAssign &VA, const SDLoc &DL,
10633                                    const RISCVSubtarget &Subtarget) {
10634   switch (VA.getLocInfo()) {
10635   default:
10636     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10637   case CCValAssign::Full:
10638     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
10639       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
10640     break;
10641   case CCValAssign::BCvt:
10642     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10643       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
10644     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10645       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
10646     else
10647       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
10648     break;
10649   }
10650   return Val;
10651 }
10652 
10653 // The caller is responsible for loading the full value if the argument is
10654 // passed with CCValAssign::Indirect.
10655 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
10656                                 const CCValAssign &VA, const SDLoc &DL,
10657                                 const RISCVTargetLowering &TLI) {
10658   MachineFunction &MF = DAG.getMachineFunction();
10659   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10660   EVT LocVT = VA.getLocVT();
10661   SDValue Val;
10662   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
10663   Register VReg = RegInfo.createVirtualRegister(RC);
10664   RegInfo.addLiveIn(VA.getLocReg(), VReg);
10665   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
10666 
10667   if (VA.getLocInfo() == CCValAssign::Indirect)
10668     return Val;
10669 
10670   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
10671 }
10672 
10673 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
10674                                    const CCValAssign &VA, const SDLoc &DL,
10675                                    const RISCVSubtarget &Subtarget) {
10676   EVT LocVT = VA.getLocVT();
10677 
10678   switch (VA.getLocInfo()) {
10679   default:
10680     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10681   case CCValAssign::Full:
10682     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
10683       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
10684     break;
10685   case CCValAssign::BCvt:
10686     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10687       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
10688     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10689       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
10690     else
10691       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
10692     break;
10693   }
10694   return Val;
10695 }
10696 
10697 // The caller is responsible for loading the full value if the argument is
10698 // passed with CCValAssign::Indirect.
10699 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
10700                                 const CCValAssign &VA, const SDLoc &DL) {
10701   MachineFunction &MF = DAG.getMachineFunction();
10702   MachineFrameInfo &MFI = MF.getFrameInfo();
10703   EVT LocVT = VA.getLocVT();
10704   EVT ValVT = VA.getValVT();
10705   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
10706   if (ValVT.isScalableVector()) {
10707     // When the value is a scalable vector, we save the pointer which points to
10708     // the scalable vector value in the stack. The ValVT will be the pointer
10709     // type, instead of the scalable vector type.
10710     ValVT = LocVT;
10711   }
10712   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
10713                                  /*IsImmutable=*/true);
10714   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
10715   SDValue Val;
10716 
10717   ISD::LoadExtType ExtType;
10718   switch (VA.getLocInfo()) {
10719   default:
10720     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10721   case CCValAssign::Full:
10722   case CCValAssign::Indirect:
10723   case CCValAssign::BCvt:
10724     ExtType = ISD::NON_EXTLOAD;
10725     break;
10726   }
10727   Val = DAG.getExtLoad(
10728       ExtType, DL, LocVT, Chain, FIN,
10729       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
10730   return Val;
10731 }
10732 
10733 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
10734                                        const CCValAssign &VA, const SDLoc &DL) {
10735   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
10736          "Unexpected VA");
10737   MachineFunction &MF = DAG.getMachineFunction();
10738   MachineFrameInfo &MFI = MF.getFrameInfo();
10739   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10740 
10741   if (VA.isMemLoc()) {
10742     // f64 is passed on the stack.
10743     int FI =
10744         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
10745     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10746     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
10747                        MachinePointerInfo::getFixedStack(MF, FI));
10748   }
10749 
10750   assert(VA.isRegLoc() && "Expected register VA assignment");
10751 
10752   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10753   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
10754   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
10755   SDValue Hi;
10756   if (VA.getLocReg() == RISCV::X17) {
10757     // Second half of f64 is passed on the stack.
10758     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
10759     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10760     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10761                      MachinePointerInfo::getFixedStack(MF, FI));
10762   } else {
10763     // Second half of f64 is passed in another GPR.
10764     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10765     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10766     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10767   }
10768   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10769 }
10770 
10771 // FastCC has less than 1% performance improvement for some particular
10772 // benchmark. But theoretically, it may has benenfit for some cases.
10773 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10774                             unsigned ValNo, MVT ValVT, MVT LocVT,
10775                             CCValAssign::LocInfo LocInfo,
10776                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10777                             bool IsFixed, bool IsRet, Type *OrigTy,
10778                             const RISCVTargetLowering &TLI,
10779                             Optional<unsigned> FirstMaskArgument) {
10780 
10781   // X5 and X6 might be used for save-restore libcall.
10782   static const MCPhysReg GPRList[] = {
10783       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10784       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10785       RISCV::X29, RISCV::X30, RISCV::X31};
10786 
10787   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10788     if (unsigned Reg = State.AllocateReg(GPRList)) {
10789       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10790       return false;
10791     }
10792   }
10793 
10794   if (LocVT == MVT::f16) {
10795     static const MCPhysReg FPR16List[] = {
10796         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10797         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10798         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10799         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10800     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10801       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10802       return false;
10803     }
10804   }
10805 
10806   if (LocVT == MVT::f32) {
10807     static const MCPhysReg FPR32List[] = {
10808         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10809         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10810         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10811         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10812     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10813       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10814       return false;
10815     }
10816   }
10817 
10818   if (LocVT == MVT::f64) {
10819     static const MCPhysReg FPR64List[] = {
10820         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10821         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10822         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10823         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10824     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10825       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10826       return false;
10827     }
10828   }
10829 
10830   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10831     unsigned Offset4 = State.AllocateStack(4, Align(4));
10832     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10833     return false;
10834   }
10835 
10836   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10837     unsigned Offset5 = State.AllocateStack(8, Align(8));
10838     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10839     return false;
10840   }
10841 
10842   if (LocVT.isVector()) {
10843     if (unsigned Reg =
10844             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10845       // Fixed-length vectors are located in the corresponding scalable-vector
10846       // container types.
10847       if (ValVT.isFixedLengthVector())
10848         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10849       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10850     } else {
10851       // Try and pass the address via a "fast" GPR.
10852       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10853         LocInfo = CCValAssign::Indirect;
10854         LocVT = TLI.getSubtarget().getXLenVT();
10855         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10856       } else if (ValVT.isFixedLengthVector()) {
10857         auto StackAlign =
10858             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10859         unsigned StackOffset =
10860             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10861         State.addLoc(
10862             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10863       } else {
10864         // Can't pass scalable vectors on the stack.
10865         return true;
10866       }
10867     }
10868 
10869     return false;
10870   }
10871 
10872   return true; // CC didn't match.
10873 }
10874 
10875 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10876                          CCValAssign::LocInfo LocInfo,
10877                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10878 
10879   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10880     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10881     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10882     static const MCPhysReg GPRList[] = {
10883         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10884         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10885     if (unsigned Reg = State.AllocateReg(GPRList)) {
10886       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10887       return false;
10888     }
10889   }
10890 
10891   if (LocVT == MVT::f32) {
10892     // Pass in STG registers: F1, ..., F6
10893     //                        fs0 ... fs5
10894     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10895                                           RISCV::F18_F, RISCV::F19_F,
10896                                           RISCV::F20_F, RISCV::F21_F};
10897     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10898       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10899       return false;
10900     }
10901   }
10902 
10903   if (LocVT == MVT::f64) {
10904     // Pass in STG registers: D1, ..., D6
10905     //                        fs6 ... fs11
10906     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10907                                           RISCV::F24_D, RISCV::F25_D,
10908                                           RISCV::F26_D, RISCV::F27_D};
10909     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10910       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10911       return false;
10912     }
10913   }
10914 
10915   report_fatal_error("No registers left in GHC calling convention");
10916   return true;
10917 }
10918 
10919 // Transform physical registers into virtual registers.
10920 SDValue RISCVTargetLowering::LowerFormalArguments(
10921     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10922     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10923     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10924 
10925   MachineFunction &MF = DAG.getMachineFunction();
10926 
10927   switch (CallConv) {
10928   default:
10929     report_fatal_error("Unsupported calling convention");
10930   case CallingConv::C:
10931   case CallingConv::Fast:
10932     break;
10933   case CallingConv::GHC:
10934     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10935         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10936       report_fatal_error(
10937         "GHC calling convention requires the F and D instruction set extensions");
10938   }
10939 
10940   const Function &Func = MF.getFunction();
10941   if (Func.hasFnAttribute("interrupt")) {
10942     if (!Func.arg_empty())
10943       report_fatal_error(
10944         "Functions with the interrupt attribute cannot have arguments!");
10945 
10946     StringRef Kind =
10947       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10948 
10949     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10950       report_fatal_error(
10951         "Function interrupt attribute argument not supported!");
10952   }
10953 
10954   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10955   MVT XLenVT = Subtarget.getXLenVT();
10956   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10957   // Used with vargs to acumulate store chains.
10958   std::vector<SDValue> OutChains;
10959 
10960   // Assign locations to all of the incoming arguments.
10961   SmallVector<CCValAssign, 16> ArgLocs;
10962   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10963 
10964   if (CallConv == CallingConv::GHC)
10965     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10966   else
10967     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10968                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10969                                                    : CC_RISCV);
10970 
10971   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10972     CCValAssign &VA = ArgLocs[i];
10973     SDValue ArgValue;
10974     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10975     // case.
10976     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10977       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10978     else if (VA.isRegLoc())
10979       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10980     else
10981       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10982 
10983     if (VA.getLocInfo() == CCValAssign::Indirect) {
10984       // If the original argument was split and passed by reference (e.g. i128
10985       // on RV32), we need to load all parts of it here (using the same
10986       // address). Vectors may be partly split to registers and partly to the
10987       // stack, in which case the base address is partly offset and subsequent
10988       // stores are relative to that.
10989       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10990                                    MachinePointerInfo()));
10991       unsigned ArgIndex = Ins[i].OrigArgIndex;
10992       unsigned ArgPartOffset = Ins[i].PartOffset;
10993       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10994       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10995         CCValAssign &PartVA = ArgLocs[i + 1];
10996         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10997         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10998         if (PartVA.getValVT().isScalableVector())
10999           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
11000         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
11001         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
11002                                      MachinePointerInfo()));
11003         ++i;
11004       }
11005       continue;
11006     }
11007     InVals.push_back(ArgValue);
11008   }
11009 
11010   if (IsVarArg) {
11011     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
11012     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
11013     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
11014     MachineFrameInfo &MFI = MF.getFrameInfo();
11015     MachineRegisterInfo &RegInfo = MF.getRegInfo();
11016     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
11017 
11018     // Offset of the first variable argument from stack pointer, and size of
11019     // the vararg save area. For now, the varargs save area is either zero or
11020     // large enough to hold a0-a7.
11021     int VaArgOffset, VarArgsSaveSize;
11022 
11023     // If all registers are allocated, then all varargs must be passed on the
11024     // stack and we don't need to save any argregs.
11025     if (ArgRegs.size() == Idx) {
11026       VaArgOffset = CCInfo.getNextStackOffset();
11027       VarArgsSaveSize = 0;
11028     } else {
11029       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
11030       VaArgOffset = -VarArgsSaveSize;
11031     }
11032 
11033     // Record the frame index of the first variable argument
11034     // which is a value necessary to VASTART.
11035     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
11036     RVFI->setVarArgsFrameIndex(FI);
11037 
11038     // If saving an odd number of registers then create an extra stack slot to
11039     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
11040     // offsets to even-numbered registered remain 2*XLEN-aligned.
11041     if (Idx % 2) {
11042       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
11043       VarArgsSaveSize += XLenInBytes;
11044     }
11045 
11046     // Copy the integer registers that may have been used for passing varargs
11047     // to the vararg save area.
11048     for (unsigned I = Idx; I < ArgRegs.size();
11049          ++I, VaArgOffset += XLenInBytes) {
11050       const Register Reg = RegInfo.createVirtualRegister(RC);
11051       RegInfo.addLiveIn(ArgRegs[I], Reg);
11052       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
11053       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
11054       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
11055       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
11056                                    MachinePointerInfo::getFixedStack(MF, FI));
11057       cast<StoreSDNode>(Store.getNode())
11058           ->getMemOperand()
11059           ->setValue((Value *)nullptr);
11060       OutChains.push_back(Store);
11061     }
11062     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
11063   }
11064 
11065   // All stores are grouped in one node to allow the matching between
11066   // the size of Ins and InVals. This only happens for vararg functions.
11067   if (!OutChains.empty()) {
11068     OutChains.push_back(Chain);
11069     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
11070   }
11071 
11072   return Chain;
11073 }
11074 
11075 /// isEligibleForTailCallOptimization - Check whether the call is eligible
11076 /// for tail call optimization.
11077 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
11078 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
11079     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
11080     const SmallVector<CCValAssign, 16> &ArgLocs) const {
11081 
11082   auto &Callee = CLI.Callee;
11083   auto CalleeCC = CLI.CallConv;
11084   auto &Outs = CLI.Outs;
11085   auto &Caller = MF.getFunction();
11086   auto CallerCC = Caller.getCallingConv();
11087 
11088   // Exception-handling functions need a special set of instructions to
11089   // indicate a return to the hardware. Tail-calling another function would
11090   // probably break this.
11091   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
11092   // should be expanded as new function attributes are introduced.
11093   if (Caller.hasFnAttribute("interrupt"))
11094     return false;
11095 
11096   // Do not tail call opt if the stack is used to pass parameters.
11097   if (CCInfo.getNextStackOffset() != 0)
11098     return false;
11099 
11100   // Do not tail call opt if any parameters need to be passed indirectly.
11101   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
11102   // passed indirectly. So the address of the value will be passed in a
11103   // register, or if not available, then the address is put on the stack. In
11104   // order to pass indirectly, space on the stack often needs to be allocated
11105   // in order to store the value. In this case the CCInfo.getNextStackOffset()
11106   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
11107   // are passed CCValAssign::Indirect.
11108   for (auto &VA : ArgLocs)
11109     if (VA.getLocInfo() == CCValAssign::Indirect)
11110       return false;
11111 
11112   // Do not tail call opt if either caller or callee uses struct return
11113   // semantics.
11114   auto IsCallerStructRet = Caller.hasStructRetAttr();
11115   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
11116   if (IsCallerStructRet || IsCalleeStructRet)
11117     return false;
11118 
11119   // Externally-defined functions with weak linkage should not be
11120   // tail-called. The behaviour of branch instructions in this situation (as
11121   // used for tail calls) is implementation-defined, so we cannot rely on the
11122   // linker replacing the tail call with a return.
11123   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
11124     const GlobalValue *GV = G->getGlobal();
11125     if (GV->hasExternalWeakLinkage())
11126       return false;
11127   }
11128 
11129   // The callee has to preserve all registers the caller needs to preserve.
11130   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
11131   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
11132   if (CalleeCC != CallerCC) {
11133     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
11134     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
11135       return false;
11136   }
11137 
11138   // Byval parameters hand the function a pointer directly into the stack area
11139   // we want to reuse during a tail call. Working around this *is* possible
11140   // but less efficient and uglier in LowerCall.
11141   for (auto &Arg : Outs)
11142     if (Arg.Flags.isByVal())
11143       return false;
11144 
11145   return true;
11146 }
11147 
11148 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
11149   return DAG.getDataLayout().getPrefTypeAlign(
11150       VT.getTypeForEVT(*DAG.getContext()));
11151 }
11152 
11153 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
11154 // and output parameter nodes.
11155 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
11156                                        SmallVectorImpl<SDValue> &InVals) const {
11157   SelectionDAG &DAG = CLI.DAG;
11158   SDLoc &DL = CLI.DL;
11159   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
11160   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
11161   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
11162   SDValue Chain = CLI.Chain;
11163   SDValue Callee = CLI.Callee;
11164   bool &IsTailCall = CLI.IsTailCall;
11165   CallingConv::ID CallConv = CLI.CallConv;
11166   bool IsVarArg = CLI.IsVarArg;
11167   EVT PtrVT = getPointerTy(DAG.getDataLayout());
11168   MVT XLenVT = Subtarget.getXLenVT();
11169 
11170   MachineFunction &MF = DAG.getMachineFunction();
11171 
11172   // Analyze the operands of the call, assigning locations to each operand.
11173   SmallVector<CCValAssign, 16> ArgLocs;
11174   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
11175 
11176   if (CallConv == CallingConv::GHC)
11177     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
11178   else
11179     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
11180                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
11181                                                     : CC_RISCV);
11182 
11183   // Check if it's really possible to do a tail call.
11184   if (IsTailCall)
11185     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
11186 
11187   if (IsTailCall)
11188     ++NumTailCalls;
11189   else if (CLI.CB && CLI.CB->isMustTailCall())
11190     report_fatal_error("failed to perform tail call elimination on a call "
11191                        "site marked musttail");
11192 
11193   // Get a count of how many bytes are to be pushed on the stack.
11194   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
11195 
11196   // Create local copies for byval args
11197   SmallVector<SDValue, 8> ByValArgs;
11198   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
11199     ISD::ArgFlagsTy Flags = Outs[i].Flags;
11200     if (!Flags.isByVal())
11201       continue;
11202 
11203     SDValue Arg = OutVals[i];
11204     unsigned Size = Flags.getByValSize();
11205     Align Alignment = Flags.getNonZeroByValAlign();
11206 
11207     int FI =
11208         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
11209     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
11210     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
11211 
11212     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
11213                           /*IsVolatile=*/false,
11214                           /*AlwaysInline=*/false, IsTailCall,
11215                           MachinePointerInfo(), MachinePointerInfo());
11216     ByValArgs.push_back(FIPtr);
11217   }
11218 
11219   if (!IsTailCall)
11220     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
11221 
11222   // Copy argument values to their designated locations.
11223   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
11224   SmallVector<SDValue, 8> MemOpChains;
11225   SDValue StackPtr;
11226   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
11227     CCValAssign &VA = ArgLocs[i];
11228     SDValue ArgValue = OutVals[i];
11229     ISD::ArgFlagsTy Flags = Outs[i].Flags;
11230 
11231     // Handle passing f64 on RV32D with a soft float ABI as a special case.
11232     bool IsF64OnRV32DSoftABI =
11233         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
11234     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
11235       SDValue SplitF64 = DAG.getNode(
11236           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
11237       SDValue Lo = SplitF64.getValue(0);
11238       SDValue Hi = SplitF64.getValue(1);
11239 
11240       Register RegLo = VA.getLocReg();
11241       RegsToPass.push_back(std::make_pair(RegLo, Lo));
11242 
11243       if (RegLo == RISCV::X17) {
11244         // Second half of f64 is passed on the stack.
11245         // Work out the address of the stack slot.
11246         if (!StackPtr.getNode())
11247           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
11248         // Emit the store.
11249         MemOpChains.push_back(
11250             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
11251       } else {
11252         // Second half of f64 is passed in another GPR.
11253         assert(RegLo < RISCV::X31 && "Invalid register pair");
11254         Register RegHigh = RegLo + 1;
11255         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
11256       }
11257       continue;
11258     }
11259 
11260     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
11261     // as any other MemLoc.
11262 
11263     // Promote the value if needed.
11264     // For now, only handle fully promoted and indirect arguments.
11265     if (VA.getLocInfo() == CCValAssign::Indirect) {
11266       // Store the argument in a stack slot and pass its address.
11267       Align StackAlign =
11268           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
11269                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
11270       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
11271       // If the original argument was split (e.g. i128), we need
11272       // to store the required parts of it here (and pass just one address).
11273       // Vectors may be partly split to registers and partly to the stack, in
11274       // which case the base address is partly offset and subsequent stores are
11275       // relative to that.
11276       unsigned ArgIndex = Outs[i].OrigArgIndex;
11277       unsigned ArgPartOffset = Outs[i].PartOffset;
11278       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
11279       // Calculate the total size to store. We don't have access to what we're
11280       // actually storing other than performing the loop and collecting the
11281       // info.
11282       SmallVector<std::pair<SDValue, SDValue>> Parts;
11283       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
11284         SDValue PartValue = OutVals[i + 1];
11285         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
11286         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
11287         EVT PartVT = PartValue.getValueType();
11288         if (PartVT.isScalableVector())
11289           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
11290         StoredSize += PartVT.getStoreSize();
11291         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
11292         Parts.push_back(std::make_pair(PartValue, Offset));
11293         ++i;
11294       }
11295       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
11296       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
11297       MemOpChains.push_back(
11298           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
11299                        MachinePointerInfo::getFixedStack(MF, FI)));
11300       for (const auto &Part : Parts) {
11301         SDValue PartValue = Part.first;
11302         SDValue PartOffset = Part.second;
11303         SDValue Address =
11304             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
11305         MemOpChains.push_back(
11306             DAG.getStore(Chain, DL, PartValue, Address,
11307                          MachinePointerInfo::getFixedStack(MF, FI)));
11308       }
11309       ArgValue = SpillSlot;
11310     } else {
11311       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
11312     }
11313 
11314     // Use local copy if it is a byval arg.
11315     if (Flags.isByVal())
11316       ArgValue = ByValArgs[j++];
11317 
11318     if (VA.isRegLoc()) {
11319       // Queue up the argument copies and emit them at the end.
11320       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
11321     } else {
11322       assert(VA.isMemLoc() && "Argument not register or memory");
11323       assert(!IsTailCall && "Tail call not allowed if stack is used "
11324                             "for passing parameters");
11325 
11326       // Work out the address of the stack slot.
11327       if (!StackPtr.getNode())
11328         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
11329       SDValue Address =
11330           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
11331                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
11332 
11333       // Emit the store.
11334       MemOpChains.push_back(
11335           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
11336     }
11337   }
11338 
11339   // Join the stores, which are independent of one another.
11340   if (!MemOpChains.empty())
11341     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
11342 
11343   SDValue Glue;
11344 
11345   // Build a sequence of copy-to-reg nodes, chained and glued together.
11346   for (auto &Reg : RegsToPass) {
11347     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
11348     Glue = Chain.getValue(1);
11349   }
11350 
11351   // Validate that none of the argument registers have been marked as
11352   // reserved, if so report an error. Do the same for the return address if this
11353   // is not a tailcall.
11354   validateCCReservedRegs(RegsToPass, MF);
11355   if (!IsTailCall &&
11356       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
11357     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11358         MF.getFunction(),
11359         "Return address register required, but has been reserved."});
11360 
11361   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
11362   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
11363   // split it and then direct call can be matched by PseudoCALL.
11364   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
11365     const GlobalValue *GV = S->getGlobal();
11366 
11367     unsigned OpFlags = RISCVII::MO_CALL;
11368     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
11369       OpFlags = RISCVII::MO_PLT;
11370 
11371     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
11372   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
11373     unsigned OpFlags = RISCVII::MO_CALL;
11374 
11375     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
11376                                                  nullptr))
11377       OpFlags = RISCVII::MO_PLT;
11378 
11379     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
11380   }
11381 
11382   // The first call operand is the chain and the second is the target address.
11383   SmallVector<SDValue, 8> Ops;
11384   Ops.push_back(Chain);
11385   Ops.push_back(Callee);
11386 
11387   // Add argument registers to the end of the list so that they are
11388   // known live into the call.
11389   for (auto &Reg : RegsToPass)
11390     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
11391 
11392   if (!IsTailCall) {
11393     // Add a register mask operand representing the call-preserved registers.
11394     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
11395     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
11396     assert(Mask && "Missing call preserved mask for calling convention");
11397     Ops.push_back(DAG.getRegisterMask(Mask));
11398   }
11399 
11400   // Glue the call to the argument copies, if any.
11401   if (Glue.getNode())
11402     Ops.push_back(Glue);
11403 
11404   // Emit the call.
11405   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11406 
11407   if (IsTailCall) {
11408     MF.getFrameInfo().setHasTailCall();
11409     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
11410   }
11411 
11412   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
11413   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
11414   Glue = Chain.getValue(1);
11415 
11416   // Mark the end of the call, which is glued to the call itself.
11417   Chain = DAG.getCALLSEQ_END(Chain,
11418                              DAG.getConstant(NumBytes, DL, PtrVT, true),
11419                              DAG.getConstant(0, DL, PtrVT, true),
11420                              Glue, DL);
11421   Glue = Chain.getValue(1);
11422 
11423   // Assign locations to each value returned by this call.
11424   SmallVector<CCValAssign, 16> RVLocs;
11425   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
11426   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
11427 
11428   // Copy all of the result registers out of their specified physreg.
11429   for (auto &VA : RVLocs) {
11430     // Copy the value out
11431     SDValue RetValue =
11432         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
11433     // Glue the RetValue to the end of the call sequence
11434     Chain = RetValue.getValue(1);
11435     Glue = RetValue.getValue(2);
11436 
11437     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11438       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
11439       SDValue RetValue2 =
11440           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
11441       Chain = RetValue2.getValue(1);
11442       Glue = RetValue2.getValue(2);
11443       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
11444                              RetValue2);
11445     }
11446 
11447     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
11448 
11449     InVals.push_back(RetValue);
11450   }
11451 
11452   return Chain;
11453 }
11454 
11455 bool RISCVTargetLowering::CanLowerReturn(
11456     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
11457     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
11458   SmallVector<CCValAssign, 16> RVLocs;
11459   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
11460 
11461   Optional<unsigned> FirstMaskArgument;
11462   if (Subtarget.hasVInstructions())
11463     FirstMaskArgument = preAssignMask(Outs);
11464 
11465   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
11466     MVT VT = Outs[i].VT;
11467     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
11468     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
11469     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
11470                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
11471                  *this, FirstMaskArgument))
11472       return false;
11473   }
11474   return true;
11475 }
11476 
11477 SDValue
11478 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
11479                                  bool IsVarArg,
11480                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
11481                                  const SmallVectorImpl<SDValue> &OutVals,
11482                                  const SDLoc &DL, SelectionDAG &DAG) const {
11483   const MachineFunction &MF = DAG.getMachineFunction();
11484   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11485 
11486   // Stores the assignment of the return value to a location.
11487   SmallVector<CCValAssign, 16> RVLocs;
11488 
11489   // Info about the registers and stack slot.
11490   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
11491                  *DAG.getContext());
11492 
11493   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
11494                     nullptr, CC_RISCV);
11495 
11496   if (CallConv == CallingConv::GHC && !RVLocs.empty())
11497     report_fatal_error("GHC functions return void only");
11498 
11499   SDValue Glue;
11500   SmallVector<SDValue, 4> RetOps(1, Chain);
11501 
11502   // Copy the result values into the output registers.
11503   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
11504     SDValue Val = OutVals[i];
11505     CCValAssign &VA = RVLocs[i];
11506     assert(VA.isRegLoc() && "Can only return in registers!");
11507 
11508     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
11509       // Handle returning f64 on RV32D with a soft float ABI.
11510       assert(VA.isRegLoc() && "Expected return via registers");
11511       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
11512                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
11513       SDValue Lo = SplitF64.getValue(0);
11514       SDValue Hi = SplitF64.getValue(1);
11515       Register RegLo = VA.getLocReg();
11516       assert(RegLo < RISCV::X31 && "Invalid register pair");
11517       Register RegHi = RegLo + 1;
11518 
11519       if (STI.isRegisterReservedByUser(RegLo) ||
11520           STI.isRegisterReservedByUser(RegHi))
11521         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11522             MF.getFunction(),
11523             "Return value register required, but has been reserved."});
11524 
11525       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
11526       Glue = Chain.getValue(1);
11527       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
11528       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
11529       Glue = Chain.getValue(1);
11530       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
11531     } else {
11532       // Handle a 'normal' return.
11533       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
11534       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
11535 
11536       if (STI.isRegisterReservedByUser(VA.getLocReg()))
11537         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
11538             MF.getFunction(),
11539             "Return value register required, but has been reserved."});
11540 
11541       // Guarantee that all emitted copies are stuck together.
11542       Glue = Chain.getValue(1);
11543       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
11544     }
11545   }
11546 
11547   RetOps[0] = Chain; // Update chain.
11548 
11549   // Add the glue node if we have it.
11550   if (Glue.getNode()) {
11551     RetOps.push_back(Glue);
11552   }
11553 
11554   unsigned RetOpc = RISCVISD::RET_FLAG;
11555   // Interrupt service routines use different return instructions.
11556   const Function &Func = DAG.getMachineFunction().getFunction();
11557   if (Func.hasFnAttribute("interrupt")) {
11558     if (!Func.getReturnType()->isVoidTy())
11559       report_fatal_error(
11560           "Functions with the interrupt attribute must have void return type!");
11561 
11562     MachineFunction &MF = DAG.getMachineFunction();
11563     StringRef Kind =
11564       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
11565 
11566     if (Kind == "user")
11567       RetOpc = RISCVISD::URET_FLAG;
11568     else if (Kind == "supervisor")
11569       RetOpc = RISCVISD::SRET_FLAG;
11570     else
11571       RetOpc = RISCVISD::MRET_FLAG;
11572   }
11573 
11574   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
11575 }
11576 
11577 void RISCVTargetLowering::validateCCReservedRegs(
11578     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
11579     MachineFunction &MF) const {
11580   const Function &F = MF.getFunction();
11581   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
11582 
11583   if (llvm::any_of(Regs, [&STI](auto Reg) {
11584         return STI.isRegisterReservedByUser(Reg.first);
11585       }))
11586     F.getContext().diagnose(DiagnosticInfoUnsupported{
11587         F, "Argument register required, but has been reserved."});
11588 }
11589 
11590 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
11591   return CI->isTailCall();
11592 }
11593 
11594 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
11595 #define NODE_NAME_CASE(NODE)                                                   \
11596   case RISCVISD::NODE:                                                         \
11597     return "RISCVISD::" #NODE;
11598   // clang-format off
11599   switch ((RISCVISD::NodeType)Opcode) {
11600   case RISCVISD::FIRST_NUMBER:
11601     break;
11602   NODE_NAME_CASE(RET_FLAG)
11603   NODE_NAME_CASE(URET_FLAG)
11604   NODE_NAME_CASE(SRET_FLAG)
11605   NODE_NAME_CASE(MRET_FLAG)
11606   NODE_NAME_CASE(CALL)
11607   NODE_NAME_CASE(SELECT_CC)
11608   NODE_NAME_CASE(BR_CC)
11609   NODE_NAME_CASE(BuildPairF64)
11610   NODE_NAME_CASE(SplitF64)
11611   NODE_NAME_CASE(TAIL)
11612   NODE_NAME_CASE(ADD_LO)
11613   NODE_NAME_CASE(HI)
11614   NODE_NAME_CASE(LLA)
11615   NODE_NAME_CASE(ADD_TPREL)
11616   NODE_NAME_CASE(LA)
11617   NODE_NAME_CASE(LA_TLS_IE)
11618   NODE_NAME_CASE(LA_TLS_GD)
11619   NODE_NAME_CASE(MULHSU)
11620   NODE_NAME_CASE(SLLW)
11621   NODE_NAME_CASE(SRAW)
11622   NODE_NAME_CASE(SRLW)
11623   NODE_NAME_CASE(DIVW)
11624   NODE_NAME_CASE(DIVUW)
11625   NODE_NAME_CASE(REMUW)
11626   NODE_NAME_CASE(ROLW)
11627   NODE_NAME_CASE(RORW)
11628   NODE_NAME_CASE(CLZW)
11629   NODE_NAME_CASE(CTZW)
11630   NODE_NAME_CASE(FSLW)
11631   NODE_NAME_CASE(FSRW)
11632   NODE_NAME_CASE(FSL)
11633   NODE_NAME_CASE(FSR)
11634   NODE_NAME_CASE(FMV_H_X)
11635   NODE_NAME_CASE(FMV_X_ANYEXTH)
11636   NODE_NAME_CASE(FMV_X_SIGNEXTH)
11637   NODE_NAME_CASE(FMV_W_X_RV64)
11638   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
11639   NODE_NAME_CASE(FCVT_X)
11640   NODE_NAME_CASE(FCVT_XU)
11641   NODE_NAME_CASE(FCVT_W_RV64)
11642   NODE_NAME_CASE(FCVT_WU_RV64)
11643   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
11644   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
11645   NODE_NAME_CASE(READ_CYCLE_WIDE)
11646   NODE_NAME_CASE(GREV)
11647   NODE_NAME_CASE(GREVW)
11648   NODE_NAME_CASE(GORC)
11649   NODE_NAME_CASE(GORCW)
11650   NODE_NAME_CASE(SHFL)
11651   NODE_NAME_CASE(SHFLW)
11652   NODE_NAME_CASE(UNSHFL)
11653   NODE_NAME_CASE(UNSHFLW)
11654   NODE_NAME_CASE(BFP)
11655   NODE_NAME_CASE(BFPW)
11656   NODE_NAME_CASE(BCOMPRESS)
11657   NODE_NAME_CASE(BCOMPRESSW)
11658   NODE_NAME_CASE(BDECOMPRESS)
11659   NODE_NAME_CASE(BDECOMPRESSW)
11660   NODE_NAME_CASE(VMV_V_X_VL)
11661   NODE_NAME_CASE(VFMV_V_F_VL)
11662   NODE_NAME_CASE(VMV_X_S)
11663   NODE_NAME_CASE(VMV_S_X_VL)
11664   NODE_NAME_CASE(VFMV_S_F_VL)
11665   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
11666   NODE_NAME_CASE(READ_VLENB)
11667   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
11668   NODE_NAME_CASE(VSLIDEUP_VL)
11669   NODE_NAME_CASE(VSLIDE1UP_VL)
11670   NODE_NAME_CASE(VSLIDEDOWN_VL)
11671   NODE_NAME_CASE(VSLIDE1DOWN_VL)
11672   NODE_NAME_CASE(VID_VL)
11673   NODE_NAME_CASE(VFNCVT_ROD_VL)
11674   NODE_NAME_CASE(VECREDUCE_ADD_VL)
11675   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
11676   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
11677   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
11678   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
11679   NODE_NAME_CASE(VECREDUCE_AND_VL)
11680   NODE_NAME_CASE(VECREDUCE_OR_VL)
11681   NODE_NAME_CASE(VECREDUCE_XOR_VL)
11682   NODE_NAME_CASE(VECREDUCE_FADD_VL)
11683   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
11684   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
11685   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
11686   NODE_NAME_CASE(ADD_VL)
11687   NODE_NAME_CASE(AND_VL)
11688   NODE_NAME_CASE(MUL_VL)
11689   NODE_NAME_CASE(OR_VL)
11690   NODE_NAME_CASE(SDIV_VL)
11691   NODE_NAME_CASE(SHL_VL)
11692   NODE_NAME_CASE(SREM_VL)
11693   NODE_NAME_CASE(SRA_VL)
11694   NODE_NAME_CASE(SRL_VL)
11695   NODE_NAME_CASE(SUB_VL)
11696   NODE_NAME_CASE(UDIV_VL)
11697   NODE_NAME_CASE(UREM_VL)
11698   NODE_NAME_CASE(XOR_VL)
11699   NODE_NAME_CASE(SADDSAT_VL)
11700   NODE_NAME_CASE(UADDSAT_VL)
11701   NODE_NAME_CASE(SSUBSAT_VL)
11702   NODE_NAME_CASE(USUBSAT_VL)
11703   NODE_NAME_CASE(FADD_VL)
11704   NODE_NAME_CASE(FSUB_VL)
11705   NODE_NAME_CASE(FMUL_VL)
11706   NODE_NAME_CASE(FDIV_VL)
11707   NODE_NAME_CASE(FNEG_VL)
11708   NODE_NAME_CASE(FABS_VL)
11709   NODE_NAME_CASE(FSQRT_VL)
11710   NODE_NAME_CASE(VFMADD_VL)
11711   NODE_NAME_CASE(VFNMADD_VL)
11712   NODE_NAME_CASE(VFMSUB_VL)
11713   NODE_NAME_CASE(VFNMSUB_VL)
11714   NODE_NAME_CASE(FCOPYSIGN_VL)
11715   NODE_NAME_CASE(SMIN_VL)
11716   NODE_NAME_CASE(SMAX_VL)
11717   NODE_NAME_CASE(UMIN_VL)
11718   NODE_NAME_CASE(UMAX_VL)
11719   NODE_NAME_CASE(FMINNUM_VL)
11720   NODE_NAME_CASE(FMAXNUM_VL)
11721   NODE_NAME_CASE(MULHS_VL)
11722   NODE_NAME_CASE(MULHU_VL)
11723   NODE_NAME_CASE(FP_TO_SINT_VL)
11724   NODE_NAME_CASE(FP_TO_UINT_VL)
11725   NODE_NAME_CASE(SINT_TO_FP_VL)
11726   NODE_NAME_CASE(UINT_TO_FP_VL)
11727   NODE_NAME_CASE(FP_EXTEND_VL)
11728   NODE_NAME_CASE(FP_ROUND_VL)
11729   NODE_NAME_CASE(VWMUL_VL)
11730   NODE_NAME_CASE(VWMULU_VL)
11731   NODE_NAME_CASE(VWMULSU_VL)
11732   NODE_NAME_CASE(VWADD_VL)
11733   NODE_NAME_CASE(VWADDU_VL)
11734   NODE_NAME_CASE(VWSUB_VL)
11735   NODE_NAME_CASE(VWSUBU_VL)
11736   NODE_NAME_CASE(VWADD_W_VL)
11737   NODE_NAME_CASE(VWADDU_W_VL)
11738   NODE_NAME_CASE(VWSUB_W_VL)
11739   NODE_NAME_CASE(VWSUBU_W_VL)
11740   NODE_NAME_CASE(SETCC_VL)
11741   NODE_NAME_CASE(VSELECT_VL)
11742   NODE_NAME_CASE(VP_MERGE_VL)
11743   NODE_NAME_CASE(VMAND_VL)
11744   NODE_NAME_CASE(VMOR_VL)
11745   NODE_NAME_CASE(VMXOR_VL)
11746   NODE_NAME_CASE(VMCLR_VL)
11747   NODE_NAME_CASE(VMSET_VL)
11748   NODE_NAME_CASE(VRGATHER_VX_VL)
11749   NODE_NAME_CASE(VRGATHER_VV_VL)
11750   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
11751   NODE_NAME_CASE(VSEXT_VL)
11752   NODE_NAME_CASE(VZEXT_VL)
11753   NODE_NAME_CASE(VCPOP_VL)
11754   NODE_NAME_CASE(READ_CSR)
11755   NODE_NAME_CASE(WRITE_CSR)
11756   NODE_NAME_CASE(SWAP_CSR)
11757   }
11758   // clang-format on
11759   return nullptr;
11760 #undef NODE_NAME_CASE
11761 }
11762 
11763 /// getConstraintType - Given a constraint letter, return the type of
11764 /// constraint it is for this target.
11765 RISCVTargetLowering::ConstraintType
11766 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
11767   if (Constraint.size() == 1) {
11768     switch (Constraint[0]) {
11769     default:
11770       break;
11771     case 'f':
11772       return C_RegisterClass;
11773     case 'I':
11774     case 'J':
11775     case 'K':
11776       return C_Immediate;
11777     case 'A':
11778       return C_Memory;
11779     case 'S': // A symbolic address
11780       return C_Other;
11781     }
11782   } else {
11783     if (Constraint == "vr" || Constraint == "vm")
11784       return C_RegisterClass;
11785   }
11786   return TargetLowering::getConstraintType(Constraint);
11787 }
11788 
11789 std::pair<unsigned, const TargetRegisterClass *>
11790 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11791                                                   StringRef Constraint,
11792                                                   MVT VT) const {
11793   // First, see if this is a constraint that directly corresponds to a
11794   // RISCV register class.
11795   if (Constraint.size() == 1) {
11796     switch (Constraint[0]) {
11797     case 'r':
11798       // TODO: Support fixed vectors up to XLen for P extension?
11799       if (VT.isVector())
11800         break;
11801       return std::make_pair(0U, &RISCV::GPRRegClass);
11802     case 'f':
11803       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11804         return std::make_pair(0U, &RISCV::FPR16RegClass);
11805       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11806         return std::make_pair(0U, &RISCV::FPR32RegClass);
11807       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11808         return std::make_pair(0U, &RISCV::FPR64RegClass);
11809       break;
11810     default:
11811       break;
11812     }
11813   } else if (Constraint == "vr") {
11814     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11815                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11816       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11817         return std::make_pair(0U, RC);
11818     }
11819   } else if (Constraint == "vm") {
11820     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11821       return std::make_pair(0U, &RISCV::VMV0RegClass);
11822   }
11823 
11824   // Clang will correctly decode the usage of register name aliases into their
11825   // official names. However, other frontends like `rustc` do not. This allows
11826   // users of these frontends to use the ABI names for registers in LLVM-style
11827   // register constraints.
11828   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11829                                .Case("{zero}", RISCV::X0)
11830                                .Case("{ra}", RISCV::X1)
11831                                .Case("{sp}", RISCV::X2)
11832                                .Case("{gp}", RISCV::X3)
11833                                .Case("{tp}", RISCV::X4)
11834                                .Case("{t0}", RISCV::X5)
11835                                .Case("{t1}", RISCV::X6)
11836                                .Case("{t2}", RISCV::X7)
11837                                .Cases("{s0}", "{fp}", RISCV::X8)
11838                                .Case("{s1}", RISCV::X9)
11839                                .Case("{a0}", RISCV::X10)
11840                                .Case("{a1}", RISCV::X11)
11841                                .Case("{a2}", RISCV::X12)
11842                                .Case("{a3}", RISCV::X13)
11843                                .Case("{a4}", RISCV::X14)
11844                                .Case("{a5}", RISCV::X15)
11845                                .Case("{a6}", RISCV::X16)
11846                                .Case("{a7}", RISCV::X17)
11847                                .Case("{s2}", RISCV::X18)
11848                                .Case("{s3}", RISCV::X19)
11849                                .Case("{s4}", RISCV::X20)
11850                                .Case("{s5}", RISCV::X21)
11851                                .Case("{s6}", RISCV::X22)
11852                                .Case("{s7}", RISCV::X23)
11853                                .Case("{s8}", RISCV::X24)
11854                                .Case("{s9}", RISCV::X25)
11855                                .Case("{s10}", RISCV::X26)
11856                                .Case("{s11}", RISCV::X27)
11857                                .Case("{t3}", RISCV::X28)
11858                                .Case("{t4}", RISCV::X29)
11859                                .Case("{t5}", RISCV::X30)
11860                                .Case("{t6}", RISCV::X31)
11861                                .Default(RISCV::NoRegister);
11862   if (XRegFromAlias != RISCV::NoRegister)
11863     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11864 
11865   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11866   // TableGen record rather than the AsmName to choose registers for InlineAsm
11867   // constraints, plus we want to match those names to the widest floating point
11868   // register type available, manually select floating point registers here.
11869   //
11870   // The second case is the ABI name of the register, so that frontends can also
11871   // use the ABI names in register constraint lists.
11872   if (Subtarget.hasStdExtF()) {
11873     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11874                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11875                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11876                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11877                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11878                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11879                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11880                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11881                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11882                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11883                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11884                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11885                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11886                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11887                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11888                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11889                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11890                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11891                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11892                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11893                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11894                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11895                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11896                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11897                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11898                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11899                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11900                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11901                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11902                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11903                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11904                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11905                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11906                         .Default(RISCV::NoRegister);
11907     if (FReg != RISCV::NoRegister) {
11908       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11909       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11910         unsigned RegNo = FReg - RISCV::F0_F;
11911         unsigned DReg = RISCV::F0_D + RegNo;
11912         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11913       }
11914       if (VT == MVT::f32 || VT == MVT::Other)
11915         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11916       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11917         unsigned RegNo = FReg - RISCV::F0_F;
11918         unsigned HReg = RISCV::F0_H + RegNo;
11919         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11920       }
11921     }
11922   }
11923 
11924   if (Subtarget.hasVInstructions()) {
11925     Register VReg = StringSwitch<Register>(Constraint.lower())
11926                         .Case("{v0}", RISCV::V0)
11927                         .Case("{v1}", RISCV::V1)
11928                         .Case("{v2}", RISCV::V2)
11929                         .Case("{v3}", RISCV::V3)
11930                         .Case("{v4}", RISCV::V4)
11931                         .Case("{v5}", RISCV::V5)
11932                         .Case("{v6}", RISCV::V6)
11933                         .Case("{v7}", RISCV::V7)
11934                         .Case("{v8}", RISCV::V8)
11935                         .Case("{v9}", RISCV::V9)
11936                         .Case("{v10}", RISCV::V10)
11937                         .Case("{v11}", RISCV::V11)
11938                         .Case("{v12}", RISCV::V12)
11939                         .Case("{v13}", RISCV::V13)
11940                         .Case("{v14}", RISCV::V14)
11941                         .Case("{v15}", RISCV::V15)
11942                         .Case("{v16}", RISCV::V16)
11943                         .Case("{v17}", RISCV::V17)
11944                         .Case("{v18}", RISCV::V18)
11945                         .Case("{v19}", RISCV::V19)
11946                         .Case("{v20}", RISCV::V20)
11947                         .Case("{v21}", RISCV::V21)
11948                         .Case("{v22}", RISCV::V22)
11949                         .Case("{v23}", RISCV::V23)
11950                         .Case("{v24}", RISCV::V24)
11951                         .Case("{v25}", RISCV::V25)
11952                         .Case("{v26}", RISCV::V26)
11953                         .Case("{v27}", RISCV::V27)
11954                         .Case("{v28}", RISCV::V28)
11955                         .Case("{v29}", RISCV::V29)
11956                         .Case("{v30}", RISCV::V30)
11957                         .Case("{v31}", RISCV::V31)
11958                         .Default(RISCV::NoRegister);
11959     if (VReg != RISCV::NoRegister) {
11960       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11961         return std::make_pair(VReg, &RISCV::VMRegClass);
11962       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11963         return std::make_pair(VReg, &RISCV::VRRegClass);
11964       for (const auto *RC :
11965            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11966         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11967           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11968           return std::make_pair(VReg, RC);
11969         }
11970       }
11971     }
11972   }
11973 
11974   std::pair<Register, const TargetRegisterClass *> Res =
11975       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11976 
11977   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11978   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11979   // Subtarget into account.
11980   if (Res.second == &RISCV::GPRF16RegClass ||
11981       Res.second == &RISCV::GPRF32RegClass ||
11982       Res.second == &RISCV::GPRF64RegClass)
11983     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11984 
11985   return Res;
11986 }
11987 
11988 unsigned
11989 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11990   // Currently only support length 1 constraints.
11991   if (ConstraintCode.size() == 1) {
11992     switch (ConstraintCode[0]) {
11993     case 'A':
11994       return InlineAsm::Constraint_A;
11995     default:
11996       break;
11997     }
11998   }
11999 
12000   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
12001 }
12002 
12003 void RISCVTargetLowering::LowerAsmOperandForConstraint(
12004     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
12005     SelectionDAG &DAG) const {
12006   // Currently only support length 1 constraints.
12007   if (Constraint.length() == 1) {
12008     switch (Constraint[0]) {
12009     case 'I':
12010       // Validate & create a 12-bit signed immediate operand.
12011       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
12012         uint64_t CVal = C->getSExtValue();
12013         if (isInt<12>(CVal))
12014           Ops.push_back(
12015               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
12016       }
12017       return;
12018     case 'J':
12019       // Validate & create an integer zero operand.
12020       if (auto *C = dyn_cast<ConstantSDNode>(Op))
12021         if (C->getZExtValue() == 0)
12022           Ops.push_back(
12023               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
12024       return;
12025     case 'K':
12026       // Validate & create a 5-bit unsigned immediate operand.
12027       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
12028         uint64_t CVal = C->getZExtValue();
12029         if (isUInt<5>(CVal))
12030           Ops.push_back(
12031               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
12032       }
12033       return;
12034     case 'S':
12035       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
12036         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
12037                                                  GA->getValueType(0)));
12038       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
12039         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
12040                                                 BA->getValueType(0)));
12041       }
12042       return;
12043     default:
12044       break;
12045     }
12046   }
12047   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12048 }
12049 
12050 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
12051                                                    Instruction *Inst,
12052                                                    AtomicOrdering Ord) const {
12053   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
12054     return Builder.CreateFence(Ord);
12055   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
12056     return Builder.CreateFence(AtomicOrdering::Release);
12057   return nullptr;
12058 }
12059 
12060 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
12061                                                     Instruction *Inst,
12062                                                     AtomicOrdering Ord) const {
12063   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
12064     return Builder.CreateFence(AtomicOrdering::Acquire);
12065   return nullptr;
12066 }
12067 
12068 TargetLowering::AtomicExpansionKind
12069 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
12070   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
12071   // point operations can't be used in an lr/sc sequence without breaking the
12072   // forward-progress guarantee.
12073   if (AI->isFloatingPointOperation())
12074     return AtomicExpansionKind::CmpXChg;
12075 
12076   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
12077   if (Size == 8 || Size == 16)
12078     return AtomicExpansionKind::MaskedIntrinsic;
12079   return AtomicExpansionKind::None;
12080 }
12081 
12082 static Intrinsic::ID
12083 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
12084   if (XLen == 32) {
12085     switch (BinOp) {
12086     default:
12087       llvm_unreachable("Unexpected AtomicRMW BinOp");
12088     case AtomicRMWInst::Xchg:
12089       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
12090     case AtomicRMWInst::Add:
12091       return Intrinsic::riscv_masked_atomicrmw_add_i32;
12092     case AtomicRMWInst::Sub:
12093       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
12094     case AtomicRMWInst::Nand:
12095       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
12096     case AtomicRMWInst::Max:
12097       return Intrinsic::riscv_masked_atomicrmw_max_i32;
12098     case AtomicRMWInst::Min:
12099       return Intrinsic::riscv_masked_atomicrmw_min_i32;
12100     case AtomicRMWInst::UMax:
12101       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
12102     case AtomicRMWInst::UMin:
12103       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
12104     }
12105   }
12106 
12107   if (XLen == 64) {
12108     switch (BinOp) {
12109     default:
12110       llvm_unreachable("Unexpected AtomicRMW BinOp");
12111     case AtomicRMWInst::Xchg:
12112       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
12113     case AtomicRMWInst::Add:
12114       return Intrinsic::riscv_masked_atomicrmw_add_i64;
12115     case AtomicRMWInst::Sub:
12116       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
12117     case AtomicRMWInst::Nand:
12118       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
12119     case AtomicRMWInst::Max:
12120       return Intrinsic::riscv_masked_atomicrmw_max_i64;
12121     case AtomicRMWInst::Min:
12122       return Intrinsic::riscv_masked_atomicrmw_min_i64;
12123     case AtomicRMWInst::UMax:
12124       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
12125     case AtomicRMWInst::UMin:
12126       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
12127     }
12128   }
12129 
12130   llvm_unreachable("Unexpected XLen\n");
12131 }
12132 
12133 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
12134     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
12135     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
12136   unsigned XLen = Subtarget.getXLen();
12137   Value *Ordering =
12138       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
12139   Type *Tys[] = {AlignedAddr->getType()};
12140   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
12141       AI->getModule(),
12142       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
12143 
12144   if (XLen == 64) {
12145     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
12146     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
12147     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
12148   }
12149 
12150   Value *Result;
12151 
12152   // Must pass the shift amount needed to sign extend the loaded value prior
12153   // to performing a signed comparison for min/max. ShiftAmt is the number of
12154   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
12155   // is the number of bits to left+right shift the value in order to
12156   // sign-extend.
12157   if (AI->getOperation() == AtomicRMWInst::Min ||
12158       AI->getOperation() == AtomicRMWInst::Max) {
12159     const DataLayout &DL = AI->getModule()->getDataLayout();
12160     unsigned ValWidth =
12161         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
12162     Value *SextShamt =
12163         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
12164     Result = Builder.CreateCall(LrwOpScwLoop,
12165                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
12166   } else {
12167     Result =
12168         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
12169   }
12170 
12171   if (XLen == 64)
12172     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
12173   return Result;
12174 }
12175 
12176 TargetLowering::AtomicExpansionKind
12177 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
12178     AtomicCmpXchgInst *CI) const {
12179   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
12180   if (Size == 8 || Size == 16)
12181     return AtomicExpansionKind::MaskedIntrinsic;
12182   return AtomicExpansionKind::None;
12183 }
12184 
12185 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
12186     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
12187     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
12188   unsigned XLen = Subtarget.getXLen();
12189   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
12190   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
12191   if (XLen == 64) {
12192     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
12193     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
12194     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
12195     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
12196   }
12197   Type *Tys[] = {AlignedAddr->getType()};
12198   Function *MaskedCmpXchg =
12199       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
12200   Value *Result = Builder.CreateCall(
12201       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
12202   if (XLen == 64)
12203     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
12204   return Result;
12205 }
12206 
12207 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT,
12208                                                         EVT DataVT) const {
12209   return false;
12210 }
12211 
12212 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
12213                                                EVT VT) const {
12214   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
12215     return false;
12216 
12217   switch (FPVT.getSimpleVT().SimpleTy) {
12218   case MVT::f16:
12219     return Subtarget.hasStdExtZfh();
12220   case MVT::f32:
12221     return Subtarget.hasStdExtF();
12222   case MVT::f64:
12223     return Subtarget.hasStdExtD();
12224   default:
12225     return false;
12226   }
12227 }
12228 
12229 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
12230   // If we are using the small code model, we can reduce size of jump table
12231   // entry to 4 bytes.
12232   if (Subtarget.is64Bit() && !isPositionIndependent() &&
12233       getTargetMachine().getCodeModel() == CodeModel::Small) {
12234     return MachineJumpTableInfo::EK_Custom32;
12235   }
12236   return TargetLowering::getJumpTableEncoding();
12237 }
12238 
12239 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
12240     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
12241     unsigned uid, MCContext &Ctx) const {
12242   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
12243          getTargetMachine().getCodeModel() == CodeModel::Small);
12244   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
12245 }
12246 
12247 bool RISCVTargetLowering::isVScaleKnownToBeAPowerOfTwo() const {
12248   // We define vscale to be VLEN/RVVBitsPerBlock.  VLEN is always a power
12249   // of two >= 64, and RVVBitsPerBlock is 64.  Thus, vscale must be
12250   // a power of two as well.
12251   // FIXME: This doesn't work for zve32, but that's already broken
12252   // elsewhere for the same reason.
12253   assert(Subtarget.getRealMinVLen() >= 64 && "zve32* unsupported");
12254   static_assert(RISCV::RVVBitsPerBlock == 64,
12255                 "RVVBitsPerBlock changed, audit needed");
12256   return true;
12257 }
12258 
12259 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
12260                                                      EVT VT) const {
12261   VT = VT.getScalarType();
12262 
12263   if (!VT.isSimple())
12264     return false;
12265 
12266   switch (VT.getSimpleVT().SimpleTy) {
12267   case MVT::f16:
12268     return Subtarget.hasStdExtZfh();
12269   case MVT::f32:
12270     return Subtarget.hasStdExtF();
12271   case MVT::f64:
12272     return Subtarget.hasStdExtD();
12273   default:
12274     break;
12275   }
12276 
12277   return false;
12278 }
12279 
12280 Register RISCVTargetLowering::getExceptionPointerRegister(
12281     const Constant *PersonalityFn) const {
12282   return RISCV::X10;
12283 }
12284 
12285 Register RISCVTargetLowering::getExceptionSelectorRegister(
12286     const Constant *PersonalityFn) const {
12287   return RISCV::X11;
12288 }
12289 
12290 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
12291   // Return false to suppress the unnecessary extensions if the LibCall
12292   // arguments or return value is f32 type for LP64 ABI.
12293   RISCVABI::ABI ABI = Subtarget.getTargetABI();
12294   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
12295     return false;
12296 
12297   return true;
12298 }
12299 
12300 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
12301   if (Subtarget.is64Bit() && Type == MVT::i32)
12302     return true;
12303 
12304   return IsSigned;
12305 }
12306 
12307 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
12308                                                  SDValue C) const {
12309   // Check integral scalar types.
12310   const bool HasExtMOrZmmul =
12311       Subtarget.hasStdExtM() || Subtarget.hasStdExtZmmul();
12312   if (VT.isScalarInteger()) {
12313     // Omit the optimization if the sub target has the M extension and the data
12314     // size exceeds XLen.
12315     if (HasExtMOrZmmul && VT.getSizeInBits() > Subtarget.getXLen())
12316       return false;
12317     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
12318       // Break the MUL to a SLLI and an ADD/SUB.
12319       const APInt &Imm = ConstNode->getAPIntValue();
12320       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
12321           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
12322         return true;
12323       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
12324       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
12325           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
12326            (Imm - 8).isPowerOf2()))
12327         return true;
12328       // Omit the following optimization if the sub target has the M extension
12329       // and the data size >= XLen.
12330       if (HasExtMOrZmmul && VT.getSizeInBits() >= Subtarget.getXLen())
12331         return false;
12332       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
12333       // a pair of LUI/ADDI.
12334       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
12335         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
12336         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
12337             (1 - ImmS).isPowerOf2())
12338           return true;
12339       }
12340     }
12341   }
12342 
12343   return false;
12344 }
12345 
12346 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
12347                                                       SDValue ConstNode) const {
12348   // Let the DAGCombiner decide for vectors.
12349   EVT VT = AddNode.getValueType();
12350   if (VT.isVector())
12351     return true;
12352 
12353   // Let the DAGCombiner decide for larger types.
12354   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
12355     return true;
12356 
12357   // It is worse if c1 is simm12 while c1*c2 is not.
12358   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
12359   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
12360   const APInt &C1 = C1Node->getAPIntValue();
12361   const APInt &C2 = C2Node->getAPIntValue();
12362   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
12363     return false;
12364 
12365   // Default to true and let the DAGCombiner decide.
12366   return true;
12367 }
12368 
12369 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
12370     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
12371     bool *Fast) const {
12372   if (!VT.isVector()) {
12373     if (Fast)
12374       *Fast = false;
12375     return Subtarget.enableUnalignedScalarMem();
12376   }
12377 
12378   // All vector implementations must support element alignment
12379   EVT ElemVT = VT.getVectorElementType();
12380   if (Alignment >= ElemVT.getStoreSize()) {
12381     if (Fast)
12382       *Fast = true;
12383     return true;
12384   }
12385 
12386   return false;
12387 }
12388 
12389 bool RISCVTargetLowering::splitValueIntoRegisterParts(
12390     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
12391     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
12392   bool IsABIRegCopy = CC.has_value();
12393   EVT ValueVT = Val.getValueType();
12394   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
12395     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
12396     // and cast to f32.
12397     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
12398     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
12399     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
12400                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
12401     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
12402     Parts[0] = Val;
12403     return true;
12404   }
12405 
12406   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
12407     LLVMContext &Context = *DAG.getContext();
12408     EVT ValueEltVT = ValueVT.getVectorElementType();
12409     EVT PartEltVT = PartVT.getVectorElementType();
12410     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
12411     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
12412     if (PartVTBitSize % ValueVTBitSize == 0) {
12413       assert(PartVTBitSize >= ValueVTBitSize);
12414       // If the element types are different, bitcast to the same element type of
12415       // PartVT first.
12416       // Give an example here, we want copy a <vscale x 1 x i8> value to
12417       // <vscale x 4 x i16>.
12418       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
12419       // subvector, then we can bitcast to <vscale x 4 x i16>.
12420       if (ValueEltVT != PartEltVT) {
12421         if (PartVTBitSize > ValueVTBitSize) {
12422           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
12423           assert(Count != 0 && "The number of element should not be zero.");
12424           EVT SameEltTypeVT =
12425               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
12426           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
12427                             DAG.getUNDEF(SameEltTypeVT), Val,
12428                             DAG.getVectorIdxConstant(0, DL));
12429         }
12430         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
12431       } else {
12432         Val =
12433             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
12434                         Val, DAG.getVectorIdxConstant(0, DL));
12435       }
12436       Parts[0] = Val;
12437       return true;
12438     }
12439   }
12440   return false;
12441 }
12442 
12443 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
12444     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
12445     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
12446   bool IsABIRegCopy = CC.has_value();
12447   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
12448     SDValue Val = Parts[0];
12449 
12450     // Cast the f32 to i32, truncate to i16, and cast back to f16.
12451     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
12452     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
12453     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
12454     return Val;
12455   }
12456 
12457   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
12458     LLVMContext &Context = *DAG.getContext();
12459     SDValue Val = Parts[0];
12460     EVT ValueEltVT = ValueVT.getVectorElementType();
12461     EVT PartEltVT = PartVT.getVectorElementType();
12462     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
12463     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
12464     if (PartVTBitSize % ValueVTBitSize == 0) {
12465       assert(PartVTBitSize >= ValueVTBitSize);
12466       EVT SameEltTypeVT = ValueVT;
12467       // If the element types are different, convert it to the same element type
12468       // of PartVT.
12469       // Give an example here, we want copy a <vscale x 1 x i8> value from
12470       // <vscale x 4 x i16>.
12471       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
12472       // then we can extract <vscale x 1 x i8>.
12473       if (ValueEltVT != PartEltVT) {
12474         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
12475         assert(Count != 0 && "The number of element should not be zero.");
12476         SameEltTypeVT =
12477             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
12478         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
12479       }
12480       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
12481                         DAG.getVectorIdxConstant(0, DL));
12482       return Val;
12483     }
12484   }
12485   return SDValue();
12486 }
12487 
12488 SDValue
12489 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12490                                    SelectionDAG &DAG,
12491                                    SmallVectorImpl<SDNode *> &Created) const {
12492   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
12493   if (isIntDivCheap(N->getValueType(0), Attr))
12494     return SDValue(N, 0); // Lower SDIV as SDIV
12495 
12496   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
12497          "Unexpected divisor!");
12498 
12499   // Conditional move is needed, so do the transformation iff Zbt is enabled.
12500   if (!Subtarget.hasStdExtZbt())
12501     return SDValue();
12502 
12503   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
12504   // Besides, more critical path instructions will be generated when dividing
12505   // by 2. So we keep using the original DAGs for these cases.
12506   unsigned Lg2 = Divisor.countTrailingZeros();
12507   if (Lg2 == 1 || Lg2 >= 12)
12508     return SDValue();
12509 
12510   // fold (sdiv X, pow2)
12511   EVT VT = N->getValueType(0);
12512   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
12513     return SDValue();
12514 
12515   SDLoc DL(N);
12516   SDValue N0 = N->getOperand(0);
12517   SDValue Zero = DAG.getConstant(0, DL, VT);
12518   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
12519 
12520   // Add (N0 < 0) ? Pow2 - 1 : 0;
12521   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
12522   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
12523   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
12524 
12525   Created.push_back(Cmp.getNode());
12526   Created.push_back(Add.getNode());
12527   Created.push_back(Sel.getNode());
12528 
12529   // Divide by pow2.
12530   SDValue SRA =
12531       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
12532 
12533   // If we're dividing by a positive value, we're done.  Otherwise, we must
12534   // negate the result.
12535   if (Divisor.isNonNegative())
12536     return SRA;
12537 
12538   Created.push_back(SRA.getNode());
12539   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
12540 }
12541 
12542 #define GET_REGISTER_MATCHER
12543 #include "RISCVGenAsmMatcher.inc"
12544 
12545 Register
12546 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
12547                                        const MachineFunction &MF) const {
12548   Register Reg = MatchRegisterAltName(RegName);
12549   if (Reg == RISCV::NoRegister)
12550     Reg = MatchRegisterName(RegName);
12551   if (Reg == RISCV::NoRegister)
12552     report_fatal_error(
12553         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
12554   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
12555   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
12556     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
12557                              StringRef(RegName) + "\"."));
12558   return Reg;
12559 }
12560 
12561 namespace llvm {
12562 namespace RISCVVIntrinsicsTable {
12563 
12564 #define GET_RISCVVIntrinsicsTable_IMPL
12565 #include "RISCVGenSearchableTables.inc"
12566 
12567 } // namespace RISCVVIntrinsicsTable
12568 
12569 } // namespace llvm
12570