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/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
28 #include "llvm/CodeGen/ValueTypes.h"
29 #include "llvm/IR/DiagnosticInfo.h"
30 #include "llvm/IR/DiagnosticPrinter.h"
31 #include "llvm/IR/IntrinsicsRISCV.h"
32 #include "llvm/IR/IRBuilder.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/KnownBits.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "riscv-lower"
42 
43 STATISTIC(NumTailCalls, "Number of tail calls");
44 
45 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
46                                          const RISCVSubtarget &STI)
47     : TargetLowering(TM), Subtarget(STI) {
48 
49   if (Subtarget.isRV32E())
50     report_fatal_error("Codegen not yet implemented for RV32E");
51 
52   RISCVABI::ABI ABI = Subtarget.getTargetABI();
53   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
54 
55   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
56       !Subtarget.hasStdExtF()) {
57     errs() << "Hard-float 'f' ABI can't be used for a target that "
58                 "doesn't support the F instruction set extension (ignoring "
59                           "target-abi)\n";
60     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
61   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
62              !Subtarget.hasStdExtD()) {
63     errs() << "Hard-float 'd' ABI can't be used for a target that "
64               "doesn't support the D instruction set extension (ignoring "
65               "target-abi)\n";
66     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
67   }
68 
69   switch (ABI) {
70   default:
71     report_fatal_error("Don't know how to lower this ABI");
72   case RISCVABI::ABI_ILP32:
73   case RISCVABI::ABI_ILP32F:
74   case RISCVABI::ABI_ILP32D:
75   case RISCVABI::ABI_LP64:
76   case RISCVABI::ABI_LP64F:
77   case RISCVABI::ABI_LP64D:
78     break;
79   }
80 
81   MVT XLenVT = Subtarget.getXLenVT();
82 
83   // Set up the register classes.
84   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
85 
86   if (Subtarget.hasStdExtZfh())
87     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
88   if (Subtarget.hasStdExtF())
89     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
90   if (Subtarget.hasStdExtD())
91     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
92 
93   static const MVT::SimpleValueType BoolVecVTs[] = {
94       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
95       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
96   static const MVT::SimpleValueType IntVecVTs[] = {
97       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
98       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
99       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
100       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
101       MVT::nxv4i64, MVT::nxv8i64};
102   static const MVT::SimpleValueType F16VecVTs[] = {
103       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
104       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
105   static const MVT::SimpleValueType F32VecVTs[] = {
106       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
107   static const MVT::SimpleValueType F64VecVTs[] = {
108       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
109 
110   if (Subtarget.hasStdExtV()) {
111     auto addRegClassForRVV = [this](MVT VT) {
112       unsigned Size = VT.getSizeInBits().getKnownMinValue();
113       assert(Size <= 512 && isPowerOf2_32(Size));
114       const TargetRegisterClass *RC;
115       if (Size <= 64)
116         RC = &RISCV::VRRegClass;
117       else if (Size == 128)
118         RC = &RISCV::VRM2RegClass;
119       else if (Size == 256)
120         RC = &RISCV::VRM4RegClass;
121       else
122         RC = &RISCV::VRM8RegClass;
123 
124       addRegisterClass(VT, RC);
125     };
126 
127     for (MVT VT : BoolVecVTs)
128       addRegClassForRVV(VT);
129     for (MVT VT : IntVecVTs)
130       addRegClassForRVV(VT);
131 
132     if (Subtarget.hasStdExtZfh())
133       for (MVT VT : F16VecVTs)
134         addRegClassForRVV(VT);
135 
136     if (Subtarget.hasStdExtF())
137       for (MVT VT : F32VecVTs)
138         addRegClassForRVV(VT);
139 
140     if (Subtarget.hasStdExtD())
141       for (MVT VT : F64VecVTs)
142         addRegClassForRVV(VT);
143 
144     if (Subtarget.useRVVForFixedLengthVectors()) {
145       auto addRegClassForFixedVectors = [this](MVT VT) {
146         MVT ContainerVT = getContainerForFixedLengthVector(VT);
147         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
148         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
149         addRegisterClass(VT, TRI.getRegClass(RCID));
150       };
151       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
152         if (useRVVForFixedLengthVectorVT(VT))
153           addRegClassForFixedVectors(VT);
154 
155       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
156         if (useRVVForFixedLengthVectorVT(VT))
157           addRegClassForFixedVectors(VT);
158     }
159   }
160 
161   // Compute derived properties from the register classes.
162   computeRegisterProperties(STI.getRegisterInfo());
163 
164   setStackPointerRegisterToSaveRestore(RISCV::X2);
165 
166   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
167     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
168 
169   // TODO: add all necessary setOperationAction calls.
170   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
171 
172   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
173   setOperationAction(ISD::BR_CC, XLenVT, Expand);
174   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
175   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
176 
177   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
178   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
179 
180   setOperationAction(ISD::VASTART, MVT::Other, Custom);
181   setOperationAction(ISD::VAARG, MVT::Other, Expand);
182   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
183   setOperationAction(ISD::VAEND, MVT::Other, Expand);
184 
185   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
186   if (!Subtarget.hasStdExtZbb()) {
187     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
188     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
189   }
190 
191   if (Subtarget.is64Bit()) {
192     setOperationAction(ISD::ADD, MVT::i32, Custom);
193     setOperationAction(ISD::SUB, MVT::i32, Custom);
194     setOperationAction(ISD::SHL, MVT::i32, Custom);
195     setOperationAction(ISD::SRA, MVT::i32, Custom);
196     setOperationAction(ISD::SRL, MVT::i32, Custom);
197 
198     setOperationAction(ISD::UADDO, MVT::i32, Custom);
199     setOperationAction(ISD::USUBO, MVT::i32, Custom);
200     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
201     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
202   } else {
203     setLibcallName(RTLIB::MUL_I128, nullptr);
204     setLibcallName(RTLIB::MULO_I64, nullptr);
205   }
206 
207   if (!Subtarget.hasStdExtM()) {
208     setOperationAction(ISD::MUL, XLenVT, Expand);
209     setOperationAction(ISD::MULHS, XLenVT, Expand);
210     setOperationAction(ISD::MULHU, XLenVT, Expand);
211     setOperationAction(ISD::SDIV, XLenVT, Expand);
212     setOperationAction(ISD::UDIV, XLenVT, Expand);
213     setOperationAction(ISD::SREM, XLenVT, Expand);
214     setOperationAction(ISD::UREM, XLenVT, Expand);
215   } else {
216     if (Subtarget.is64Bit()) {
217       setOperationAction(ISD::MUL, MVT::i32, Custom);
218       setOperationAction(ISD::MUL, MVT::i128, Custom);
219 
220       setOperationAction(ISD::SDIV, MVT::i8, Custom);
221       setOperationAction(ISD::UDIV, MVT::i8, Custom);
222       setOperationAction(ISD::UREM, MVT::i8, Custom);
223       setOperationAction(ISD::SDIV, MVT::i16, Custom);
224       setOperationAction(ISD::UDIV, MVT::i16, Custom);
225       setOperationAction(ISD::UREM, MVT::i16, Custom);
226       setOperationAction(ISD::SDIV, MVT::i32, Custom);
227       setOperationAction(ISD::UDIV, MVT::i32, Custom);
228       setOperationAction(ISD::UREM, MVT::i32, Custom);
229     } else {
230       setOperationAction(ISD::MUL, MVT::i64, Custom);
231     }
232   }
233 
234   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
235   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
236   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
237   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
238 
239   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
240   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
241   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
242 
243   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
244     if (Subtarget.is64Bit()) {
245       setOperationAction(ISD::ROTL, MVT::i32, Custom);
246       setOperationAction(ISD::ROTR, MVT::i32, Custom);
247     }
248   } else {
249     setOperationAction(ISD::ROTL, XLenVT, Expand);
250     setOperationAction(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, XLenVT,   Custom);
257     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
258     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
259     // BSWAP i8 doesn't exist.
260     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
261     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
262 
263     if (Subtarget.is64Bit()) {
264       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
265       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
266     }
267   } else {
268     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
269     // pattern match it directly in isel.
270     setOperationAction(ISD::BSWAP, XLenVT,
271                        Subtarget.hasStdExtZbb() ? Legal : Expand);
272   }
273 
274   if (Subtarget.hasStdExtZbb()) {
275     setOperationAction(ISD::SMIN, XLenVT, Legal);
276     setOperationAction(ISD::SMAX, XLenVT, Legal);
277     setOperationAction(ISD::UMIN, XLenVT, Legal);
278     setOperationAction(ISD::UMAX, XLenVT, Legal);
279 
280     if (Subtarget.is64Bit()) {
281       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
282       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
283       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
284       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
285     }
286   } else {
287     setOperationAction(ISD::CTTZ, XLenVT, Expand);
288     setOperationAction(ISD::CTLZ, XLenVT, Expand);
289     setOperationAction(ISD::CTPOP, XLenVT, Expand);
290   }
291 
292   if (Subtarget.hasStdExtZbt()) {
293     setOperationAction(ISD::FSHL, XLenVT, Custom);
294     setOperationAction(ISD::FSHR, XLenVT, Custom);
295     setOperationAction(ISD::SELECT, XLenVT, Legal);
296 
297     if (Subtarget.is64Bit()) {
298       setOperationAction(ISD::FSHL, MVT::i32, Custom);
299       setOperationAction(ISD::FSHR, MVT::i32, Custom);
300     }
301   } else {
302     setOperationAction(ISD::SELECT, XLenVT, Custom);
303   }
304 
305   ISD::CondCode FPCCToExpand[] = {
306       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
307       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
308       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
309 
310   ISD::NodeType FPOpToExpand[] = {
311       ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, ISD::FREM, ISD::FP16_TO_FP,
312       ISD::FP_TO_FP16};
313 
314   if (Subtarget.hasStdExtZfh())
315     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
316 
317   if (Subtarget.hasStdExtZfh()) {
318     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
319     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
320     setOperationAction(ISD::LRINT, MVT::f16, Legal);
321     setOperationAction(ISD::LLRINT, MVT::f16, Legal);
322     setOperationAction(ISD::LROUND, MVT::f16, Legal);
323     setOperationAction(ISD::LLROUND, MVT::f16, Legal);
324     for (auto CC : FPCCToExpand)
325       setCondCodeAction(CC, MVT::f16, Expand);
326     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
327     setOperationAction(ISD::SELECT, MVT::f16, Custom);
328     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
329     for (auto Op : FPOpToExpand)
330       setOperationAction(Op, MVT::f16, Expand);
331   }
332 
333   if (Subtarget.hasStdExtF()) {
334     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
335     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
336     setOperationAction(ISD::LRINT, MVT::f32, Legal);
337     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
338     setOperationAction(ISD::LROUND, MVT::f32, Legal);
339     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
340     for (auto CC : FPCCToExpand)
341       setCondCodeAction(CC, MVT::f32, Expand);
342     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
343     setOperationAction(ISD::SELECT, MVT::f32, Custom);
344     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
345     for (auto Op : FPOpToExpand)
346       setOperationAction(Op, MVT::f32, Expand);
347     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
348     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
349   }
350 
351   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
352     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
353 
354   if (Subtarget.hasStdExtD()) {
355     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
356     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
357     setOperationAction(ISD::LRINT, MVT::f64, Legal);
358     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
359     setOperationAction(ISD::LROUND, MVT::f64, Legal);
360     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
361     for (auto CC : FPCCToExpand)
362       setCondCodeAction(CC, MVT::f64, Expand);
363     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
364     setOperationAction(ISD::SELECT, MVT::f64, Custom);
365     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
366     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
367     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
368     for (auto Op : FPOpToExpand)
369       setOperationAction(Op, MVT::f64, Expand);
370     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
371     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
372   }
373 
374   if (Subtarget.is64Bit()) {
375     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
376     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
377     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
378     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
379   }
380 
381   if (Subtarget.hasStdExtF()) {
382     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
383     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
384 
385     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
386     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
387   }
388 
389   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
390   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
391   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
392   setOperationAction(ISD::JumpTable, XLenVT, Custom);
393 
394   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
395 
396   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
397   // Unfortunately this can't be determined just from the ISA naming string.
398   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
399                      Subtarget.is64Bit() ? Legal : Custom);
400 
401   setOperationAction(ISD::TRAP, MVT::Other, Legal);
402   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
403   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
404   if (Subtarget.is64Bit())
405     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
406 
407   if (Subtarget.hasStdExtA()) {
408     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
409     setMinCmpXchgSizeInBits(32);
410   } else {
411     setMaxAtomicSizeInBitsSupported(0);
412   }
413 
414   setBooleanContents(ZeroOrOneBooleanContent);
415 
416   if (Subtarget.hasStdExtV()) {
417     setBooleanVectorContents(ZeroOrOneBooleanContent);
418 
419     setOperationAction(ISD::VSCALE, XLenVT, Custom);
420 
421     // RVV intrinsics may have illegal operands.
422     // We also need to custom legalize vmv.x.s.
423     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
424     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
425     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
426     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
427     if (Subtarget.is64Bit()) {
428       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
429     } else {
430       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
431       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
432     }
433 
434     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
435 
436     static unsigned IntegerVPOps[] = {
437         ISD::VP_ADD,  ISD::VP_SUB,  ISD::VP_MUL, ISD::VP_SDIV, ISD::VP_UDIV,
438         ISD::VP_SREM, ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR,   ISD::VP_XOR,
439         ISD::VP_ASHR, ISD::VP_LSHR, ISD::VP_SHL};
440 
441     static unsigned FloatingPointVPOps[] = {ISD::VP_FADD, ISD::VP_FSUB,
442                                             ISD::VP_FMUL, ISD::VP_FDIV};
443 
444     if (!Subtarget.is64Bit()) {
445       // We must custom-lower certain vXi64 operations on RV32 due to the vector
446       // element type being illegal.
447       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
448       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
449 
450       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
451       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
452       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
453       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
454       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
455       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
456       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
457       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
458     }
459 
460     for (MVT VT : BoolVecVTs) {
461       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
462 
463       // Mask VTs are custom-expanded into a series of standard nodes
464       setOperationAction(ISD::TRUNCATE, VT, Custom);
465       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
466       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
467       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
468 
469       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
470       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
471 
472       setOperationAction(ISD::SELECT, VT, Custom);
473       setOperationAction(ISD::SELECT_CC, VT, Expand);
474       setOperationAction(ISD::VSELECT, VT, Expand);
475 
476       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
477       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
478       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
479 
480       // RVV has native int->float & float->int conversions where the
481       // element type sizes are within one power-of-two of each other. Any
482       // wider distances between type sizes have to be lowered as sequences
483       // which progressively narrow the gap in stages.
484       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
485       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
486       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
487       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
488 
489       // Expand all extending loads to types larger than this, and truncating
490       // stores from types larger than this.
491       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
492         setTruncStoreAction(OtherVT, VT, Expand);
493         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
494         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
495         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
496       }
497     }
498 
499     for (MVT VT : IntVecVTs) {
500       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
501       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
502 
503       setOperationAction(ISD::SMIN, VT, Legal);
504       setOperationAction(ISD::SMAX, VT, Legal);
505       setOperationAction(ISD::UMIN, VT, Legal);
506       setOperationAction(ISD::UMAX, VT, Legal);
507 
508       setOperationAction(ISD::ROTL, VT, Expand);
509       setOperationAction(ISD::ROTR, VT, Expand);
510 
511       // Custom-lower extensions and truncations from/to mask types.
512       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
513       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
514       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
515 
516       // RVV has native int->float & float->int conversions where the
517       // element type sizes are within one power-of-two of each other. Any
518       // wider distances between type sizes have to be lowered as sequences
519       // which progressively narrow the gap in stages.
520       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
521       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
522       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
523       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
524 
525       setOperationAction(ISD::SADDSAT, VT, Legal);
526       setOperationAction(ISD::UADDSAT, VT, Legal);
527       setOperationAction(ISD::SSUBSAT, VT, Legal);
528       setOperationAction(ISD::USUBSAT, VT, Legal);
529 
530       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
531       // nodes which truncate by one power of two at a time.
532       setOperationAction(ISD::TRUNCATE, VT, Custom);
533 
534       // Custom-lower insert/extract operations to simplify patterns.
535       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
536       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
537 
538       // Custom-lower reduction operations to set up the corresponding custom
539       // nodes' operands.
540       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
541       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
542       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
543       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
544       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
545       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
546       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
547       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
548 
549       for (unsigned VPOpc : IntegerVPOps)
550         setOperationAction(VPOpc, VT, Custom);
551 
552       setOperationAction(ISD::LOAD, VT, Custom);
553       setOperationAction(ISD::STORE, VT, Custom);
554 
555       setOperationAction(ISD::MLOAD, VT, Custom);
556       setOperationAction(ISD::MSTORE, VT, Custom);
557       setOperationAction(ISD::MGATHER, VT, Custom);
558       setOperationAction(ISD::MSCATTER, VT, Custom);
559 
560       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
561       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
562       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
563 
564       setOperationAction(ISD::SELECT, VT, Custom);
565       setOperationAction(ISD::SELECT_CC, VT, Expand);
566 
567       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
568       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
569 
570       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
571         setTruncStoreAction(VT, OtherVT, Expand);
572         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
573         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
574         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
575       }
576     }
577 
578     // Expand various CCs to best match the RVV ISA, which natively supports UNE
579     // but no other unordered comparisons, and supports all ordered comparisons
580     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
581     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
582     // and we pattern-match those back to the "original", swapping operands once
583     // more. This way we catch both operations and both "vf" and "fv" forms with
584     // fewer patterns.
585     ISD::CondCode VFPCCToExpand[] = {
586         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
587         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
588         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
589     };
590 
591     // Sets common operation actions on RVV floating-point vector types.
592     const auto SetCommonVFPActions = [&](MVT VT) {
593       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
594       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
595       // sizes are within one power-of-two of each other. Therefore conversions
596       // between vXf16 and vXf64 must be lowered as sequences which convert via
597       // vXf32.
598       setOperationAction(ISD::FP_ROUND, VT, Custom);
599       setOperationAction(ISD::FP_EXTEND, VT, Custom);
600       // Custom-lower insert/extract operations to simplify patterns.
601       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
602       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
603       // Expand various condition codes (explained above).
604       for (auto CC : VFPCCToExpand)
605         setCondCodeAction(CC, VT, Expand);
606 
607       setOperationAction(ISD::FMINNUM, VT, Legal);
608       setOperationAction(ISD::FMAXNUM, VT, Legal);
609 
610       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
611       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
612       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
613       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
614       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
615 
616       setOperationAction(ISD::LOAD, VT, Custom);
617       setOperationAction(ISD::STORE, VT, Custom);
618 
619       setOperationAction(ISD::MLOAD, VT, Custom);
620       setOperationAction(ISD::MSTORE, VT, Custom);
621       setOperationAction(ISD::MGATHER, VT, Custom);
622       setOperationAction(ISD::MSCATTER, VT, Custom);
623 
624       setOperationAction(ISD::SELECT, VT, Custom);
625       setOperationAction(ISD::SELECT_CC, VT, Expand);
626 
627       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
628       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
629       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
630 
631       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
632 
633       for (unsigned VPOpc : FloatingPointVPOps)
634         setOperationAction(VPOpc, VT, Custom);
635     };
636 
637     // Sets common extload/truncstore actions on RVV floating-point vector
638     // types.
639     const auto SetCommonVFPExtLoadTruncStoreActions =
640         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
641           for (auto SmallVT : SmallerVTs) {
642             setTruncStoreAction(VT, SmallVT, Expand);
643             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
644           }
645         };
646 
647     if (Subtarget.hasStdExtZfh())
648       for (MVT VT : F16VecVTs)
649         SetCommonVFPActions(VT);
650 
651     for (MVT VT : F32VecVTs) {
652       if (Subtarget.hasStdExtF())
653         SetCommonVFPActions(VT);
654       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
655     }
656 
657     for (MVT VT : F64VecVTs) {
658       if (Subtarget.hasStdExtD())
659         SetCommonVFPActions(VT);
660       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
661       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
662     }
663 
664     if (Subtarget.useRVVForFixedLengthVectors()) {
665       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
666         if (!useRVVForFixedLengthVectorVT(VT))
667           continue;
668 
669         // By default everything must be expanded.
670         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
671           setOperationAction(Op, VT, Expand);
672         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
673           setTruncStoreAction(VT, OtherVT, Expand);
674           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
675           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
676           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
677         }
678 
679         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
680         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
681         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
682 
683         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
684         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
685 
686         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
687         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
688 
689         setOperationAction(ISD::LOAD, VT, Custom);
690         setOperationAction(ISD::STORE, VT, Custom);
691 
692         setOperationAction(ISD::SETCC, VT, Custom);
693 
694         setOperationAction(ISD::SELECT, VT, Custom);
695 
696         setOperationAction(ISD::TRUNCATE, VT, Custom);
697 
698         setOperationAction(ISD::BITCAST, VT, Custom);
699 
700         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
701         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
702         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
703 
704         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
705         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
706         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
707         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
708 
709         // Operations below are different for between masks and other vectors.
710         if (VT.getVectorElementType() == MVT::i1) {
711           setOperationAction(ISD::AND, VT, Custom);
712           setOperationAction(ISD::OR, VT, Custom);
713           setOperationAction(ISD::XOR, VT, Custom);
714           continue;
715         }
716 
717         // Use SPLAT_VECTOR to prevent type legalization from destroying the
718         // splats when type legalizing i64 scalar on RV32.
719         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
720         // improvements first.
721         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
722           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
723           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
724         }
725 
726         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
727         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
728 
729         setOperationAction(ISD::MLOAD, VT, Custom);
730         setOperationAction(ISD::MSTORE, VT, Custom);
731         setOperationAction(ISD::MGATHER, VT, Custom);
732         setOperationAction(ISD::MSCATTER, VT, Custom);
733         setOperationAction(ISD::ADD, VT, Custom);
734         setOperationAction(ISD::MUL, VT, Custom);
735         setOperationAction(ISD::SUB, VT, Custom);
736         setOperationAction(ISD::AND, VT, Custom);
737         setOperationAction(ISD::OR, VT, Custom);
738         setOperationAction(ISD::XOR, VT, Custom);
739         setOperationAction(ISD::SDIV, VT, Custom);
740         setOperationAction(ISD::SREM, VT, Custom);
741         setOperationAction(ISD::UDIV, VT, Custom);
742         setOperationAction(ISD::UREM, VT, Custom);
743         setOperationAction(ISD::SHL, VT, Custom);
744         setOperationAction(ISD::SRA, VT, Custom);
745         setOperationAction(ISD::SRL, VT, Custom);
746 
747         setOperationAction(ISD::SMIN, VT, Custom);
748         setOperationAction(ISD::SMAX, VT, Custom);
749         setOperationAction(ISD::UMIN, VT, Custom);
750         setOperationAction(ISD::UMAX, VT, Custom);
751         setOperationAction(ISD::ABS,  VT, Custom);
752 
753         setOperationAction(ISD::MULHS, VT, Custom);
754         setOperationAction(ISD::MULHU, VT, Custom);
755 
756         setOperationAction(ISD::SADDSAT, VT, Custom);
757         setOperationAction(ISD::UADDSAT, VT, Custom);
758         setOperationAction(ISD::SSUBSAT, VT, Custom);
759         setOperationAction(ISD::USUBSAT, VT, Custom);
760 
761         setOperationAction(ISD::VSELECT, VT, Custom);
762         setOperationAction(ISD::SELECT_CC, VT, Expand);
763 
764         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
765         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
766         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
767 
768         // Custom-lower reduction operations to set up the corresponding custom
769         // nodes' operands.
770         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
771         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
772         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
773         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
774         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
775 
776         for (unsigned VPOpc : IntegerVPOps)
777           setOperationAction(VPOpc, VT, Custom);
778       }
779 
780       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
781         if (!useRVVForFixedLengthVectorVT(VT))
782           continue;
783 
784         // By default everything must be expanded.
785         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
786           setOperationAction(Op, VT, Expand);
787         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
788           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
789           setTruncStoreAction(VT, OtherVT, Expand);
790         }
791 
792         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
793         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
794         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
795 
796         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
797         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
798         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
799         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
800         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
801 
802         setOperationAction(ISD::LOAD, VT, Custom);
803         setOperationAction(ISD::STORE, VT, Custom);
804         setOperationAction(ISD::MLOAD, VT, Custom);
805         setOperationAction(ISD::MSTORE, VT, Custom);
806         setOperationAction(ISD::MGATHER, VT, Custom);
807         setOperationAction(ISD::MSCATTER, VT, Custom);
808         setOperationAction(ISD::FADD, VT, Custom);
809         setOperationAction(ISD::FSUB, VT, Custom);
810         setOperationAction(ISD::FMUL, VT, Custom);
811         setOperationAction(ISD::FDIV, VT, Custom);
812         setOperationAction(ISD::FNEG, VT, Custom);
813         setOperationAction(ISD::FABS, VT, Custom);
814         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
815         setOperationAction(ISD::FSQRT, VT, Custom);
816         setOperationAction(ISD::FMA, VT, Custom);
817         setOperationAction(ISD::FMINNUM, VT, Custom);
818         setOperationAction(ISD::FMAXNUM, VT, Custom);
819 
820         setOperationAction(ISD::FP_ROUND, VT, Custom);
821         setOperationAction(ISD::FP_EXTEND, VT, Custom);
822 
823         for (auto CC : VFPCCToExpand)
824           setCondCodeAction(CC, VT, Expand);
825 
826         setOperationAction(ISD::VSELECT, VT, Custom);
827         setOperationAction(ISD::SELECT, VT, Custom);
828         setOperationAction(ISD::SELECT_CC, VT, Expand);
829 
830         setOperationAction(ISD::BITCAST, VT, Custom);
831 
832         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
833         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
834         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
835         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
836 
837         for (unsigned VPOpc : FloatingPointVPOps)
838           setOperationAction(VPOpc, VT, Custom);
839       }
840 
841       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
842       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
843       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
844       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
845       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
846       setOperationAction(ISD::BITCAST, MVT::f16, Custom);
847       setOperationAction(ISD::BITCAST, MVT::f32, Custom);
848       setOperationAction(ISD::BITCAST, MVT::f64, Custom);
849     }
850   }
851 
852   // Function alignments.
853   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
854   setMinFunctionAlignment(FunctionAlignment);
855   setPrefFunctionAlignment(FunctionAlignment);
856 
857   setMinimumJumpTableEntries(5);
858 
859   // Jumps are expensive, compared to logic
860   setJumpIsExpensive();
861 
862   // We can use any register for comparisons
863   setHasMultipleConditionRegisters();
864 
865   setTargetDAGCombine(ISD::ADD);
866   setTargetDAGCombine(ISD::SUB);
867   setTargetDAGCombine(ISD::AND);
868   setTargetDAGCombine(ISD::OR);
869   setTargetDAGCombine(ISD::XOR);
870   setTargetDAGCombine(ISD::ANY_EXTEND);
871   setTargetDAGCombine(ISD::ZERO_EXTEND);
872   if (Subtarget.hasStdExtV()) {
873     setTargetDAGCombine(ISD::FCOPYSIGN);
874     setTargetDAGCombine(ISD::MGATHER);
875     setTargetDAGCombine(ISD::MSCATTER);
876     setTargetDAGCombine(ISD::SRA);
877     setTargetDAGCombine(ISD::SRL);
878     setTargetDAGCombine(ISD::SHL);
879   }
880 }
881 
882 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
883                                             LLVMContext &Context,
884                                             EVT VT) const {
885   if (!VT.isVector())
886     return getPointerTy(DL);
887   if (Subtarget.hasStdExtV() &&
888       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
889     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
890   return VT.changeVectorElementTypeToInteger();
891 }
892 
893 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
894   return Subtarget.getXLenVT();
895 }
896 
897 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
898                                              const CallInst &I,
899                                              MachineFunction &MF,
900                                              unsigned Intrinsic) const {
901   switch (Intrinsic) {
902   default:
903     return false;
904   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
905   case Intrinsic::riscv_masked_atomicrmw_add_i32:
906   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
907   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
908   case Intrinsic::riscv_masked_atomicrmw_max_i32:
909   case Intrinsic::riscv_masked_atomicrmw_min_i32:
910   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
911   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
912   case Intrinsic::riscv_masked_cmpxchg_i32: {
913     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
914     Info.opc = ISD::INTRINSIC_W_CHAIN;
915     Info.memVT = MVT::getVT(PtrTy->getElementType());
916     Info.ptrVal = I.getArgOperand(0);
917     Info.offset = 0;
918     Info.align = Align(4);
919     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
920                  MachineMemOperand::MOVolatile;
921     return true;
922   }
923   }
924 }
925 
926 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
927                                                 const AddrMode &AM, Type *Ty,
928                                                 unsigned AS,
929                                                 Instruction *I) const {
930   // No global is ever allowed as a base.
931   if (AM.BaseGV)
932     return false;
933 
934   // Require a 12-bit signed offset.
935   if (!isInt<12>(AM.BaseOffs))
936     return false;
937 
938   switch (AM.Scale) {
939   case 0: // "r+i" or just "i", depending on HasBaseReg.
940     break;
941   case 1:
942     if (!AM.HasBaseReg) // allow "r+i".
943       break;
944     return false; // disallow "r+r" or "r+r+i".
945   default:
946     return false;
947   }
948 
949   return true;
950 }
951 
952 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
953   return isInt<12>(Imm);
954 }
955 
956 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
957   return isInt<12>(Imm);
958 }
959 
960 // On RV32, 64-bit integers are split into their high and low parts and held
961 // in two different registers, so the trunc is free since the low register can
962 // just be used.
963 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
964   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
965     return false;
966   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
967   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
968   return (SrcBits == 64 && DestBits == 32);
969 }
970 
971 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
972   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
973       !SrcVT.isInteger() || !DstVT.isInteger())
974     return false;
975   unsigned SrcBits = SrcVT.getSizeInBits();
976   unsigned DestBits = DstVT.getSizeInBits();
977   return (SrcBits == 64 && DestBits == 32);
978 }
979 
980 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
981   // Zexts are free if they can be combined with a load.
982   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
983     EVT MemVT = LD->getMemoryVT();
984     if ((MemVT == MVT::i8 || MemVT == MVT::i16 ||
985          (Subtarget.is64Bit() && MemVT == MVT::i32)) &&
986         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
987          LD->getExtensionType() == ISD::ZEXTLOAD))
988       return true;
989   }
990 
991   return TargetLowering::isZExtFree(Val, VT2);
992 }
993 
994 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
995   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
996 }
997 
998 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
999   return Subtarget.hasStdExtZbb();
1000 }
1001 
1002 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1003   return Subtarget.hasStdExtZbb();
1004 }
1005 
1006 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1007                                        bool ForCodeSize) const {
1008   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1009     return false;
1010   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1011     return false;
1012   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1013     return false;
1014   if (Imm.isNegZero())
1015     return false;
1016   return Imm.isZero();
1017 }
1018 
1019 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1020   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1021          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1022          (VT == MVT::f64 && Subtarget.hasStdExtD());
1023 }
1024 
1025 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1026                                                       CallingConv::ID CC,
1027                                                       EVT VT) const {
1028   // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still
1029   // end up using a GPR but that will be decided based on ABI.
1030   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1031     return MVT::f32;
1032 
1033   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1034 }
1035 
1036 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1037                                                            CallingConv::ID CC,
1038                                                            EVT VT) const {
1039   // Use f32 to pass f16 if it is legal and Zfh is not enabled. We might still
1040   // end up using a GPR but that will be decided based on ABI.
1041   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1042     return 1;
1043 
1044   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1045 }
1046 
1047 // Changes the condition code and swaps operands if necessary, so the SetCC
1048 // operation matches one of the comparisons supported directly by branches
1049 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1050 // with 1/-1.
1051 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1052                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1053   // Convert X > -1 to X >= 0.
1054   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1055     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1056     CC = ISD::SETGE;
1057     return;
1058   }
1059   // Convert X < 1 to 0 >= X.
1060   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1061     RHS = LHS;
1062     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1063     CC = ISD::SETGE;
1064     return;
1065   }
1066 
1067   switch (CC) {
1068   default:
1069     break;
1070   case ISD::SETGT:
1071   case ISD::SETLE:
1072   case ISD::SETUGT:
1073   case ISD::SETULE:
1074     CC = ISD::getSetCCSwappedOperands(CC);
1075     std::swap(LHS, RHS);
1076     break;
1077   }
1078 }
1079 
1080 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1081   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1082   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1083   if (VT.getVectorElementType() == MVT::i1)
1084     KnownSize *= 8;
1085 
1086   switch (KnownSize) {
1087   default:
1088     llvm_unreachable("Invalid LMUL.");
1089   case 8:
1090     return RISCVII::VLMUL::LMUL_F8;
1091   case 16:
1092     return RISCVII::VLMUL::LMUL_F4;
1093   case 32:
1094     return RISCVII::VLMUL::LMUL_F2;
1095   case 64:
1096     return RISCVII::VLMUL::LMUL_1;
1097   case 128:
1098     return RISCVII::VLMUL::LMUL_2;
1099   case 256:
1100     return RISCVII::VLMUL::LMUL_4;
1101   case 512:
1102     return RISCVII::VLMUL::LMUL_8;
1103   }
1104 }
1105 
1106 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1107   switch (LMul) {
1108   default:
1109     llvm_unreachable("Invalid LMUL.");
1110   case RISCVII::VLMUL::LMUL_F8:
1111   case RISCVII::VLMUL::LMUL_F4:
1112   case RISCVII::VLMUL::LMUL_F2:
1113   case RISCVII::VLMUL::LMUL_1:
1114     return RISCV::VRRegClassID;
1115   case RISCVII::VLMUL::LMUL_2:
1116     return RISCV::VRM2RegClassID;
1117   case RISCVII::VLMUL::LMUL_4:
1118     return RISCV::VRM4RegClassID;
1119   case RISCVII::VLMUL::LMUL_8:
1120     return RISCV::VRM8RegClassID;
1121   }
1122 }
1123 
1124 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1125   RISCVII::VLMUL LMUL = getLMUL(VT);
1126   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1127       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1128       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1129       LMUL == RISCVII::VLMUL::LMUL_1) {
1130     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1131                   "Unexpected subreg numbering");
1132     return RISCV::sub_vrm1_0 + Index;
1133   }
1134   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1135     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1136                   "Unexpected subreg numbering");
1137     return RISCV::sub_vrm2_0 + Index;
1138   }
1139   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1140     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1141                   "Unexpected subreg numbering");
1142     return RISCV::sub_vrm4_0 + Index;
1143   }
1144   llvm_unreachable("Invalid vector type.");
1145 }
1146 
1147 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1148   if (VT.getVectorElementType() == MVT::i1)
1149     return RISCV::VRRegClassID;
1150   return getRegClassIDForLMUL(getLMUL(VT));
1151 }
1152 
1153 // Attempt to decompose a subvector insert/extract between VecVT and
1154 // SubVecVT via subregister indices. Returns the subregister index that
1155 // can perform the subvector insert/extract with the given element index, as
1156 // well as the index corresponding to any leftover subvectors that must be
1157 // further inserted/extracted within the register class for SubVecVT.
1158 std::pair<unsigned, unsigned>
1159 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1160     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1161     const RISCVRegisterInfo *TRI) {
1162   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1163                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1164                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1165                 "Register classes not ordered");
1166   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1167   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1168   // Try to compose a subregister index that takes us from the incoming
1169   // LMUL>1 register class down to the outgoing one. At each step we half
1170   // the LMUL:
1171   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1172   // Note that this is not guaranteed to find a subregister index, such as
1173   // when we are extracting from one VR type to another.
1174   unsigned SubRegIdx = RISCV::NoSubRegister;
1175   for (const unsigned RCID :
1176        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1177     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1178       VecVT = VecVT.getHalfNumVectorElementsVT();
1179       bool IsHi =
1180           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1181       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1182                                             getSubregIndexByMVT(VecVT, IsHi));
1183       if (IsHi)
1184         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1185     }
1186   return {SubRegIdx, InsertExtractIdx};
1187 }
1188 
1189 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1190 // stores for those types.
1191 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1192   return !Subtarget.useRVVForFixedLengthVectors() ||
1193          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1194 }
1195 
1196 static bool useRVVForFixedLengthVectorVT(MVT VT,
1197                                          const RISCVSubtarget &Subtarget) {
1198   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1199   if (!Subtarget.useRVVForFixedLengthVectors())
1200     return false;
1201 
1202   // We only support a set of vector types with a consistent maximum fixed size
1203   // across all supported vector element types to avoid legalization issues.
1204   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1205   // fixed-length vector type we support is 1024 bytes.
1206   if (VT.getFixedSizeInBits() > 1024 * 8)
1207     return false;
1208 
1209   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1210 
1211   MVT EltVT = VT.getVectorElementType();
1212 
1213   // Don't use RVV for vectors we cannot scalarize if required.
1214   switch (EltVT.SimpleTy) {
1215   // i1 is supported but has different rules.
1216   default:
1217     return false;
1218   case MVT::i1:
1219     // Masks can only use a single register.
1220     if (VT.getVectorNumElements() > MinVLen)
1221       return false;
1222     MinVLen /= 8;
1223     break;
1224   case MVT::i8:
1225   case MVT::i16:
1226   case MVT::i32:
1227   case MVT::i64:
1228     break;
1229   case MVT::f16:
1230     if (!Subtarget.hasStdExtZfh())
1231       return false;
1232     break;
1233   case MVT::f32:
1234     if (!Subtarget.hasStdExtF())
1235       return false;
1236     break;
1237   case MVT::f64:
1238     if (!Subtarget.hasStdExtD())
1239       return false;
1240     break;
1241   }
1242 
1243   // Reject elements larger than ELEN.
1244   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1245     return false;
1246 
1247   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1248   // Don't use RVV for types that don't fit.
1249   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1250     return false;
1251 
1252   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1253   // the base fixed length RVV support in place.
1254   if (!VT.isPow2VectorType())
1255     return false;
1256 
1257   return true;
1258 }
1259 
1260 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1261   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1262 }
1263 
1264 // Return the largest legal scalable vector type that matches VT's element type.
1265 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1266                                             const RISCVSubtarget &Subtarget) {
1267   // This may be called before legal types are setup.
1268   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1269           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1270          "Expected legal fixed length vector!");
1271 
1272   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1273   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1274 
1275   MVT EltVT = VT.getVectorElementType();
1276   switch (EltVT.SimpleTy) {
1277   default:
1278     llvm_unreachable("unexpected element type for RVV container");
1279   case MVT::i1:
1280   case MVT::i8:
1281   case MVT::i16:
1282   case MVT::i32:
1283   case MVT::i64:
1284   case MVT::f16:
1285   case MVT::f32:
1286   case MVT::f64: {
1287     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1288     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1289     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1290     unsigned NumElts =
1291         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1292     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1293     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1294     return MVT::getScalableVectorVT(EltVT, NumElts);
1295   }
1296   }
1297 }
1298 
1299 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1300                                             const RISCVSubtarget &Subtarget) {
1301   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1302                                           Subtarget);
1303 }
1304 
1305 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1306   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1307 }
1308 
1309 // Grow V to consume an entire RVV register.
1310 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1311                                        const RISCVSubtarget &Subtarget) {
1312   assert(VT.isScalableVector() &&
1313          "Expected to convert into a scalable vector!");
1314   assert(V.getValueType().isFixedLengthVector() &&
1315          "Expected a fixed length vector operand!");
1316   SDLoc DL(V);
1317   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1318   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1319 }
1320 
1321 // Shrink V so it's just big enough to maintain a VT's worth of data.
1322 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1323                                          const RISCVSubtarget &Subtarget) {
1324   assert(VT.isFixedLengthVector() &&
1325          "Expected to convert into a fixed length vector!");
1326   assert(V.getValueType().isScalableVector() &&
1327          "Expected a scalable vector operand!");
1328   SDLoc DL(V);
1329   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1330   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1331 }
1332 
1333 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1334 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1335 // the vector type that it is contained in.
1336 static std::pair<SDValue, SDValue>
1337 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1338                 const RISCVSubtarget &Subtarget) {
1339   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1340   MVT XLenVT = Subtarget.getXLenVT();
1341   SDValue VL = VecVT.isFixedLengthVector()
1342                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1343                    : DAG.getRegister(RISCV::X0, XLenVT);
1344   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1345   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1346   return {Mask, VL};
1347 }
1348 
1349 // As above but assuming the given type is a scalable vector type.
1350 static std::pair<SDValue, SDValue>
1351 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1352                         const RISCVSubtarget &Subtarget) {
1353   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1354   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1355 }
1356 
1357 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1358 // of either is (currently) supported. This can get us into an infinite loop
1359 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1360 // as a ..., etc.
1361 // Until either (or both) of these can reliably lower any node, reporting that
1362 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1363 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1364 // which is not desirable.
1365 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1366     EVT VT, unsigned DefinedValues) const {
1367   return false;
1368 }
1369 
1370 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1371   // Only splats are currently supported.
1372   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1373     return true;
1374 
1375   return false;
1376 }
1377 
1378 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG) {
1379   // RISCV FP-to-int conversions saturate to the destination register size, but
1380   // don't produce 0 for nan. We can use a conversion instruction and fix the
1381   // nan case with a compare and a select.
1382   SDValue Src = Op.getOperand(0);
1383 
1384   EVT DstVT = Op.getValueType();
1385   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1386 
1387   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1388   unsigned Opc;
1389   if (SatVT == DstVT)
1390     Opc = IsSigned ? RISCVISD::FCVT_X_RTZ : RISCVISD::FCVT_XU_RTZ;
1391   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1392     Opc = IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
1393   else
1394     return SDValue();
1395   // FIXME: Support other SatVTs by clamping before or after the conversion.
1396 
1397   SDLoc DL(Op);
1398   SDValue FpToInt = DAG.getNode(Opc, DL, DstVT, Src);
1399 
1400   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1401   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1402 }
1403 
1404 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1405                                  const RISCVSubtarget &Subtarget) {
1406   MVT VT = Op.getSimpleValueType();
1407   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1408 
1409   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1410 
1411   SDLoc DL(Op);
1412   SDValue Mask, VL;
1413   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1414 
1415   unsigned Opc =
1416       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1417   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1418   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1419 }
1420 
1421 struct VIDSequence {
1422   int64_t StepNumerator;
1423   unsigned StepDenominator;
1424   int64_t Addend;
1425 };
1426 
1427 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1428 // to the (non-zero) step S and start value X. This can be then lowered as the
1429 // RVV sequence (VID * S) + X, for example.
1430 // The step S is represented as an integer numerator divided by a positive
1431 // denominator. Note that the implementation currently only identifies
1432 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1433 // cannot detect 2/3, for example.
1434 // Note that this method will also match potentially unappealing index
1435 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1436 // determine whether this is worth generating code for.
1437 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1438   unsigned NumElts = Op.getNumOperands();
1439   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1440   if (!Op.getValueType().isInteger())
1441     return None;
1442 
1443   Optional<unsigned> SeqStepDenom;
1444   Optional<int64_t> SeqStepNum, SeqAddend;
1445   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1446   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1447   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1448     // Assume undef elements match the sequence; we just have to be careful
1449     // when interpolating across them.
1450     if (Op.getOperand(Idx).isUndef())
1451       continue;
1452     // The BUILD_VECTOR must be all constants.
1453     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1454       return None;
1455 
1456     uint64_t Val = Op.getConstantOperandVal(Idx) &
1457                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1458 
1459     if (PrevElt) {
1460       // Calculate the step since the last non-undef element, and ensure
1461       // it's consistent across the entire sequence.
1462       unsigned IdxDiff = Idx - PrevElt->second;
1463       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1464 
1465       // A zero-value value difference means that we're somewhere in the middle
1466       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1467       // step change before evaluating the sequence.
1468       if (ValDiff != 0) {
1469         int64_t Remainder = ValDiff % IdxDiff;
1470         // Normalize the step if it's greater than 1.
1471         if (Remainder != ValDiff) {
1472           // The difference must cleanly divide the element span.
1473           if (Remainder != 0)
1474             return None;
1475           ValDiff /= IdxDiff;
1476           IdxDiff = 1;
1477         }
1478 
1479         if (!SeqStepNum)
1480           SeqStepNum = ValDiff;
1481         else if (ValDiff != SeqStepNum)
1482           return None;
1483 
1484         if (!SeqStepDenom)
1485           SeqStepDenom = IdxDiff;
1486         else if (IdxDiff != *SeqStepDenom)
1487           return None;
1488       }
1489     }
1490 
1491     // Record and/or check any addend.
1492     if (SeqStepNum && SeqStepDenom) {
1493       uint64_t ExpectedVal =
1494           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1495       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1496       if (!SeqAddend)
1497         SeqAddend = Addend;
1498       else if (SeqAddend != Addend)
1499         return None;
1500     }
1501 
1502     // Record this non-undef element for later.
1503     if (!PrevElt || PrevElt->first != Val)
1504       PrevElt = std::make_pair(Val, Idx);
1505   }
1506   // We need to have logged both a step and an addend for this to count as
1507   // a legal index sequence.
1508   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1509     return None;
1510 
1511   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1512 }
1513 
1514 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1515                                  const RISCVSubtarget &Subtarget) {
1516   MVT VT = Op.getSimpleValueType();
1517   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1518 
1519   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1520 
1521   SDLoc DL(Op);
1522   SDValue Mask, VL;
1523   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1524 
1525   MVT XLenVT = Subtarget.getXLenVT();
1526   unsigned NumElts = Op.getNumOperands();
1527 
1528   if (VT.getVectorElementType() == MVT::i1) {
1529     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1530       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1531       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1532     }
1533 
1534     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1535       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1536       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1537     }
1538 
1539     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1540     // scalar integer chunks whose bit-width depends on the number of mask
1541     // bits and XLEN.
1542     // First, determine the most appropriate scalar integer type to use. This
1543     // is at most XLenVT, but may be shrunk to a smaller vector element type
1544     // according to the size of the final vector - use i8 chunks rather than
1545     // XLenVT if we're producing a v8i1. This results in more consistent
1546     // codegen across RV32 and RV64.
1547     unsigned NumViaIntegerBits =
1548         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1549     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1550       // If we have to use more than one INSERT_VECTOR_ELT then this
1551       // optimization is likely to increase code size; avoid peforming it in
1552       // such a case. We can use a load from a constant pool in this case.
1553       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1554         return SDValue();
1555       // Now we can create our integer vector type. Note that it may be larger
1556       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
1557       MVT IntegerViaVecVT =
1558           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
1559                            divideCeil(NumElts, NumViaIntegerBits));
1560 
1561       uint64_t Bits = 0;
1562       unsigned BitPos = 0, IntegerEltIdx = 0;
1563       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
1564 
1565       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
1566         // Once we accumulate enough bits to fill our scalar type, insert into
1567         // our vector and clear our accumulated data.
1568         if (I != 0 && I % NumViaIntegerBits == 0) {
1569           if (NumViaIntegerBits <= 32)
1570             Bits = SignExtend64(Bits, 32);
1571           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1572           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
1573                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1574           Bits = 0;
1575           BitPos = 0;
1576           IntegerEltIdx++;
1577         }
1578         SDValue V = Op.getOperand(I);
1579         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
1580         Bits |= ((uint64_t)BitValue << BitPos);
1581       }
1582 
1583       // Insert the (remaining) scalar value into position in our integer
1584       // vector type.
1585       if (NumViaIntegerBits <= 32)
1586         Bits = SignExtend64(Bits, 32);
1587       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
1588       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
1589                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
1590 
1591       if (NumElts < NumViaIntegerBits) {
1592         // If we're producing a smaller vector than our minimum legal integer
1593         // type, bitcast to the equivalent (known-legal) mask type, and extract
1594         // our final mask.
1595         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
1596         Vec = DAG.getBitcast(MVT::v8i1, Vec);
1597         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
1598                           DAG.getConstant(0, DL, XLenVT));
1599       } else {
1600         // Else we must have produced an integer type with the same size as the
1601         // mask type; bitcast for the final result.
1602         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
1603         Vec = DAG.getBitcast(VT, Vec);
1604       }
1605 
1606       return Vec;
1607     }
1608 
1609     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
1610     // vector type, we have a legal equivalently-sized i8 type, so we can use
1611     // that.
1612     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
1613     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
1614 
1615     SDValue WideVec;
1616     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1617       // For a splat, perform a scalar truncate before creating the wider
1618       // vector.
1619       assert(Splat.getValueType() == XLenVT &&
1620              "Unexpected type for i1 splat value");
1621       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
1622                           DAG.getConstant(1, DL, XLenVT));
1623       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
1624     } else {
1625       SmallVector<SDValue, 8> Ops(Op->op_values());
1626       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
1627       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
1628       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
1629     }
1630 
1631     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
1632   }
1633 
1634   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
1635     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
1636                                         : RISCVISD::VMV_V_X_VL;
1637     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
1638     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1639   }
1640 
1641   // Try and match index sequences, which we can lower to the vid instruction
1642   // with optional modifications. An all-undef vector is matched by
1643   // getSplatValue, above.
1644   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
1645     int64_t StepNumerator = SimpleVID->StepNumerator;
1646     unsigned StepDenominator = SimpleVID->StepDenominator;
1647     int64_t Addend = SimpleVID->Addend;
1648     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
1649     // threshold since it's the immediate value many RVV instructions accept.
1650     if (isInt<5>(StepNumerator) && isPowerOf2_32(StepDenominator) &&
1651         isInt<5>(Addend)) {
1652       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
1653       // Convert right out of the scalable type so we can use standard ISD
1654       // nodes for the rest of the computation. If we used scalable types with
1655       // these, we'd lose the fixed-length vector info and generate worse
1656       // vsetvli code.
1657       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
1658       assert(StepNumerator != 0 && "Invalid step");
1659       bool Negate = false;
1660       if (StepNumerator != 1) {
1661         int64_t SplatStepVal = StepNumerator;
1662         unsigned Opcode = ISD::MUL;
1663         if (isPowerOf2_64(std::abs(StepNumerator))) {
1664           Negate = StepNumerator < 0;
1665           Opcode = ISD::SHL;
1666           SplatStepVal = Log2_64(std::abs(StepNumerator));
1667         }
1668         SDValue SplatStep = DAG.getSplatVector(
1669             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
1670         VID = DAG.getNode(Opcode, DL, VT, VID, SplatStep);
1671       }
1672       if (StepDenominator != 1) {
1673         SDValue SplatStep = DAG.getSplatVector(
1674             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
1675         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
1676       }
1677       if (Addend != 0 || Negate) {
1678         SDValue SplatAddend =
1679             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
1680         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
1681       }
1682       return VID;
1683     }
1684   }
1685 
1686   // Attempt to detect "hidden" splats, which only reveal themselves as splats
1687   // when re-interpreted as a vector with a larger element type. For example,
1688   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
1689   // could be instead splat as
1690   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
1691   // TODO: This optimization could also work on non-constant splats, but it
1692   // would require bit-manipulation instructions to construct the splat value.
1693   SmallVector<SDValue> Sequence;
1694   unsigned EltBitSize = VT.getScalarSizeInBits();
1695   const auto *BV = cast<BuildVectorSDNode>(Op);
1696   if (VT.isInteger() && EltBitSize < 64 &&
1697       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
1698       BV->getRepeatedSequence(Sequence) &&
1699       (Sequence.size() * EltBitSize) <= 64) {
1700     unsigned SeqLen = Sequence.size();
1701     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
1702     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
1703     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
1704             ViaIntVT == MVT::i64) &&
1705            "Unexpected sequence type");
1706 
1707     unsigned EltIdx = 0;
1708     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
1709     uint64_t SplatValue = 0;
1710     // Construct the amalgamated value which can be splatted as this larger
1711     // vector type.
1712     for (const auto &SeqV : Sequence) {
1713       if (!SeqV.isUndef())
1714         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
1715                        << (EltIdx * EltBitSize));
1716       EltIdx++;
1717     }
1718 
1719     // On RV64, sign-extend from 32 to 64 bits where possible in order to
1720     // achieve better constant materializion.
1721     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
1722       SplatValue = SignExtend64(SplatValue, 32);
1723 
1724     // Since we can't introduce illegal i64 types at this stage, we can only
1725     // perform an i64 splat on RV32 if it is its own sign-extended value. That
1726     // way we can use RVV instructions to splat.
1727     assert((ViaIntVT.bitsLE(XLenVT) ||
1728             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
1729            "Unexpected bitcast sequence");
1730     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
1731       SDValue ViaVL =
1732           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
1733       MVT ViaContainerVT =
1734           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
1735       SDValue Splat =
1736           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
1737                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
1738       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
1739       return DAG.getBitcast(VT, Splat);
1740     }
1741   }
1742 
1743   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
1744   // which constitute a large proportion of the elements. In such cases we can
1745   // splat a vector with the dominant element and make up the shortfall with
1746   // INSERT_VECTOR_ELTs.
1747   // Note that this includes vectors of 2 elements by association. The
1748   // upper-most element is the "dominant" one, allowing us to use a splat to
1749   // "insert" the upper element, and an insert of the lower element at position
1750   // 0, which improves codegen.
1751   SDValue DominantValue;
1752   unsigned MostCommonCount = 0;
1753   DenseMap<SDValue, unsigned> ValueCounts;
1754   unsigned NumUndefElts =
1755       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
1756 
1757   // Track the number of scalar loads we know we'd be inserting, estimated as
1758   // any non-zero floating-point constant. Other kinds of element are either
1759   // already in registers or are materialized on demand. The threshold at which
1760   // a vector load is more desirable than several scalar materializion and
1761   // vector-insertion instructions is not known.
1762   unsigned NumScalarLoads = 0;
1763 
1764   for (SDValue V : Op->op_values()) {
1765     if (V.isUndef())
1766       continue;
1767 
1768     ValueCounts.insert(std::make_pair(V, 0));
1769     unsigned &Count = ValueCounts[V];
1770 
1771     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
1772       NumScalarLoads += !CFP->isExactlyValue(+0.0);
1773 
1774     // Is this value dominant? In case of a tie, prefer the highest element as
1775     // it's cheaper to insert near the beginning of a vector than it is at the
1776     // end.
1777     if (++Count >= MostCommonCount) {
1778       DominantValue = V;
1779       MostCommonCount = Count;
1780     }
1781   }
1782 
1783   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
1784   unsigned NumDefElts = NumElts - NumUndefElts;
1785   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
1786 
1787   // Don't perform this optimization when optimizing for size, since
1788   // materializing elements and inserting them tends to cause code bloat.
1789   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
1790       ((MostCommonCount > DominantValueCountThreshold) ||
1791        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
1792     // Start by splatting the most common element.
1793     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
1794 
1795     DenseSet<SDValue> Processed{DominantValue};
1796     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
1797     for (const auto &OpIdx : enumerate(Op->ops())) {
1798       const SDValue &V = OpIdx.value();
1799       if (V.isUndef() || !Processed.insert(V).second)
1800         continue;
1801       if (ValueCounts[V] == 1) {
1802         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
1803                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
1804       } else {
1805         // Blend in all instances of this value using a VSELECT, using a
1806         // mask where each bit signals whether that element is the one
1807         // we're after.
1808         SmallVector<SDValue> Ops;
1809         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
1810           return DAG.getConstant(V == V1, DL, XLenVT);
1811         });
1812         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
1813                           DAG.getBuildVector(SelMaskTy, DL, Ops),
1814                           DAG.getSplatBuildVector(VT, DL, V), Vec);
1815       }
1816     }
1817 
1818     return Vec;
1819   }
1820 
1821   return SDValue();
1822 }
1823 
1824 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
1825                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
1826   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
1827     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
1828     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
1829     // If Hi constant is all the same sign bit as Lo, lower this as a custom
1830     // node in order to try and match RVV vector/scalar instructions.
1831     if ((LoC >> 31) == HiC)
1832       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
1833   }
1834 
1835   // Fall back to a stack store and stride x0 vector load.
1836   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
1837 }
1838 
1839 // Called by type legalization to handle splat of i64 on RV32.
1840 // FIXME: We can optimize this when the type has sign or zero bits in one
1841 // of the halves.
1842 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
1843                                    SDValue VL, SelectionDAG &DAG) {
1844   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
1845   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
1846                            DAG.getConstant(0, DL, MVT::i32));
1847   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
1848                            DAG.getConstant(1, DL, MVT::i32));
1849   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
1850 }
1851 
1852 // This function lowers a splat of a scalar operand Splat with the vector
1853 // length VL. It ensures the final sequence is type legal, which is useful when
1854 // lowering a splat after type legalization.
1855 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
1856                                 SelectionDAG &DAG,
1857                                 const RISCVSubtarget &Subtarget) {
1858   if (VT.isFloatingPoint())
1859     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
1860 
1861   MVT XLenVT = Subtarget.getXLenVT();
1862 
1863   // Simplest case is that the operand needs to be promoted to XLenVT.
1864   if (Scalar.getValueType().bitsLE(XLenVT)) {
1865     // If the operand is a constant, sign extend to increase our chances
1866     // of being able to use a .vi instruction. ANY_EXTEND would become a
1867     // a zero extend and the simm5 check in isel would fail.
1868     // FIXME: Should we ignore the upper bits in isel instead?
1869     unsigned ExtOpc =
1870         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
1871     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
1872     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
1873   }
1874 
1875   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
1876          "Unexpected scalar for splat lowering!");
1877 
1878   // Otherwise use the more complicated splatting algorithm.
1879   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
1880 }
1881 
1882 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
1883                                    const RISCVSubtarget &Subtarget) {
1884   SDValue V1 = Op.getOperand(0);
1885   SDValue V2 = Op.getOperand(1);
1886   SDLoc DL(Op);
1887   MVT XLenVT = Subtarget.getXLenVT();
1888   MVT VT = Op.getSimpleValueType();
1889   unsigned NumElts = VT.getVectorNumElements();
1890   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
1891 
1892   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1893 
1894   SDValue TrueMask, VL;
1895   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1896 
1897   if (SVN->isSplat()) {
1898     const int Lane = SVN->getSplatIndex();
1899     if (Lane >= 0) {
1900       MVT SVT = VT.getVectorElementType();
1901 
1902       // Turn splatted vector load into a strided load with an X0 stride.
1903       SDValue V = V1;
1904       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
1905       // with undef.
1906       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
1907       int Offset = Lane;
1908       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
1909         int OpElements =
1910             V.getOperand(0).getSimpleValueType().getVectorNumElements();
1911         V = V.getOperand(Offset / OpElements);
1912         Offset %= OpElements;
1913       }
1914 
1915       // We need to ensure the load isn't atomic or volatile.
1916       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
1917         auto *Ld = cast<LoadSDNode>(V);
1918         Offset *= SVT.getStoreSize();
1919         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
1920                                                    TypeSize::Fixed(Offset), DL);
1921 
1922         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
1923         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
1924           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
1925           SDValue IntID =
1926               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
1927           SDValue Ops[] = {Ld->getChain(), IntID, NewAddr,
1928                            DAG.getRegister(RISCV::X0, XLenVT), VL};
1929           SDValue NewLoad = DAG.getMemIntrinsicNode(
1930               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
1931               DAG.getMachineFunction().getMachineMemOperand(
1932                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
1933           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
1934           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
1935         }
1936 
1937         // Otherwise use a scalar load and splat. This will give the best
1938         // opportunity to fold a splat into the operation. ISel can turn it into
1939         // the x0 strided load if we aren't able to fold away the select.
1940         if (SVT.isFloatingPoint())
1941           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
1942                           Ld->getPointerInfo().getWithOffset(Offset),
1943                           Ld->getOriginalAlign(),
1944                           Ld->getMemOperand()->getFlags());
1945         else
1946           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
1947                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
1948                              Ld->getOriginalAlign(),
1949                              Ld->getMemOperand()->getFlags());
1950         DAG.makeEquivalentMemoryOrdering(Ld, V);
1951 
1952         unsigned Opc =
1953             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1954         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
1955         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1956       }
1957 
1958       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
1959       assert(Lane < (int)NumElts && "Unexpected lane!");
1960       SDValue Gather =
1961           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
1962                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
1963       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
1964     }
1965   }
1966 
1967   // Detect shuffles which can be re-expressed as vector selects; these are
1968   // shuffles in which each element in the destination is taken from an element
1969   // at the corresponding index in either source vectors.
1970   bool IsSelect = all_of(enumerate(SVN->getMask()), [&](const auto &MaskIdx) {
1971     int MaskIndex = MaskIdx.value();
1972     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
1973   });
1974 
1975   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
1976 
1977   SmallVector<SDValue> MaskVals;
1978   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
1979   // merged with a second vrgather.
1980   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
1981 
1982   // By default we preserve the original operand order, and use a mask to
1983   // select LHS as true and RHS as false. However, since RVV vector selects may
1984   // feature splats but only on the LHS, we may choose to invert our mask and
1985   // instead select between RHS and LHS.
1986   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
1987   bool InvertMask = IsSelect == SwapOps;
1988 
1989   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
1990   // half.
1991   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
1992 
1993   // Now construct the mask that will be used by the vselect or blended
1994   // vrgather operation. For vrgathers, construct the appropriate indices into
1995   // each vector.
1996   for (int MaskIndex : SVN->getMask()) {
1997     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
1998     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
1999     if (!IsSelect) {
2000       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2001       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2002                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2003                                      : DAG.getUNDEF(XLenVT));
2004       GatherIndicesRHS.push_back(
2005           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2006                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2007       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2008         ++LHSIndexCounts[MaskIndex];
2009       if (!IsLHSOrUndefIndex)
2010         ++RHSIndexCounts[MaskIndex - NumElts];
2011     }
2012   }
2013 
2014   if (SwapOps) {
2015     std::swap(V1, V2);
2016     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2017   }
2018 
2019   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2020   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2021   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2022 
2023   if (IsSelect)
2024     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2025 
2026   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2027     // On such a large vector we're unable to use i8 as the index type.
2028     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2029     // may involve vector splitting if we're already at LMUL=8, or our
2030     // user-supplied maximum fixed-length LMUL.
2031     return SDValue();
2032   }
2033 
2034   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2035   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2036   MVT IndexVT = VT.changeTypeToInteger();
2037   // Since we can't introduce illegal index types at this stage, use i16 and
2038   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2039   // than XLenVT.
2040   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2041     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2042     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2043   }
2044 
2045   MVT IndexContainerVT =
2046       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2047 
2048   SDValue Gather;
2049   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2050   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2051   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2052     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2053   } else {
2054     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2055     // If only one index is used, we can use a "splat" vrgather.
2056     // TODO: We can splat the most-common index and fix-up any stragglers, if
2057     // that's beneficial.
2058     if (LHSIndexCounts.size() == 1) {
2059       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2060       Gather =
2061           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2062                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2063     } else {
2064       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2065       LHSIndices =
2066           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2067 
2068       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2069                            TrueMask, VL);
2070     }
2071   }
2072 
2073   // If a second vector operand is used by this shuffle, blend it in with an
2074   // additional vrgather.
2075   if (!V2.isUndef()) {
2076     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2077     // If only one index is used, we can use a "splat" vrgather.
2078     // TODO: We can splat the most-common index and fix-up any stragglers, if
2079     // that's beneficial.
2080     if (RHSIndexCounts.size() == 1) {
2081       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2082       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2083                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2084     } else {
2085       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2086       RHSIndices =
2087           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2088       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2089                        VL);
2090     }
2091 
2092     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2093     SelectMask =
2094         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2095 
2096     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2097                          Gather, VL);
2098   }
2099 
2100   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2101 }
2102 
2103 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2104                                      SDLoc DL, SelectionDAG &DAG,
2105                                      const RISCVSubtarget &Subtarget) {
2106   if (VT.isScalableVector())
2107     return DAG.getFPExtendOrRound(Op, DL, VT);
2108   assert(VT.isFixedLengthVector() &&
2109          "Unexpected value type for RVV FP extend/round lowering");
2110   SDValue Mask, VL;
2111   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2112   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2113                         ? RISCVISD::FP_EXTEND_VL
2114                         : RISCVISD::FP_ROUND_VL;
2115   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2116 }
2117 
2118 // While RVV has alignment restrictions, we should always be able to load as a
2119 // legal equivalently-sized byte-typed vector instead. This method is
2120 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2121 // the load is already correctly-aligned, it returns SDValue().
2122 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2123                                                     SelectionDAG &DAG) const {
2124   auto *Load = cast<LoadSDNode>(Op);
2125   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2126 
2127   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2128                                      Load->getMemoryVT(),
2129                                      *Load->getMemOperand()))
2130     return SDValue();
2131 
2132   SDLoc DL(Op);
2133   MVT VT = Op.getSimpleValueType();
2134   unsigned EltSizeBits = VT.getScalarSizeInBits();
2135   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2136          "Unexpected unaligned RVV load type");
2137   MVT NewVT =
2138       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2139   assert(NewVT.isValid() &&
2140          "Expecting equally-sized RVV vector types to be legal");
2141   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2142                           Load->getPointerInfo(), Load->getOriginalAlign(),
2143                           Load->getMemOperand()->getFlags());
2144   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2145 }
2146 
2147 // While RVV has alignment restrictions, we should always be able to store as a
2148 // legal equivalently-sized byte-typed vector instead. This method is
2149 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2150 // returns SDValue() if the store is already correctly aligned.
2151 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2152                                                      SelectionDAG &DAG) const {
2153   auto *Store = cast<StoreSDNode>(Op);
2154   assert(Store && Store->getValue().getValueType().isVector() &&
2155          "Expected vector store");
2156 
2157   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2158                                      Store->getMemoryVT(),
2159                                      *Store->getMemOperand()))
2160     return SDValue();
2161 
2162   SDLoc DL(Op);
2163   SDValue StoredVal = Store->getValue();
2164   MVT VT = StoredVal.getSimpleValueType();
2165   unsigned EltSizeBits = VT.getScalarSizeInBits();
2166   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2167          "Unexpected unaligned RVV store type");
2168   MVT NewVT =
2169       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2170   assert(NewVT.isValid() &&
2171          "Expecting equally-sized RVV vector types to be legal");
2172   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2173   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2174                       Store->getPointerInfo(), Store->getOriginalAlign(),
2175                       Store->getMemOperand()->getFlags());
2176 }
2177 
2178 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2179                                             SelectionDAG &DAG) const {
2180   switch (Op.getOpcode()) {
2181   default:
2182     report_fatal_error("unimplemented operand");
2183   case ISD::GlobalAddress:
2184     return lowerGlobalAddress(Op, DAG);
2185   case ISD::BlockAddress:
2186     return lowerBlockAddress(Op, DAG);
2187   case ISD::ConstantPool:
2188     return lowerConstantPool(Op, DAG);
2189   case ISD::JumpTable:
2190     return lowerJumpTable(Op, DAG);
2191   case ISD::GlobalTLSAddress:
2192     return lowerGlobalTLSAddress(Op, DAG);
2193   case ISD::SELECT:
2194     return lowerSELECT(Op, DAG);
2195   case ISD::BRCOND:
2196     return lowerBRCOND(Op, DAG);
2197   case ISD::VASTART:
2198     return lowerVASTART(Op, DAG);
2199   case ISD::FRAMEADDR:
2200     return lowerFRAMEADDR(Op, DAG);
2201   case ISD::RETURNADDR:
2202     return lowerRETURNADDR(Op, DAG);
2203   case ISD::SHL_PARTS:
2204     return lowerShiftLeftParts(Op, DAG);
2205   case ISD::SRA_PARTS:
2206     return lowerShiftRightParts(Op, DAG, true);
2207   case ISD::SRL_PARTS:
2208     return lowerShiftRightParts(Op, DAG, false);
2209   case ISD::BITCAST: {
2210     SDLoc DL(Op);
2211     EVT VT = Op.getValueType();
2212     SDValue Op0 = Op.getOperand(0);
2213     EVT Op0VT = Op0.getValueType();
2214     MVT XLenVT = Subtarget.getXLenVT();
2215     if (VT.isFixedLengthVector()) {
2216       // We can handle fixed length vector bitcasts with a simple replacement
2217       // in isel.
2218       if (Op0VT.isFixedLengthVector())
2219         return Op;
2220       // When bitcasting from scalar to fixed-length vector, insert the scalar
2221       // into a one-element vector of the result type, and perform a vector
2222       // bitcast.
2223       if (!Op0VT.isVector()) {
2224         auto BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2225         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2226                                               DAG.getUNDEF(BVT), Op0,
2227                                               DAG.getConstant(0, DL, XLenVT)));
2228       }
2229       return SDValue();
2230     }
2231     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2232     // thus: bitcast the vector to a one-element vector type whose element type
2233     // is the same as the result type, and extract the first element.
2234     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2235       LLVMContext &Context = *DAG.getContext();
2236       SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0);
2237       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2238                          DAG.getConstant(0, DL, XLenVT));
2239     }
2240     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2241       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2242       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2243       return FPConv;
2244     }
2245     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2246         Subtarget.hasStdExtF()) {
2247       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2248       SDValue FPConv =
2249           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2250       return FPConv;
2251     }
2252     return SDValue();
2253   }
2254   case ISD::INTRINSIC_WO_CHAIN:
2255     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2256   case ISD::INTRINSIC_W_CHAIN:
2257     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2258   case ISD::BSWAP:
2259   case ISD::BITREVERSE: {
2260     // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2261     assert(Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
2262     MVT VT = Op.getSimpleValueType();
2263     SDLoc DL(Op);
2264     // Start with the maximum immediate value which is the bitwidth - 1.
2265     unsigned Imm = VT.getSizeInBits() - 1;
2266     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2267     if (Op.getOpcode() == ISD::BSWAP)
2268       Imm &= ~0x7U;
2269     return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2270                        DAG.getConstant(Imm, DL, VT));
2271   }
2272   case ISD::FSHL:
2273   case ISD::FSHR: {
2274     MVT VT = Op.getSimpleValueType();
2275     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2276     SDLoc DL(Op);
2277     if (Op.getOperand(2).getOpcode() == ISD::Constant)
2278       return Op;
2279     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2280     // use log(XLen) bits. Mask the shift amount accordingly.
2281     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2282     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2283                                 DAG.getConstant(ShAmtWidth, DL, VT));
2284     unsigned Opc = Op.getOpcode() == ISD::FSHL ? RISCVISD::FSL : RISCVISD::FSR;
2285     return DAG.getNode(Opc, DL, VT, Op.getOperand(0), Op.getOperand(1), ShAmt);
2286   }
2287   case ISD::TRUNCATE: {
2288     SDLoc DL(Op);
2289     MVT VT = Op.getSimpleValueType();
2290     // Only custom-lower vector truncates
2291     if (!VT.isVector())
2292       return Op;
2293 
2294     // Truncates to mask types are handled differently
2295     if (VT.getVectorElementType() == MVT::i1)
2296       return lowerVectorMaskTrunc(Op, DAG);
2297 
2298     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
2299     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
2300     // truncate by one power of two at a time.
2301     MVT DstEltVT = VT.getVectorElementType();
2302 
2303     SDValue Src = Op.getOperand(0);
2304     MVT SrcVT = Src.getSimpleValueType();
2305     MVT SrcEltVT = SrcVT.getVectorElementType();
2306 
2307     assert(DstEltVT.bitsLT(SrcEltVT) &&
2308            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
2309            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
2310            "Unexpected vector truncate lowering");
2311 
2312     MVT ContainerVT = SrcVT;
2313     if (SrcVT.isFixedLengthVector()) {
2314       ContainerVT = getContainerForFixedLengthVector(SrcVT);
2315       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
2316     }
2317 
2318     SDValue Result = Src;
2319     SDValue Mask, VL;
2320     std::tie(Mask, VL) =
2321         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
2322     LLVMContext &Context = *DAG.getContext();
2323     const ElementCount Count = ContainerVT.getVectorElementCount();
2324     do {
2325       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
2326       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
2327       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
2328                            Mask, VL);
2329     } while (SrcEltVT != DstEltVT);
2330 
2331     if (SrcVT.isFixedLengthVector())
2332       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
2333 
2334     return Result;
2335   }
2336   case ISD::ANY_EXTEND:
2337   case ISD::ZERO_EXTEND:
2338     if (Op.getOperand(0).getValueType().isVector() &&
2339         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2340       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
2341     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
2342   case ISD::SIGN_EXTEND:
2343     if (Op.getOperand(0).getValueType().isVector() &&
2344         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2345       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
2346     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
2347   case ISD::SPLAT_VECTOR_PARTS:
2348     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
2349   case ISD::INSERT_VECTOR_ELT:
2350     return lowerINSERT_VECTOR_ELT(Op, DAG);
2351   case ISD::EXTRACT_VECTOR_ELT:
2352     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
2353   case ISD::VSCALE: {
2354     MVT VT = Op.getSimpleValueType();
2355     SDLoc DL(Op);
2356     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
2357     // We define our scalable vector types for lmul=1 to use a 64 bit known
2358     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
2359     // vscale as VLENB / 8.
2360     assert(RISCV::RVVBitsPerBlock == 64 && "Unexpected bits per block!");
2361     if (isa<ConstantSDNode>(Op.getOperand(0))) {
2362       // We assume VLENB is a multiple of 8. We manually choose the best shift
2363       // here because SimplifyDemandedBits isn't always able to simplify it.
2364       uint64_t Val = Op.getConstantOperandVal(0);
2365       if (isPowerOf2_64(Val)) {
2366         uint64_t Log2 = Log2_64(Val);
2367         if (Log2 < 3)
2368           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
2369                              DAG.getConstant(3 - Log2, DL, VT));
2370         if (Log2 > 3)
2371           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
2372                              DAG.getConstant(Log2 - 3, DL, VT));
2373         return VLENB;
2374       }
2375       // If the multiplier is a multiple of 8, scale it down to avoid needing
2376       // to shift the VLENB value.
2377       if ((Val % 8) == 0)
2378         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
2379                            DAG.getConstant(Val / 8, DL, VT));
2380     }
2381 
2382     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
2383                                  DAG.getConstant(3, DL, VT));
2384     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
2385   }
2386   case ISD::FP_EXTEND: {
2387     // RVV can only do fp_extend to types double the size as the source. We
2388     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
2389     // via f32.
2390     SDLoc DL(Op);
2391     MVT VT = Op.getSimpleValueType();
2392     SDValue Src = Op.getOperand(0);
2393     MVT SrcVT = Src.getSimpleValueType();
2394 
2395     // Prepare any fixed-length vector operands.
2396     MVT ContainerVT = VT;
2397     if (SrcVT.isFixedLengthVector()) {
2398       ContainerVT = getContainerForFixedLengthVector(VT);
2399       MVT SrcContainerVT =
2400           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
2401       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2402     }
2403 
2404     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
2405         SrcVT.getVectorElementType() != MVT::f16) {
2406       // For scalable vectors, we only need to close the gap between
2407       // vXf16->vXf64.
2408       if (!VT.isFixedLengthVector())
2409         return Op;
2410       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
2411       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2412       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2413     }
2414 
2415     MVT InterVT = VT.changeVectorElementType(MVT::f32);
2416     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
2417     SDValue IntermediateExtend = getRVVFPExtendOrRound(
2418         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
2419 
2420     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
2421                                            DL, DAG, Subtarget);
2422     if (VT.isFixedLengthVector())
2423       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
2424     return Extend;
2425   }
2426   case ISD::FP_ROUND: {
2427     // RVV can only do fp_round to types half the size as the source. We
2428     // custom-lower f64->f16 rounds via RVV's round-to-odd float
2429     // conversion instruction.
2430     SDLoc DL(Op);
2431     MVT VT = Op.getSimpleValueType();
2432     SDValue Src = Op.getOperand(0);
2433     MVT SrcVT = Src.getSimpleValueType();
2434 
2435     // Prepare any fixed-length vector operands.
2436     MVT ContainerVT = VT;
2437     if (VT.isFixedLengthVector()) {
2438       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2439       ContainerVT =
2440           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2441       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2442     }
2443 
2444     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
2445         SrcVT.getVectorElementType() != MVT::f64) {
2446       // For scalable vectors, we only need to close the gap between
2447       // vXf64<->vXf16.
2448       if (!VT.isFixedLengthVector())
2449         return Op;
2450       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
2451       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
2452       return convertFromScalableVector(VT, Src, DAG, Subtarget);
2453     }
2454 
2455     SDValue Mask, VL;
2456     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2457 
2458     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
2459     SDValue IntermediateRound =
2460         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
2461     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
2462                                           DL, DAG, Subtarget);
2463 
2464     if (VT.isFixedLengthVector())
2465       return convertFromScalableVector(VT, Round, DAG, Subtarget);
2466     return Round;
2467   }
2468   case ISD::FP_TO_SINT:
2469   case ISD::FP_TO_UINT:
2470   case ISD::SINT_TO_FP:
2471   case ISD::UINT_TO_FP: {
2472     // RVV can only do fp<->int conversions to types half/double the size as
2473     // the source. We custom-lower any conversions that do two hops into
2474     // sequences.
2475     MVT VT = Op.getSimpleValueType();
2476     if (!VT.isVector())
2477       return Op;
2478     SDLoc DL(Op);
2479     SDValue Src = Op.getOperand(0);
2480     MVT EltVT = VT.getVectorElementType();
2481     MVT SrcVT = Src.getSimpleValueType();
2482     MVT SrcEltVT = SrcVT.getVectorElementType();
2483     unsigned EltSize = EltVT.getSizeInBits();
2484     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
2485     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
2486            "Unexpected vector element types");
2487 
2488     bool IsInt2FP = SrcEltVT.isInteger();
2489     // Widening conversions
2490     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
2491       if (IsInt2FP) {
2492         // Do a regular integer sign/zero extension then convert to float.
2493         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
2494                                       VT.getVectorElementCount());
2495         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
2496                                  ? ISD::ZERO_EXTEND
2497                                  : ISD::SIGN_EXTEND;
2498         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
2499         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
2500       }
2501       // FP2Int
2502       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
2503       // Do one doubling fp_extend then complete the operation by converting
2504       // to int.
2505       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2506       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
2507       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
2508     }
2509 
2510     // Narrowing conversions
2511     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
2512       if (IsInt2FP) {
2513         // One narrowing int_to_fp, then an fp_round.
2514         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
2515         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
2516         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
2517         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
2518       }
2519       // FP2Int
2520       // One narrowing fp_to_int, then truncate the integer. If the float isn't
2521       // representable by the integer, the result is poison.
2522       MVT IVecVT =
2523           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
2524                            VT.getVectorElementCount());
2525       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
2526       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
2527     }
2528 
2529     // Scalable vectors can exit here. Patterns will handle equally-sized
2530     // conversions halving/doubling ones.
2531     if (!VT.isFixedLengthVector())
2532       return Op;
2533 
2534     // For fixed-length vectors we lower to a custom "VL" node.
2535     unsigned RVVOpc = 0;
2536     switch (Op.getOpcode()) {
2537     default:
2538       llvm_unreachable("Impossible opcode");
2539     case ISD::FP_TO_SINT:
2540       RVVOpc = RISCVISD::FP_TO_SINT_VL;
2541       break;
2542     case ISD::FP_TO_UINT:
2543       RVVOpc = RISCVISD::FP_TO_UINT_VL;
2544       break;
2545     case ISD::SINT_TO_FP:
2546       RVVOpc = RISCVISD::SINT_TO_FP_VL;
2547       break;
2548     case ISD::UINT_TO_FP:
2549       RVVOpc = RISCVISD::UINT_TO_FP_VL;
2550       break;
2551     }
2552 
2553     MVT ContainerVT, SrcContainerVT;
2554     // Derive the reference container type from the larger vector type.
2555     if (SrcEltSize > EltSize) {
2556       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
2557       ContainerVT =
2558           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
2559     } else {
2560       ContainerVT = getContainerForFixedLengthVector(VT);
2561       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
2562     }
2563 
2564     SDValue Mask, VL;
2565     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2566 
2567     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
2568     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
2569     return convertFromScalableVector(VT, Src, DAG, Subtarget);
2570   }
2571   case ISD::FP_TO_SINT_SAT:
2572   case ISD::FP_TO_UINT_SAT:
2573     return lowerFP_TO_INT_SAT(Op, DAG);
2574   case ISD::VECREDUCE_ADD:
2575   case ISD::VECREDUCE_UMAX:
2576   case ISD::VECREDUCE_SMAX:
2577   case ISD::VECREDUCE_UMIN:
2578   case ISD::VECREDUCE_SMIN:
2579     return lowerVECREDUCE(Op, DAG);
2580   case ISD::VECREDUCE_AND:
2581   case ISD::VECREDUCE_OR:
2582   case ISD::VECREDUCE_XOR:
2583     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
2584       return lowerVectorMaskVECREDUCE(Op, DAG);
2585     return lowerVECREDUCE(Op, DAG);
2586   case ISD::VECREDUCE_FADD:
2587   case ISD::VECREDUCE_SEQ_FADD:
2588   case ISD::VECREDUCE_FMIN:
2589   case ISD::VECREDUCE_FMAX:
2590     return lowerFPVECREDUCE(Op, DAG);
2591   case ISD::INSERT_SUBVECTOR:
2592     return lowerINSERT_SUBVECTOR(Op, DAG);
2593   case ISD::EXTRACT_SUBVECTOR:
2594     return lowerEXTRACT_SUBVECTOR(Op, DAG);
2595   case ISD::STEP_VECTOR:
2596     return lowerSTEP_VECTOR(Op, DAG);
2597   case ISD::VECTOR_REVERSE:
2598     return lowerVECTOR_REVERSE(Op, DAG);
2599   case ISD::BUILD_VECTOR:
2600     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
2601   case ISD::SPLAT_VECTOR:
2602     if (Op.getValueType().getVectorElementType() == MVT::i1)
2603       return lowerVectorMaskSplat(Op, DAG);
2604     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
2605   case ISD::VECTOR_SHUFFLE:
2606     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
2607   case ISD::CONCAT_VECTORS: {
2608     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
2609     // better than going through the stack, as the default expansion does.
2610     SDLoc DL(Op);
2611     MVT VT = Op.getSimpleValueType();
2612     unsigned NumOpElts =
2613         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
2614     SDValue Vec = DAG.getUNDEF(VT);
2615     for (const auto &OpIdx : enumerate(Op->ops()))
2616       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, OpIdx.value(),
2617                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
2618     return Vec;
2619   }
2620   case ISD::LOAD:
2621     if (auto V = expandUnalignedRVVLoad(Op, DAG))
2622       return V;
2623     if (Op.getValueType().isFixedLengthVector())
2624       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
2625     return Op;
2626   case ISD::STORE:
2627     if (auto V = expandUnalignedRVVStore(Op, DAG))
2628       return V;
2629     if (Op.getOperand(1).getValueType().isFixedLengthVector())
2630       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
2631     return Op;
2632   case ISD::MLOAD:
2633     return lowerMLOAD(Op, DAG);
2634   case ISD::MSTORE:
2635     return lowerMSTORE(Op, DAG);
2636   case ISD::SETCC:
2637     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
2638   case ISD::ADD:
2639     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
2640   case ISD::SUB:
2641     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
2642   case ISD::MUL:
2643     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
2644   case ISD::MULHS:
2645     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
2646   case ISD::MULHU:
2647     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
2648   case ISD::AND:
2649     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
2650                                               RISCVISD::AND_VL);
2651   case ISD::OR:
2652     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
2653                                               RISCVISD::OR_VL);
2654   case ISD::XOR:
2655     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
2656                                               RISCVISD::XOR_VL);
2657   case ISD::SDIV:
2658     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
2659   case ISD::SREM:
2660     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
2661   case ISD::UDIV:
2662     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
2663   case ISD::UREM:
2664     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
2665   case ISD::SHL:
2666   case ISD::SRA:
2667   case ISD::SRL:
2668     if (Op.getSimpleValueType().isFixedLengthVector())
2669       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
2670     // This can be called for an i32 shift amount that needs to be promoted.
2671     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
2672            "Unexpected custom legalisation");
2673     return SDValue();
2674   case ISD::SADDSAT:
2675     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
2676   case ISD::UADDSAT:
2677     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
2678   case ISD::SSUBSAT:
2679     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
2680   case ISD::USUBSAT:
2681     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
2682   case ISD::FADD:
2683     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
2684   case ISD::FSUB:
2685     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
2686   case ISD::FMUL:
2687     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
2688   case ISD::FDIV:
2689     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
2690   case ISD::FNEG:
2691     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
2692   case ISD::FABS:
2693     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
2694   case ISD::FSQRT:
2695     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
2696   case ISD::FMA:
2697     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
2698   case ISD::SMIN:
2699     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
2700   case ISD::SMAX:
2701     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
2702   case ISD::UMIN:
2703     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
2704   case ISD::UMAX:
2705     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
2706   case ISD::FMINNUM:
2707     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
2708   case ISD::FMAXNUM:
2709     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
2710   case ISD::ABS:
2711     return lowerABS(Op, DAG);
2712   case ISD::VSELECT:
2713     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
2714   case ISD::FCOPYSIGN:
2715     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
2716   case ISD::MGATHER:
2717     return lowerMGATHER(Op, DAG);
2718   case ISD::MSCATTER:
2719     return lowerMSCATTER(Op, DAG);
2720   case ISD::FLT_ROUNDS_:
2721     return lowerGET_ROUNDING(Op, DAG);
2722   case ISD::SET_ROUNDING:
2723     return lowerSET_ROUNDING(Op, DAG);
2724   case ISD::VP_ADD:
2725     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
2726   case ISD::VP_SUB:
2727     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
2728   case ISD::VP_MUL:
2729     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
2730   case ISD::VP_SDIV:
2731     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
2732   case ISD::VP_UDIV:
2733     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
2734   case ISD::VP_SREM:
2735     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
2736   case ISD::VP_UREM:
2737     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
2738   case ISD::VP_AND:
2739     return lowerVPOp(Op, DAG, RISCVISD::AND_VL);
2740   case ISD::VP_OR:
2741     return lowerVPOp(Op, DAG, RISCVISD::OR_VL);
2742   case ISD::VP_XOR:
2743     return lowerVPOp(Op, DAG, RISCVISD::XOR_VL);
2744   case ISD::VP_ASHR:
2745     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
2746   case ISD::VP_LSHR:
2747     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
2748   case ISD::VP_SHL:
2749     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
2750   case ISD::VP_FADD:
2751     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
2752   case ISD::VP_FSUB:
2753     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
2754   case ISD::VP_FMUL:
2755     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
2756   case ISD::VP_FDIV:
2757     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
2758   }
2759 }
2760 
2761 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
2762                              SelectionDAG &DAG, unsigned Flags) {
2763   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
2764 }
2765 
2766 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
2767                              SelectionDAG &DAG, unsigned Flags) {
2768   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
2769                                    Flags);
2770 }
2771 
2772 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
2773                              SelectionDAG &DAG, unsigned Flags) {
2774   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
2775                                    N->getOffset(), Flags);
2776 }
2777 
2778 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
2779                              SelectionDAG &DAG, unsigned Flags) {
2780   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
2781 }
2782 
2783 template <class NodeTy>
2784 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
2785                                      bool IsLocal) const {
2786   SDLoc DL(N);
2787   EVT Ty = getPointerTy(DAG.getDataLayout());
2788 
2789   if (isPositionIndependent()) {
2790     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
2791     if (IsLocal)
2792       // Use PC-relative addressing to access the symbol. This generates the
2793       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
2794       // %pcrel_lo(auipc)).
2795       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
2796 
2797     // Use PC-relative addressing to access the GOT for this symbol, then load
2798     // the address from the GOT. This generates the pattern (PseudoLA sym),
2799     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
2800     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
2801   }
2802 
2803   switch (getTargetMachine().getCodeModel()) {
2804   default:
2805     report_fatal_error("Unsupported code model for lowering");
2806   case CodeModel::Small: {
2807     // Generate a sequence for accessing addresses within the first 2 GiB of
2808     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
2809     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
2810     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
2811     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
2812     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
2813   }
2814   case CodeModel::Medium: {
2815     // Generate a sequence for accessing addresses within any 2GiB range within
2816     // the address space. This generates the pattern (PseudoLLA sym), which
2817     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
2818     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
2819     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
2820   }
2821   }
2822 }
2823 
2824 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
2825                                                 SelectionDAG &DAG) const {
2826   SDLoc DL(Op);
2827   EVT Ty = Op.getValueType();
2828   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
2829   int64_t Offset = N->getOffset();
2830   MVT XLenVT = Subtarget.getXLenVT();
2831 
2832   const GlobalValue *GV = N->getGlobal();
2833   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
2834   SDValue Addr = getAddr(N, DAG, IsLocal);
2835 
2836   // In order to maximise the opportunity for common subexpression elimination,
2837   // emit a separate ADD node for the global address offset instead of folding
2838   // it in the global address node. Later peephole optimisations may choose to
2839   // fold it back in when profitable.
2840   if (Offset != 0)
2841     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
2842                        DAG.getConstant(Offset, DL, XLenVT));
2843   return Addr;
2844 }
2845 
2846 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
2847                                                SelectionDAG &DAG) const {
2848   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
2849 
2850   return getAddr(N, DAG);
2851 }
2852 
2853 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
2854                                                SelectionDAG &DAG) const {
2855   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2856 
2857   return getAddr(N, DAG);
2858 }
2859 
2860 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
2861                                             SelectionDAG &DAG) const {
2862   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
2863 
2864   return getAddr(N, DAG);
2865 }
2866 
2867 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
2868                                               SelectionDAG &DAG,
2869                                               bool UseGOT) const {
2870   SDLoc DL(N);
2871   EVT Ty = getPointerTy(DAG.getDataLayout());
2872   const GlobalValue *GV = N->getGlobal();
2873   MVT XLenVT = Subtarget.getXLenVT();
2874 
2875   if (UseGOT) {
2876     // Use PC-relative addressing to access the GOT for this TLS symbol, then
2877     // load the address from the GOT and add the thread pointer. This generates
2878     // the pattern (PseudoLA_TLS_IE sym), which expands to
2879     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
2880     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
2881     SDValue Load =
2882         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
2883 
2884     // Add the thread pointer.
2885     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
2886     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
2887   }
2888 
2889   // Generate a sequence for accessing the address relative to the thread
2890   // pointer, with the appropriate adjustment for the thread pointer offset.
2891   // This generates the pattern
2892   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
2893   SDValue AddrHi =
2894       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
2895   SDValue AddrAdd =
2896       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
2897   SDValue AddrLo =
2898       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
2899 
2900   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
2901   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
2902   SDValue MNAdd = SDValue(
2903       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
2904       0);
2905   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
2906 }
2907 
2908 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
2909                                                SelectionDAG &DAG) const {
2910   SDLoc DL(N);
2911   EVT Ty = getPointerTy(DAG.getDataLayout());
2912   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
2913   const GlobalValue *GV = N->getGlobal();
2914 
2915   // Use a PC-relative addressing mode to access the global dynamic GOT address.
2916   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
2917   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
2918   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
2919   SDValue Load =
2920       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
2921 
2922   // Prepare argument list to generate call.
2923   ArgListTy Args;
2924   ArgListEntry Entry;
2925   Entry.Node = Load;
2926   Entry.Ty = CallTy;
2927   Args.push_back(Entry);
2928 
2929   // Setup call to __tls_get_addr.
2930   TargetLowering::CallLoweringInfo CLI(DAG);
2931   CLI.setDebugLoc(DL)
2932       .setChain(DAG.getEntryNode())
2933       .setLibCallee(CallingConv::C, CallTy,
2934                     DAG.getExternalSymbol("__tls_get_addr", Ty),
2935                     std::move(Args));
2936 
2937   return LowerCallTo(CLI).first;
2938 }
2939 
2940 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
2941                                                    SelectionDAG &DAG) const {
2942   SDLoc DL(Op);
2943   EVT Ty = Op.getValueType();
2944   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
2945   int64_t Offset = N->getOffset();
2946   MVT XLenVT = Subtarget.getXLenVT();
2947 
2948   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
2949 
2950   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
2951       CallingConv::GHC)
2952     report_fatal_error("In GHC calling convention TLS is not supported");
2953 
2954   SDValue Addr;
2955   switch (Model) {
2956   case TLSModel::LocalExec:
2957     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
2958     break;
2959   case TLSModel::InitialExec:
2960     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
2961     break;
2962   case TLSModel::LocalDynamic:
2963   case TLSModel::GeneralDynamic:
2964     Addr = getDynamicTLSAddr(N, DAG);
2965     break;
2966   }
2967 
2968   // In order to maximise the opportunity for common subexpression elimination,
2969   // emit a separate ADD node for the global address offset instead of folding
2970   // it in the global address node. Later peephole optimisations may choose to
2971   // fold it back in when profitable.
2972   if (Offset != 0)
2973     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
2974                        DAG.getConstant(Offset, DL, XLenVT));
2975   return Addr;
2976 }
2977 
2978 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2979   SDValue CondV = Op.getOperand(0);
2980   SDValue TrueV = Op.getOperand(1);
2981   SDValue FalseV = Op.getOperand(2);
2982   SDLoc DL(Op);
2983   MVT VT = Op.getSimpleValueType();
2984   MVT XLenVT = Subtarget.getXLenVT();
2985 
2986   // Lower vector SELECTs to VSELECTs by splatting the condition.
2987   if (VT.isVector()) {
2988     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
2989     SDValue CondSplat = VT.isScalableVector()
2990                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
2991                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
2992     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
2993   }
2994 
2995   // If the result type is XLenVT and CondV is the output of a SETCC node
2996   // which also operated on XLenVT inputs, then merge the SETCC node into the
2997   // lowered RISCVISD::SELECT_CC to take advantage of the integer
2998   // compare+branch instructions. i.e.:
2999   // (select (setcc lhs, rhs, cc), truev, falsev)
3000   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3001   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3002       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3003     SDValue LHS = CondV.getOperand(0);
3004     SDValue RHS = CondV.getOperand(1);
3005     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3006     ISD::CondCode CCVal = CC->get();
3007 
3008     // Special case for a select of 2 constants that have a diffence of 1.
3009     // Normally this is done by DAGCombine, but if the select is introduced by
3010     // type legalization or op legalization, we miss it. Restricting to SETLT
3011     // case for now because that is what signed saturating add/sub need.
3012     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3013     // but we would probably want to swap the true/false values if the condition
3014     // is SETGE/SETLE to avoid an XORI.
3015     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3016         CCVal == ISD::SETLT) {
3017       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3018       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3019       if (TrueVal - 1 == FalseVal)
3020         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3021       if (TrueVal + 1 == FalseVal)
3022         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3023     }
3024 
3025     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3026 
3027     SDValue TargetCC = DAG.getCondCode(CCVal);
3028     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3029     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3030   }
3031 
3032   // Otherwise:
3033   // (select condv, truev, falsev)
3034   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3035   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3036   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3037 
3038   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3039 
3040   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3041 }
3042 
3043 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3044   SDValue CondV = Op.getOperand(1);
3045   SDLoc DL(Op);
3046   MVT XLenVT = Subtarget.getXLenVT();
3047 
3048   if (CondV.getOpcode() == ISD::SETCC &&
3049       CondV.getOperand(0).getValueType() == XLenVT) {
3050     SDValue LHS = CondV.getOperand(0);
3051     SDValue RHS = CondV.getOperand(1);
3052     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3053 
3054     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3055 
3056     SDValue TargetCC = DAG.getCondCode(CCVal);
3057     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3058                        LHS, RHS, TargetCC, Op.getOperand(2));
3059   }
3060 
3061   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3062                      CondV, DAG.getConstant(0, DL, XLenVT),
3063                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3064 }
3065 
3066 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3067   MachineFunction &MF = DAG.getMachineFunction();
3068   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3069 
3070   SDLoc DL(Op);
3071   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3072                                  getPointerTy(MF.getDataLayout()));
3073 
3074   // vastart just stores the address of the VarArgsFrameIndex slot into the
3075   // memory location argument.
3076   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3077   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3078                       MachinePointerInfo(SV));
3079 }
3080 
3081 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3082                                             SelectionDAG &DAG) const {
3083   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3084   MachineFunction &MF = DAG.getMachineFunction();
3085   MachineFrameInfo &MFI = MF.getFrameInfo();
3086   MFI.setFrameAddressIsTaken(true);
3087   Register FrameReg = RI.getFrameRegister(MF);
3088   int XLenInBytes = Subtarget.getXLen() / 8;
3089 
3090   EVT VT = Op.getValueType();
3091   SDLoc DL(Op);
3092   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3093   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3094   while (Depth--) {
3095     int Offset = -(XLenInBytes * 2);
3096     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3097                               DAG.getIntPtrConstant(Offset, DL));
3098     FrameAddr =
3099         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3100   }
3101   return FrameAddr;
3102 }
3103 
3104 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3105                                              SelectionDAG &DAG) const {
3106   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3107   MachineFunction &MF = DAG.getMachineFunction();
3108   MachineFrameInfo &MFI = MF.getFrameInfo();
3109   MFI.setReturnAddressIsTaken(true);
3110   MVT XLenVT = Subtarget.getXLenVT();
3111   int XLenInBytes = Subtarget.getXLen() / 8;
3112 
3113   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3114     return SDValue();
3115 
3116   EVT VT = Op.getValueType();
3117   SDLoc DL(Op);
3118   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3119   if (Depth) {
3120     int Off = -XLenInBytes;
3121     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3122     SDValue Offset = DAG.getConstant(Off, DL, VT);
3123     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3124                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3125                        MachinePointerInfo());
3126   }
3127 
3128   // Return the value of the return address register, marking it an implicit
3129   // live-in.
3130   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3131   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3132 }
3133 
3134 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3135                                                  SelectionDAG &DAG) const {
3136   SDLoc DL(Op);
3137   SDValue Lo = Op.getOperand(0);
3138   SDValue Hi = Op.getOperand(1);
3139   SDValue Shamt = Op.getOperand(2);
3140   EVT VT = Lo.getValueType();
3141 
3142   // if Shamt-XLEN < 0: // Shamt < XLEN
3143   //   Lo = Lo << Shamt
3144   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3145   // else:
3146   //   Lo = 0
3147   //   Hi = Lo << (Shamt-XLEN)
3148 
3149   SDValue Zero = DAG.getConstant(0, DL, VT);
3150   SDValue One = DAG.getConstant(1, DL, VT);
3151   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3152   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3153   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3154   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3155 
3156   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3157   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3158   SDValue ShiftRightLo =
3159       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3160   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3161   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3162   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3163 
3164   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3165 
3166   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3167   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3168 
3169   SDValue Parts[2] = {Lo, Hi};
3170   return DAG.getMergeValues(Parts, DL);
3171 }
3172 
3173 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3174                                                   bool IsSRA) const {
3175   SDLoc DL(Op);
3176   SDValue Lo = Op.getOperand(0);
3177   SDValue Hi = Op.getOperand(1);
3178   SDValue Shamt = Op.getOperand(2);
3179   EVT VT = Lo.getValueType();
3180 
3181   // SRA expansion:
3182   //   if Shamt-XLEN < 0: // Shamt < XLEN
3183   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3184   //     Hi = Hi >>s Shamt
3185   //   else:
3186   //     Lo = Hi >>s (Shamt-XLEN);
3187   //     Hi = Hi >>s (XLEN-1)
3188   //
3189   // SRL expansion:
3190   //   if Shamt-XLEN < 0: // Shamt < XLEN
3191   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3192   //     Hi = Hi >>u Shamt
3193   //   else:
3194   //     Lo = Hi >>u (Shamt-XLEN);
3195   //     Hi = 0;
3196 
3197   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3198 
3199   SDValue Zero = DAG.getConstant(0, DL, VT);
3200   SDValue One = DAG.getConstant(1, DL, VT);
3201   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3202   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3203   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3204   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3205 
3206   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3207   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3208   SDValue ShiftLeftHi =
3209       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3210   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3211   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3212   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3213   SDValue HiFalse =
3214       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3215 
3216   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3217 
3218   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3219   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3220 
3221   SDValue Parts[2] = {Lo, Hi};
3222   return DAG.getMergeValues(Parts, DL);
3223 }
3224 
3225 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3226 // legal equivalently-sized i8 type, so we can use that as a go-between.
3227 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3228                                                   SelectionDAG &DAG) const {
3229   SDLoc DL(Op);
3230   MVT VT = Op.getSimpleValueType();
3231   SDValue SplatVal = Op.getOperand(0);
3232   // All-zeros or all-ones splats are handled specially.
3233   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
3234     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3235     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
3236   }
3237   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
3238     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
3239     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
3240   }
3241   MVT XLenVT = Subtarget.getXLenVT();
3242   assert(SplatVal.getValueType() == XLenVT &&
3243          "Unexpected type for i1 splat value");
3244   MVT InterVT = VT.changeVectorElementType(MVT::i8);
3245   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
3246                          DAG.getConstant(1, DL, XLenVT));
3247   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
3248   SDValue Zero = DAG.getConstant(0, DL, InterVT);
3249   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
3250 }
3251 
3252 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
3253 // illegal (currently only vXi64 RV32).
3254 // FIXME: We could also catch non-constant sign-extended i32 values and lower
3255 // them to SPLAT_VECTOR_I64
3256 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
3257                                                      SelectionDAG &DAG) const {
3258   SDLoc DL(Op);
3259   MVT VecVT = Op.getSimpleValueType();
3260   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
3261          "Unexpected SPLAT_VECTOR_PARTS lowering");
3262 
3263   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
3264   SDValue Lo = Op.getOperand(0);
3265   SDValue Hi = Op.getOperand(1);
3266 
3267   if (VecVT.isFixedLengthVector()) {
3268     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3269     SDLoc DL(Op);
3270     SDValue Mask, VL;
3271     std::tie(Mask, VL) =
3272         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3273 
3274     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
3275     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
3276   }
3277 
3278   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
3279     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
3280     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
3281     // If Hi constant is all the same sign bit as Lo, lower this as a custom
3282     // node in order to try and match RVV vector/scalar instructions.
3283     if ((LoC >> 31) == HiC)
3284       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3285   }
3286 
3287   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
3288   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
3289       isa<ConstantSDNode>(Hi.getOperand(1)) &&
3290       Hi.getConstantOperandVal(1) == 31)
3291     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
3292 
3293   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
3294   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
3295                      DAG.getRegister(RISCV::X0, MVT::i64));
3296 }
3297 
3298 // Custom-lower extensions from mask vectors by using a vselect either with 1
3299 // for zero/any-extension or -1 for sign-extension:
3300 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
3301 // Note that any-extension is lowered identically to zero-extension.
3302 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
3303                                                 int64_t ExtTrueVal) const {
3304   SDLoc DL(Op);
3305   MVT VecVT = Op.getSimpleValueType();
3306   SDValue Src = Op.getOperand(0);
3307   // Only custom-lower extensions from mask types
3308   assert(Src.getValueType().isVector() &&
3309          Src.getValueType().getVectorElementType() == MVT::i1);
3310 
3311   MVT XLenVT = Subtarget.getXLenVT();
3312   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
3313   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
3314 
3315   if (VecVT.isScalableVector()) {
3316     // Be careful not to introduce illegal scalar types at this stage, and be
3317     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
3318     // illegal and must be expanded. Since we know that the constants are
3319     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
3320     bool IsRV32E64 =
3321         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
3322 
3323     if (!IsRV32E64) {
3324       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
3325       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
3326     } else {
3327       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
3328       SplatTrueVal =
3329           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
3330     }
3331 
3332     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
3333   }
3334 
3335   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
3336   MVT I1ContainerVT =
3337       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3338 
3339   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
3340 
3341   SDValue Mask, VL;
3342   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3343 
3344   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
3345   SplatTrueVal =
3346       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
3347   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
3348                                SplatTrueVal, SplatZero, VL);
3349 
3350   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
3351 }
3352 
3353 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
3354     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
3355   MVT ExtVT = Op.getSimpleValueType();
3356   // Only custom-lower extensions from fixed-length vector types.
3357   if (!ExtVT.isFixedLengthVector())
3358     return Op;
3359   MVT VT = Op.getOperand(0).getSimpleValueType();
3360   // Grab the canonical container type for the extended type. Infer the smaller
3361   // type from that to ensure the same number of vector elements, as we know
3362   // the LMUL will be sufficient to hold the smaller type.
3363   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
3364   // Get the extended container type manually to ensure the same number of
3365   // vector elements between source and dest.
3366   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
3367                                      ContainerExtVT.getVectorElementCount());
3368 
3369   SDValue Op1 =
3370       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
3371 
3372   SDLoc DL(Op);
3373   SDValue Mask, VL;
3374   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3375 
3376   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
3377 
3378   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
3379 }
3380 
3381 // Custom-lower truncations from vectors to mask vectors by using a mask and a
3382 // setcc operation:
3383 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
3384 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
3385                                                   SelectionDAG &DAG) const {
3386   SDLoc DL(Op);
3387   EVT MaskVT = Op.getValueType();
3388   // Only expect to custom-lower truncations to mask types
3389   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
3390          "Unexpected type for vector mask lowering");
3391   SDValue Src = Op.getOperand(0);
3392   MVT VecVT = Src.getSimpleValueType();
3393 
3394   // If this is a fixed vector, we need to convert it to a scalable vector.
3395   MVT ContainerVT = VecVT;
3396   if (VecVT.isFixedLengthVector()) {
3397     ContainerVT = getContainerForFixedLengthVector(VecVT);
3398     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3399   }
3400 
3401   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
3402   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
3403 
3404   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
3405   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
3406 
3407   if (VecVT.isScalableVector()) {
3408     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
3409     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
3410   }
3411 
3412   SDValue Mask, VL;
3413   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3414 
3415   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
3416   SDValue Trunc =
3417       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
3418   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
3419                       DAG.getCondCode(ISD::SETNE), Mask, VL);
3420   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
3421 }
3422 
3423 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
3424 // first position of a vector, and that vector is slid up to the insert index.
3425 // By limiting the active vector length to index+1 and merging with the
3426 // original vector (with an undisturbed tail policy for elements >= VL), we
3427 // achieve the desired result of leaving all elements untouched except the one
3428 // at VL-1, which is replaced with the desired value.
3429 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
3430                                                     SelectionDAG &DAG) const {
3431   SDLoc DL(Op);
3432   MVT VecVT = Op.getSimpleValueType();
3433   SDValue Vec = Op.getOperand(0);
3434   SDValue Val = Op.getOperand(1);
3435   SDValue Idx = Op.getOperand(2);
3436 
3437   if (VecVT.getVectorElementType() == MVT::i1) {
3438     // FIXME: For now we just promote to an i8 vector and insert into that,
3439     // but this is probably not optimal.
3440     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3441     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3442     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
3443     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
3444   }
3445 
3446   MVT ContainerVT = VecVT;
3447   // If the operand is a fixed-length vector, convert to a scalable one.
3448   if (VecVT.isFixedLengthVector()) {
3449     ContainerVT = getContainerForFixedLengthVector(VecVT);
3450     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3451   }
3452 
3453   MVT XLenVT = Subtarget.getXLenVT();
3454 
3455   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3456   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
3457   // Even i64-element vectors on RV32 can be lowered without scalar
3458   // legalization if the most-significant 32 bits of the value are not affected
3459   // by the sign-extension of the lower 32 bits.
3460   // TODO: We could also catch sign extensions of a 32-bit value.
3461   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
3462     const auto *CVal = cast<ConstantSDNode>(Val);
3463     if (isInt<32>(CVal->getSExtValue())) {
3464       IsLegalInsert = true;
3465       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3466     }
3467   }
3468 
3469   SDValue Mask, VL;
3470   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3471 
3472   SDValue ValInVec;
3473 
3474   if (IsLegalInsert) {
3475     unsigned Opc =
3476         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
3477     if (isNullConstant(Idx)) {
3478       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
3479       if (!VecVT.isFixedLengthVector())
3480         return Vec;
3481       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
3482     }
3483     ValInVec =
3484         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
3485   } else {
3486     // On RV32, i64-element vectors must be specially handled to place the
3487     // value at element 0, by using two vslide1up instructions in sequence on
3488     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
3489     // this.
3490     SDValue One = DAG.getConstant(1, DL, XLenVT);
3491     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
3492     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
3493     MVT I32ContainerVT =
3494         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
3495     SDValue I32Mask =
3496         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
3497     // Limit the active VL to two.
3498     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
3499     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
3500     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
3501     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
3502                            InsertI64VL);
3503     // First slide in the hi value, then the lo in underneath it.
3504     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3505                            ValHi, I32Mask, InsertI64VL);
3506     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
3507                            ValLo, I32Mask, InsertI64VL);
3508     // Bitcast back to the right container type.
3509     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
3510   }
3511 
3512   // Now that the value is in a vector, slide it into position.
3513   SDValue InsertVL =
3514       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
3515   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
3516                                 ValInVec, Idx, Mask, InsertVL);
3517   if (!VecVT.isFixedLengthVector())
3518     return Slideup;
3519   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
3520 }
3521 
3522 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
3523 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
3524 // types this is done using VMV_X_S to allow us to glean information about the
3525 // sign bits of the result.
3526 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
3527                                                      SelectionDAG &DAG) const {
3528   SDLoc DL(Op);
3529   SDValue Idx = Op.getOperand(1);
3530   SDValue Vec = Op.getOperand(0);
3531   EVT EltVT = Op.getValueType();
3532   MVT VecVT = Vec.getSimpleValueType();
3533   MVT XLenVT = Subtarget.getXLenVT();
3534 
3535   if (VecVT.getVectorElementType() == MVT::i1) {
3536     // FIXME: For now we just promote to an i8 vector and extract from that,
3537     // but this is probably not optimal.
3538     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
3539     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
3540     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
3541   }
3542 
3543   // If this is a fixed vector, we need to convert it to a scalable vector.
3544   MVT ContainerVT = VecVT;
3545   if (VecVT.isFixedLengthVector()) {
3546     ContainerVT = getContainerForFixedLengthVector(VecVT);
3547     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3548   }
3549 
3550   // If the index is 0, the vector is already in the right position.
3551   if (!isNullConstant(Idx)) {
3552     // Use a VL of 1 to avoid processing more elements than we need.
3553     SDValue VL = DAG.getConstant(1, DL, XLenVT);
3554     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
3555     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3556     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
3557                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
3558   }
3559 
3560   if (!EltVT.isInteger()) {
3561     // Floating-point extracts are handled in TableGen.
3562     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
3563                        DAG.getConstant(0, DL, XLenVT));
3564   }
3565 
3566   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
3567   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
3568 }
3569 
3570 // Some RVV intrinsics may claim that they want an integer operand to be
3571 // promoted or expanded.
3572 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
3573                                           const RISCVSubtarget &Subtarget) {
3574   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3575           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
3576          "Unexpected opcode");
3577 
3578   if (!Subtarget.hasStdExtV())
3579     return SDValue();
3580 
3581   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
3582   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
3583   SDLoc DL(Op);
3584 
3585   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
3586       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
3587   if (!II || !II->SplatOperand)
3588     return SDValue();
3589 
3590   unsigned SplatOp = II->SplatOperand + HasChain;
3591   assert(SplatOp < Op.getNumOperands());
3592 
3593   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
3594   SDValue &ScalarOp = Operands[SplatOp];
3595   MVT OpVT = ScalarOp.getSimpleValueType();
3596   MVT XLenVT = Subtarget.getXLenVT();
3597 
3598   // If this isn't a scalar, or its type is XLenVT we're done.
3599   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
3600     return SDValue();
3601 
3602   // Simplest case is that the operand needs to be promoted to XLenVT.
3603   if (OpVT.bitsLT(XLenVT)) {
3604     // If the operand is a constant, sign extend to increase our chances
3605     // of being able to use a .vi instruction. ANY_EXTEND would become a
3606     // a zero extend and the simm5 check in isel would fail.
3607     // FIXME: Should we ignore the upper bits in isel instead?
3608     unsigned ExtOpc =
3609         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
3610     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
3611     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3612   }
3613 
3614   // Use the previous operand to get the vXi64 VT. The result might be a mask
3615   // VT for compares. Using the previous operand assumes that the previous
3616   // operand will never have a smaller element size than a scalar operand and
3617   // that a widening operation never uses SEW=64.
3618   // NOTE: If this fails the below assert, we can probably just find the
3619   // element count from any operand or result and use it to construct the VT.
3620   assert(II->SplatOperand > 1 && "Unexpected splat operand!");
3621   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
3622 
3623   // The more complex case is when the scalar is larger than XLenVT.
3624   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
3625          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
3626 
3627   // If this is a sign-extended 32-bit constant, we can truncate it and rely
3628   // on the instruction to sign-extend since SEW>XLEN.
3629   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
3630     if (isInt<32>(CVal->getSExtValue())) {
3631       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
3632       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3633     }
3634   }
3635 
3636   // We need to convert the scalar to a splat vector.
3637   // FIXME: Can we implicitly truncate the scalar if it is known to
3638   // be sign extended?
3639   // VL should be the last operand.
3640   SDValue VL = Op.getOperand(Op.getNumOperands() - 1);
3641   assert(VL.getValueType() == XLenVT);
3642   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
3643   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
3644 }
3645 
3646 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
3647                                                      SelectionDAG &DAG) const {
3648   unsigned IntNo = Op.getConstantOperandVal(0);
3649   SDLoc DL(Op);
3650   MVT XLenVT = Subtarget.getXLenVT();
3651 
3652   switch (IntNo) {
3653   default:
3654     break; // Don't custom lower most intrinsics.
3655   case Intrinsic::thread_pointer: {
3656     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3657     return DAG.getRegister(RISCV::X4, PtrVT);
3658   }
3659   case Intrinsic::riscv_orc_b:
3660     // Lower to the GORCI encoding for orc.b.
3661     return DAG.getNode(RISCVISD::GORC, DL, XLenVT, Op.getOperand(1),
3662                        DAG.getConstant(7, DL, XLenVT));
3663   case Intrinsic::riscv_grev:
3664   case Intrinsic::riscv_gorc: {
3665     unsigned Opc =
3666         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
3667     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3668   }
3669   case Intrinsic::riscv_shfl:
3670   case Intrinsic::riscv_unshfl: {
3671     unsigned Opc =
3672         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
3673     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3674   }
3675   case Intrinsic::riscv_bcompress:
3676   case Intrinsic::riscv_bdecompress: {
3677     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
3678                                                        : RISCVISD::BDECOMPRESS;
3679     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
3680   }
3681   case Intrinsic::riscv_vmv_x_s:
3682     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
3683     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
3684                        Op.getOperand(1));
3685   case Intrinsic::riscv_vmv_v_x:
3686     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
3687                             Op.getSimpleValueType(), DL, DAG, Subtarget);
3688   case Intrinsic::riscv_vfmv_v_f:
3689     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
3690                        Op.getOperand(1), Op.getOperand(2));
3691   case Intrinsic::riscv_vmv_s_x: {
3692     SDValue Scalar = Op.getOperand(2);
3693 
3694     if (Scalar.getValueType().bitsLE(XLenVT)) {
3695       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
3696       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
3697                          Op.getOperand(1), Scalar, Op.getOperand(3));
3698     }
3699 
3700     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
3701 
3702     // This is an i64 value that lives in two scalar registers. We have to
3703     // insert this in a convoluted way. First we build vXi64 splat containing
3704     // the/ two values that we assemble using some bit math. Next we'll use
3705     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
3706     // to merge element 0 from our splat into the source vector.
3707     // FIXME: This is probably not the best way to do this, but it is
3708     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
3709     // point.
3710     //   sw lo, (a0)
3711     //   sw hi, 4(a0)
3712     //   vlse vX, (a0)
3713     //
3714     //   vid.v      vVid
3715     //   vmseq.vx   mMask, vVid, 0
3716     //   vmerge.vvm vDest, vSrc, vVal, mMask
3717     MVT VT = Op.getSimpleValueType();
3718     SDValue Vec = Op.getOperand(1);
3719     SDValue VL = Op.getOperand(3);
3720 
3721     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
3722     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
3723                                       DAG.getConstant(0, DL, MVT::i32), VL);
3724 
3725     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
3726     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
3727     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
3728     SDValue SelectCond =
3729         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
3730                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
3731     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
3732                        Vec, VL);
3733   }
3734   case Intrinsic::riscv_vslide1up:
3735   case Intrinsic::riscv_vslide1down:
3736   case Intrinsic::riscv_vslide1up_mask:
3737   case Intrinsic::riscv_vslide1down_mask: {
3738     // We need to special case these when the scalar is larger than XLen.
3739     unsigned NumOps = Op.getNumOperands();
3740     bool IsMasked = NumOps == 6;
3741     unsigned OpOffset = IsMasked ? 1 : 0;
3742     SDValue Scalar = Op.getOperand(2 + OpOffset);
3743     if (Scalar.getValueType().bitsLE(XLenVT))
3744       break;
3745 
3746     // Splatting a sign extended constant is fine.
3747     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
3748       if (isInt<32>(CVal->getSExtValue()))
3749         break;
3750 
3751     MVT VT = Op.getSimpleValueType();
3752     assert(VT.getVectorElementType() == MVT::i64 &&
3753            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
3754 
3755     // Convert the vector source to the equivalent nxvXi32 vector.
3756     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
3757     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
3758 
3759     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3760                                    DAG.getConstant(0, DL, XLenVT));
3761     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
3762                                    DAG.getConstant(1, DL, XLenVT));
3763 
3764     // Double the VL since we halved SEW.
3765     SDValue VL = Op.getOperand(NumOps - 1);
3766     SDValue I32VL =
3767         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
3768 
3769     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
3770     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
3771 
3772     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
3773     // instructions.
3774     if (IntNo == Intrinsic::riscv_vslide1up ||
3775         IntNo == Intrinsic::riscv_vslide1up_mask) {
3776       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
3777                         I32Mask, I32VL);
3778       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
3779                         I32Mask, I32VL);
3780     } else {
3781       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
3782                         I32Mask, I32VL);
3783       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
3784                         I32Mask, I32VL);
3785     }
3786 
3787     // Convert back to nxvXi64.
3788     Vec = DAG.getBitcast(VT, Vec);
3789 
3790     if (!IsMasked)
3791       return Vec;
3792 
3793     // Apply mask after the operation.
3794     SDValue Mask = Op.getOperand(NumOps - 2);
3795     SDValue MaskedOff = Op.getOperand(1);
3796     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
3797   }
3798   }
3799 
3800   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
3801 }
3802 
3803 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
3804                                                     SelectionDAG &DAG) const {
3805   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
3806 }
3807 
3808 static MVT getLMUL1VT(MVT VT) {
3809   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
3810          "Unexpected vector MVT");
3811   return MVT::getScalableVectorVT(
3812       VT.getVectorElementType(),
3813       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
3814 }
3815 
3816 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
3817   switch (ISDOpcode) {
3818   default:
3819     llvm_unreachable("Unhandled reduction");
3820   case ISD::VECREDUCE_ADD:
3821     return RISCVISD::VECREDUCE_ADD_VL;
3822   case ISD::VECREDUCE_UMAX:
3823     return RISCVISD::VECREDUCE_UMAX_VL;
3824   case ISD::VECREDUCE_SMAX:
3825     return RISCVISD::VECREDUCE_SMAX_VL;
3826   case ISD::VECREDUCE_UMIN:
3827     return RISCVISD::VECREDUCE_UMIN_VL;
3828   case ISD::VECREDUCE_SMIN:
3829     return RISCVISD::VECREDUCE_SMIN_VL;
3830   case ISD::VECREDUCE_AND:
3831     return RISCVISD::VECREDUCE_AND_VL;
3832   case ISD::VECREDUCE_OR:
3833     return RISCVISD::VECREDUCE_OR_VL;
3834   case ISD::VECREDUCE_XOR:
3835     return RISCVISD::VECREDUCE_XOR_VL;
3836   }
3837 }
3838 
3839 SDValue RISCVTargetLowering::lowerVectorMaskVECREDUCE(SDValue Op,
3840                                                       SelectionDAG &DAG) const {
3841   SDLoc DL(Op);
3842   SDValue Vec = Op.getOperand(0);
3843   MVT VecVT = Vec.getSimpleValueType();
3844   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
3845           Op.getOpcode() == ISD::VECREDUCE_OR ||
3846           Op.getOpcode() == ISD::VECREDUCE_XOR) &&
3847          "Unexpected reduction lowering");
3848 
3849   MVT XLenVT = Subtarget.getXLenVT();
3850   assert(Op.getValueType() == XLenVT &&
3851          "Expected reduction output to be legalized to XLenVT");
3852 
3853   MVT ContainerVT = VecVT;
3854   if (VecVT.isFixedLengthVector()) {
3855     ContainerVT = getContainerForFixedLengthVector(VecVT);
3856     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3857   }
3858 
3859   SDValue Mask, VL;
3860   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3861   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3862 
3863   switch (Op.getOpcode()) {
3864   default:
3865     llvm_unreachable("Unhandled reduction");
3866   case ISD::VECREDUCE_AND:
3867     // vpopc ~x == 0
3868     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, Mask, VL);
3869     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
3870     return DAG.getSetCC(DL, XLenVT, Vec, Zero, ISD::SETEQ);
3871   case ISD::VECREDUCE_OR:
3872     // vpopc x != 0
3873     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
3874     return DAG.getSetCC(DL, XLenVT, Vec, Zero, ISD::SETNE);
3875   case ISD::VECREDUCE_XOR: {
3876     // ((vpopc x) & 1) != 0
3877     SDValue One = DAG.getConstant(1, DL, XLenVT);
3878     Vec = DAG.getNode(RISCVISD::VPOPC_VL, DL, XLenVT, Vec, Mask, VL);
3879     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
3880     return DAG.getSetCC(DL, XLenVT, Vec, Zero, ISD::SETNE);
3881   }
3882   }
3883 }
3884 
3885 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
3886                                             SelectionDAG &DAG) const {
3887   SDLoc DL(Op);
3888   SDValue Vec = Op.getOperand(0);
3889   EVT VecEVT = Vec.getValueType();
3890 
3891   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
3892 
3893   // Due to ordering in legalize types we may have a vector type that needs to
3894   // be split. Do that manually so we can get down to a legal type.
3895   while (getTypeAction(*DAG.getContext(), VecEVT) ==
3896          TargetLowering::TypeSplitVector) {
3897     SDValue Lo, Hi;
3898     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
3899     VecEVT = Lo.getValueType();
3900     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
3901   }
3902 
3903   // TODO: The type may need to be widened rather than split. Or widened before
3904   // it can be split.
3905   if (!isTypeLegal(VecEVT))
3906     return SDValue();
3907 
3908   MVT VecVT = VecEVT.getSimpleVT();
3909   MVT VecEltVT = VecVT.getVectorElementType();
3910   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
3911 
3912   MVT ContainerVT = VecVT;
3913   if (VecVT.isFixedLengthVector()) {
3914     ContainerVT = getContainerForFixedLengthVector(VecVT);
3915     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
3916   }
3917 
3918   MVT M1VT = getLMUL1VT(ContainerVT);
3919 
3920   SDValue Mask, VL;
3921   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3922 
3923   // FIXME: This is a VLMAX splat which might be too large and can prevent
3924   // vsetvli removal.
3925   SDValue NeutralElem =
3926       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
3927   SDValue IdentitySplat = DAG.getSplatVector(M1VT, DL, NeutralElem);
3928   SDValue Reduction =
3929       DAG.getNode(RVVOpcode, DL, M1VT, Vec, IdentitySplat, Mask, VL);
3930   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
3931                              DAG.getConstant(0, DL, Subtarget.getXLenVT()));
3932   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
3933 }
3934 
3935 // Given a reduction op, this function returns the matching reduction opcode,
3936 // the vector SDValue and the scalar SDValue required to lower this to a
3937 // RISCVISD node.
3938 static std::tuple<unsigned, SDValue, SDValue>
3939 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
3940   SDLoc DL(Op);
3941   auto Flags = Op->getFlags();
3942   unsigned Opcode = Op.getOpcode();
3943   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
3944   switch (Opcode) {
3945   default:
3946     llvm_unreachable("Unhandled reduction");
3947   case ISD::VECREDUCE_FADD:
3948     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0),
3949                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
3950   case ISD::VECREDUCE_SEQ_FADD:
3951     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
3952                            Op.getOperand(0));
3953   case ISD::VECREDUCE_FMIN:
3954     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
3955                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
3956   case ISD::VECREDUCE_FMAX:
3957     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
3958                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
3959   }
3960 }
3961 
3962 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
3963                                               SelectionDAG &DAG) const {
3964   SDLoc DL(Op);
3965   MVT VecEltVT = Op.getSimpleValueType();
3966 
3967   unsigned RVVOpcode;
3968   SDValue VectorVal, ScalarVal;
3969   std::tie(RVVOpcode, VectorVal, ScalarVal) =
3970       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
3971   MVT VecVT = VectorVal.getSimpleValueType();
3972 
3973   MVT ContainerVT = VecVT;
3974   if (VecVT.isFixedLengthVector()) {
3975     ContainerVT = getContainerForFixedLengthVector(VecVT);
3976     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
3977   }
3978 
3979   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
3980 
3981   SDValue Mask, VL;
3982   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
3983 
3984   // FIXME: This is a VLMAX splat which might be too large and can prevent
3985   // vsetvli removal.
3986   SDValue ScalarSplat = DAG.getSplatVector(M1VT, DL, ScalarVal);
3987   SDValue Reduction =
3988       DAG.getNode(RVVOpcode, DL, M1VT, VectorVal, ScalarSplat, Mask, VL);
3989   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
3990                      DAG.getConstant(0, DL, Subtarget.getXLenVT()));
3991 }
3992 
3993 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
3994                                                    SelectionDAG &DAG) const {
3995   SDValue Vec = Op.getOperand(0);
3996   SDValue SubVec = Op.getOperand(1);
3997   MVT VecVT = Vec.getSimpleValueType();
3998   MVT SubVecVT = SubVec.getSimpleValueType();
3999 
4000   SDLoc DL(Op);
4001   MVT XLenVT = Subtarget.getXLenVT();
4002   unsigned OrigIdx = Op.getConstantOperandVal(2);
4003   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4004 
4005   // We don't have the ability to slide mask vectors up indexed by their i1
4006   // elements; the smallest we can do is i8. Often we are able to bitcast to
4007   // equivalent i8 vectors. Note that when inserting a fixed-length vector
4008   // into a scalable one, we might not necessarily have enough scalable
4009   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
4010   if (SubVecVT.getVectorElementType() == MVT::i1 &&
4011       (OrigIdx != 0 || !Vec.isUndef())) {
4012     if (VecVT.getVectorMinNumElements() >= 8 &&
4013         SubVecVT.getVectorMinNumElements() >= 8) {
4014       assert(OrigIdx % 8 == 0 && "Invalid index");
4015       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4016              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4017              "Unexpected mask vector lowering");
4018       OrigIdx /= 8;
4019       SubVecVT =
4020           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4021                            SubVecVT.isScalableVector());
4022       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4023                                VecVT.isScalableVector());
4024       Vec = DAG.getBitcast(VecVT, Vec);
4025       SubVec = DAG.getBitcast(SubVecVT, SubVec);
4026     } else {
4027       // We can't slide this mask vector up indexed by its i1 elements.
4028       // This poses a problem when we wish to insert a scalable vector which
4029       // can't be re-expressed as a larger type. Just choose the slow path and
4030       // extend to a larger type, then truncate back down.
4031       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4032       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4033       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4034       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
4035       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
4036                         Op.getOperand(2));
4037       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
4038       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
4039     }
4040   }
4041 
4042   // If the subvector vector is a fixed-length type, we cannot use subregister
4043   // manipulation to simplify the codegen; we don't know which register of a
4044   // LMUL group contains the specific subvector as we only know the minimum
4045   // register size. Therefore we must slide the vector group up the full
4046   // amount.
4047   if (SubVecVT.isFixedLengthVector()) {
4048     if (OrigIdx == 0 && Vec.isUndef())
4049       return Op;
4050     MVT ContainerVT = VecVT;
4051     if (VecVT.isFixedLengthVector()) {
4052       ContainerVT = getContainerForFixedLengthVector(VecVT);
4053       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4054     }
4055     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
4056                          DAG.getUNDEF(ContainerVT), SubVec,
4057                          DAG.getConstant(0, DL, XLenVT));
4058     SDValue Mask =
4059         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4060     // Set the vector length to only the number of elements we care about. Note
4061     // that for slideup this includes the offset.
4062     SDValue VL =
4063         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
4064     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4065     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4066                                   SubVec, SlideupAmt, Mask, VL);
4067     if (VecVT.isFixedLengthVector())
4068       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4069     return DAG.getBitcast(Op.getValueType(), Slideup);
4070   }
4071 
4072   unsigned SubRegIdx, RemIdx;
4073   std::tie(SubRegIdx, RemIdx) =
4074       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4075           VecVT, SubVecVT, OrigIdx, TRI);
4076 
4077   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
4078   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
4079                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
4080                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
4081 
4082   // 1. If the Idx has been completely eliminated and this subvector's size is
4083   // a vector register or a multiple thereof, or the surrounding elements are
4084   // undef, then this is a subvector insert which naturally aligns to a vector
4085   // register. These can easily be handled using subregister manipulation.
4086   // 2. If the subvector is smaller than a vector register, then the insertion
4087   // must preserve the undisturbed elements of the register. We do this by
4088   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
4089   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
4090   // subvector within the vector register, and an INSERT_SUBVECTOR of that
4091   // LMUL=1 type back into the larger vector (resolving to another subregister
4092   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
4093   // to avoid allocating a large register group to hold our subvector.
4094   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
4095     return Op;
4096 
4097   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
4098   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
4099   // (in our case undisturbed). This means we can set up a subvector insertion
4100   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
4101   // size of the subvector.
4102   MVT InterSubVT = VecVT;
4103   SDValue AlignedExtract = Vec;
4104   unsigned AlignedIdx = OrigIdx - RemIdx;
4105   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4106     InterSubVT = getLMUL1VT(VecVT);
4107     // Extract a subvector equal to the nearest full vector register type. This
4108     // should resolve to a EXTRACT_SUBREG instruction.
4109     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4110                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
4111   }
4112 
4113   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4114   // For scalable vectors this must be further multiplied by vscale.
4115   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
4116 
4117   SDValue Mask, VL;
4118   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4119 
4120   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
4121   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
4122   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
4123   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
4124 
4125   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
4126                        DAG.getUNDEF(InterSubVT), SubVec,
4127                        DAG.getConstant(0, DL, XLenVT));
4128 
4129   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
4130                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
4131 
4132   // If required, insert this subvector back into the correct vector register.
4133   // This should resolve to an INSERT_SUBREG instruction.
4134   if (VecVT.bitsGT(InterSubVT))
4135     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
4136                           DAG.getConstant(AlignedIdx, DL, XLenVT));
4137 
4138   // We might have bitcast from a mask type: cast back to the original type if
4139   // required.
4140   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
4141 }
4142 
4143 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
4144                                                     SelectionDAG &DAG) const {
4145   SDValue Vec = Op.getOperand(0);
4146   MVT SubVecVT = Op.getSimpleValueType();
4147   MVT VecVT = Vec.getSimpleValueType();
4148 
4149   SDLoc DL(Op);
4150   MVT XLenVT = Subtarget.getXLenVT();
4151   unsigned OrigIdx = Op.getConstantOperandVal(1);
4152   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
4153 
4154   // We don't have the ability to slide mask vectors down indexed by their i1
4155   // elements; the smallest we can do is i8. Often we are able to bitcast to
4156   // equivalent i8 vectors. Note that when extracting a fixed-length vector
4157   // from a scalable one, we might not necessarily have enough scalable
4158   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
4159   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
4160     if (VecVT.getVectorMinNumElements() >= 8 &&
4161         SubVecVT.getVectorMinNumElements() >= 8) {
4162       assert(OrigIdx % 8 == 0 && "Invalid index");
4163       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
4164              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
4165              "Unexpected mask vector lowering");
4166       OrigIdx /= 8;
4167       SubVecVT =
4168           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
4169                            SubVecVT.isScalableVector());
4170       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
4171                                VecVT.isScalableVector());
4172       Vec = DAG.getBitcast(VecVT, Vec);
4173     } else {
4174       // We can't slide this mask vector down, indexed by its i1 elements.
4175       // This poses a problem when we wish to extract a scalable vector which
4176       // can't be re-expressed as a larger type. Just choose the slow path and
4177       // extend to a larger type, then truncate back down.
4178       // TODO: We could probably improve this when extracting certain fixed
4179       // from fixed, where we can extract as i8 and shift the correct element
4180       // right to reach the desired subvector?
4181       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
4182       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
4183       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
4184       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
4185                         Op.getOperand(1));
4186       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
4187       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
4188     }
4189   }
4190 
4191   // If the subvector vector is a fixed-length type, we cannot use subregister
4192   // manipulation to simplify the codegen; we don't know which register of a
4193   // LMUL group contains the specific subvector as we only know the minimum
4194   // register size. Therefore we must slide the vector group down the full
4195   // amount.
4196   if (SubVecVT.isFixedLengthVector()) {
4197     // With an index of 0 this is a cast-like subvector, which can be performed
4198     // with subregister operations.
4199     if (OrigIdx == 0)
4200       return Op;
4201     MVT ContainerVT = VecVT;
4202     if (VecVT.isFixedLengthVector()) {
4203       ContainerVT = getContainerForFixedLengthVector(VecVT);
4204       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4205     }
4206     SDValue Mask =
4207         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
4208     // Set the vector length to only the number of elements we care about. This
4209     // avoids sliding down elements we're going to discard straight away.
4210     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
4211     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
4212     SDValue Slidedown =
4213         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4214                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
4215     // Now we can use a cast-like subvector extract to get the result.
4216     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4217                             DAG.getConstant(0, DL, XLenVT));
4218     return DAG.getBitcast(Op.getValueType(), Slidedown);
4219   }
4220 
4221   unsigned SubRegIdx, RemIdx;
4222   std::tie(SubRegIdx, RemIdx) =
4223       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
4224           VecVT, SubVecVT, OrigIdx, TRI);
4225 
4226   // If the Idx has been completely eliminated then this is a subvector extract
4227   // which naturally aligns to a vector register. These can easily be handled
4228   // using subregister manipulation.
4229   if (RemIdx == 0)
4230     return Op;
4231 
4232   // Else we must shift our vector register directly to extract the subvector.
4233   // Do this using VSLIDEDOWN.
4234 
4235   // If the vector type is an LMUL-group type, extract a subvector equal to the
4236   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
4237   // instruction.
4238   MVT InterSubVT = VecVT;
4239   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
4240     InterSubVT = getLMUL1VT(VecVT);
4241     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
4242                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
4243   }
4244 
4245   // Slide this vector register down by the desired number of elements in order
4246   // to place the desired subvector starting at element 0.
4247   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
4248   // For scalable vectors this must be further multiplied by vscale.
4249   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
4250 
4251   SDValue Mask, VL;
4252   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
4253   SDValue Slidedown =
4254       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
4255                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
4256 
4257   // Now the vector is in the right position, extract our final subvector. This
4258   // should resolve to a COPY.
4259   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
4260                           DAG.getConstant(0, DL, XLenVT));
4261 
4262   // We might have bitcast from a mask type: cast back to the original type if
4263   // required.
4264   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
4265 }
4266 
4267 // Lower step_vector to the vid instruction. Any non-identity step value must
4268 // be accounted for my manual expansion.
4269 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
4270                                               SelectionDAG &DAG) const {
4271   SDLoc DL(Op);
4272   MVT VT = Op.getSimpleValueType();
4273   MVT XLenVT = Subtarget.getXLenVT();
4274   SDValue Mask, VL;
4275   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
4276   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4277   uint64_t StepValImm = Op.getConstantOperandVal(0);
4278   if (StepValImm != 1) {
4279     if (isPowerOf2_64(StepValImm)) {
4280       SDValue StepVal =
4281           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4282                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
4283       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
4284     } else {
4285       SDValue StepVal = lowerScalarSplat(
4286           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
4287           DL, DAG, Subtarget);
4288       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
4289     }
4290   }
4291   return StepVec;
4292 }
4293 
4294 // Implement vector_reverse using vrgather.vv with indices determined by
4295 // subtracting the id of each element from (VLMAX-1). This will convert
4296 // the indices like so:
4297 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
4298 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
4299 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
4300                                                  SelectionDAG &DAG) const {
4301   SDLoc DL(Op);
4302   MVT VecVT = Op.getSimpleValueType();
4303   unsigned EltSize = VecVT.getScalarSizeInBits();
4304   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
4305 
4306   unsigned MaxVLMAX = 0;
4307   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
4308   if (VectorBitsMax != 0)
4309     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
4310 
4311   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
4312   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
4313 
4314   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
4315   // to use vrgatherei16.vv.
4316   // TODO: It's also possible to use vrgatherei16.vv for other types to
4317   // decrease register width for the index calculation.
4318   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
4319     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
4320     // Reverse each half, then reassemble them in reverse order.
4321     // NOTE: It's also possible that after splitting that VLMAX no longer
4322     // requires vrgatherei16.vv.
4323     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
4324       SDValue Lo, Hi;
4325       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4326       EVT LoVT, HiVT;
4327       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
4328       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
4329       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
4330       // Reassemble the low and high pieces reversed.
4331       // FIXME: This is a CONCAT_VECTORS.
4332       SDValue Res =
4333           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
4334                       DAG.getIntPtrConstant(0, DL));
4335       return DAG.getNode(
4336           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
4337           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
4338     }
4339 
4340     // Just promote the int type to i16 which will double the LMUL.
4341     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
4342     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
4343   }
4344 
4345   MVT XLenVT = Subtarget.getXLenVT();
4346   SDValue Mask, VL;
4347   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
4348 
4349   // Calculate VLMAX-1 for the desired SEW.
4350   unsigned MinElts = VecVT.getVectorMinNumElements();
4351   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
4352                               DAG.getConstant(MinElts, DL, XLenVT));
4353   SDValue VLMinus1 =
4354       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
4355 
4356   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
4357   bool IsRV32E64 =
4358       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
4359   SDValue SplatVL;
4360   if (!IsRV32E64)
4361     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
4362   else
4363     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
4364 
4365   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
4366   SDValue Indices =
4367       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
4368 
4369   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
4370 }
4371 
4372 SDValue
4373 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
4374                                                      SelectionDAG &DAG) const {
4375   SDLoc DL(Op);
4376   auto *Load = cast<LoadSDNode>(Op);
4377 
4378   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
4379                                         Load->getMemoryVT(),
4380                                         *Load->getMemOperand()) &&
4381          "Expecting a correctly-aligned load");
4382 
4383   MVT VT = Op.getSimpleValueType();
4384   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4385 
4386   SDValue VL =
4387       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4388 
4389   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4390   SDValue NewLoad = DAG.getMemIntrinsicNode(
4391       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
4392       Load->getMemoryVT(), Load->getMemOperand());
4393 
4394   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
4395   return DAG.getMergeValues({Result, Load->getChain()}, DL);
4396 }
4397 
4398 SDValue
4399 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
4400                                                       SelectionDAG &DAG) const {
4401   SDLoc DL(Op);
4402   auto *Store = cast<StoreSDNode>(Op);
4403 
4404   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
4405                                         Store->getMemoryVT(),
4406                                         *Store->getMemOperand()) &&
4407          "Expecting a correctly-aligned store");
4408 
4409   SDValue StoreVal = Store->getValue();
4410   MVT VT = StoreVal.getSimpleValueType();
4411 
4412   // If the size less than a byte, we need to pad with zeros to make a byte.
4413   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
4414     VT = MVT::v8i1;
4415     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
4416                            DAG.getConstant(0, DL, VT), StoreVal,
4417                            DAG.getIntPtrConstant(0, DL));
4418   }
4419 
4420   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4421 
4422   SDValue VL =
4423       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4424 
4425   SDValue NewValue =
4426       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
4427   return DAG.getMemIntrinsicNode(
4428       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
4429       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
4430       Store->getMemoryVT(), Store->getMemOperand());
4431 }
4432 
4433 SDValue RISCVTargetLowering::lowerMLOAD(SDValue Op, SelectionDAG &DAG) const {
4434   auto *Load = cast<MaskedLoadSDNode>(Op);
4435 
4436   SDLoc DL(Op);
4437   MVT VT = Op.getSimpleValueType();
4438   MVT XLenVT = Subtarget.getXLenVT();
4439 
4440   SDValue Mask = Load->getMask();
4441   SDValue PassThru = Load->getPassThru();
4442   SDValue VL;
4443 
4444   MVT ContainerVT = VT;
4445   if (VT.isFixedLengthVector()) {
4446     ContainerVT = getContainerForFixedLengthVector(VT);
4447     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4448 
4449     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4450     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4451     VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4452   } else
4453     VL = DAG.getRegister(RISCV::X0, XLenVT);
4454 
4455   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4456   SDValue IntID = DAG.getTargetConstant(Intrinsic::riscv_vle_mask, DL, XLenVT);
4457   SDValue Ops[] = {Load->getChain(),   IntID, PassThru,
4458                    Load->getBasePtr(), Mask,  VL};
4459   SDValue Result =
4460       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4461                               Load->getMemoryVT(), Load->getMemOperand());
4462   SDValue Chain = Result.getValue(1);
4463 
4464   if (VT.isFixedLengthVector())
4465     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4466 
4467   return DAG.getMergeValues({Result, Chain}, DL);
4468 }
4469 
4470 SDValue RISCVTargetLowering::lowerMSTORE(SDValue Op, SelectionDAG &DAG) const {
4471   auto *Store = cast<MaskedStoreSDNode>(Op);
4472 
4473   SDLoc DL(Op);
4474   SDValue Val = Store->getValue();
4475   SDValue Mask = Store->getMask();
4476   MVT VT = Val.getSimpleValueType();
4477   MVT XLenVT = Subtarget.getXLenVT();
4478   SDValue VL;
4479 
4480   MVT ContainerVT = VT;
4481   if (VT.isFixedLengthVector()) {
4482     ContainerVT = getContainerForFixedLengthVector(VT);
4483     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4484 
4485     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4486     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4487     VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4488   } else
4489     VL = DAG.getRegister(RISCV::X0, XLenVT);
4490 
4491   SDValue IntID = DAG.getTargetConstant(Intrinsic::riscv_vse_mask, DL, XLenVT);
4492   return DAG.getMemIntrinsicNode(
4493       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
4494       {Store->getChain(), IntID, Val, Store->getBasePtr(), Mask, VL},
4495       Store->getMemoryVT(), Store->getMemOperand());
4496 }
4497 
4498 SDValue
4499 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
4500                                                       SelectionDAG &DAG) const {
4501   MVT InVT = Op.getOperand(0).getSimpleValueType();
4502   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
4503 
4504   MVT VT = Op.getSimpleValueType();
4505 
4506   SDValue Op1 =
4507       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4508   SDValue Op2 =
4509       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
4510 
4511   SDLoc DL(Op);
4512   SDValue VL =
4513       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
4514 
4515   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4516   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4517 
4518   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
4519                             Op.getOperand(2), Mask, VL);
4520 
4521   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
4522 }
4523 
4524 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
4525     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
4526   MVT VT = Op.getSimpleValueType();
4527 
4528   if (VT.getVectorElementType() == MVT::i1)
4529     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
4530 
4531   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
4532 }
4533 
4534 SDValue
4535 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
4536                                                       SelectionDAG &DAG) const {
4537   unsigned Opc;
4538   switch (Op.getOpcode()) {
4539   default: llvm_unreachable("Unexpected opcode!");
4540   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
4541   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
4542   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
4543   }
4544 
4545   return lowerToScalableOp(Op, DAG, Opc);
4546 }
4547 
4548 // Lower vector ABS to smax(X, sub(0, X)).
4549 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
4550   SDLoc DL(Op);
4551   MVT VT = Op.getSimpleValueType();
4552   SDValue X = Op.getOperand(0);
4553 
4554   assert(VT.isFixedLengthVector() && "Unexpected type");
4555 
4556   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4557   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
4558 
4559   SDValue Mask, VL;
4560   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4561 
4562   SDValue SplatZero =
4563       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4564                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
4565   SDValue NegX =
4566       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
4567   SDValue Max =
4568       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
4569 
4570   return convertFromScalableVector(VT, Max, DAG, Subtarget);
4571 }
4572 
4573 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
4574     SDValue Op, SelectionDAG &DAG) const {
4575   SDLoc DL(Op);
4576   MVT VT = Op.getSimpleValueType();
4577   SDValue Mag = Op.getOperand(0);
4578   SDValue Sign = Op.getOperand(1);
4579   assert(Mag.getValueType() == Sign.getValueType() &&
4580          "Can only handle COPYSIGN with matching types.");
4581 
4582   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4583   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
4584   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
4585 
4586   SDValue Mask, VL;
4587   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4588 
4589   SDValue CopySign =
4590       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
4591 
4592   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
4593 }
4594 
4595 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
4596     SDValue Op, SelectionDAG &DAG) const {
4597   MVT VT = Op.getSimpleValueType();
4598   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4599 
4600   MVT I1ContainerVT =
4601       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4602 
4603   SDValue CC =
4604       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
4605   SDValue Op1 =
4606       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
4607   SDValue Op2 =
4608       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
4609 
4610   SDLoc DL(Op);
4611   SDValue Mask, VL;
4612   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4613 
4614   SDValue Select =
4615       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
4616 
4617   return convertFromScalableVector(VT, Select, DAG, Subtarget);
4618 }
4619 
4620 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
4621                                                unsigned NewOpc,
4622                                                bool HasMask) const {
4623   MVT VT = Op.getSimpleValueType();
4624   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4625 
4626   // Create list of operands by converting existing ones to scalable types.
4627   SmallVector<SDValue, 6> Ops;
4628   for (const SDValue &V : Op->op_values()) {
4629     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
4630 
4631     // Pass through non-vector operands.
4632     if (!V.getValueType().isVector()) {
4633       Ops.push_back(V);
4634       continue;
4635     }
4636 
4637     // "cast" fixed length vector to a scalable vector.
4638     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
4639            "Only fixed length vectors are supported!");
4640     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
4641   }
4642 
4643   SDLoc DL(Op);
4644   SDValue Mask, VL;
4645   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4646   if (HasMask)
4647     Ops.push_back(Mask);
4648   Ops.push_back(VL);
4649 
4650   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
4651   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
4652 }
4653 
4654 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
4655 // * Operands of each node are assumed to be in the same order.
4656 // * The EVL operand is promoted from i32 to i64 on RV64.
4657 // * Fixed-length vectors are converted to their scalable-vector container
4658 //   types.
4659 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
4660                                        unsigned RISCVISDOpc) const {
4661   SDLoc DL(Op);
4662   MVT VT = Op.getSimpleValueType();
4663   SmallVector<SDValue, 4> Ops;
4664 
4665   for (const auto &OpIdx : enumerate(Op->ops())) {
4666     SDValue V = OpIdx.value();
4667     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
4668     // Pass through operands which aren't fixed-length vectors.
4669     if (!V.getValueType().isFixedLengthVector()) {
4670       Ops.push_back(V);
4671       continue;
4672     }
4673     // "cast" fixed length vector to a scalable vector.
4674     MVT OpVT = V.getSimpleValueType();
4675     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
4676     assert(useRVVForFixedLengthVectorVT(OpVT) &&
4677            "Only fixed length vectors are supported!");
4678     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
4679   }
4680 
4681   if (!VT.isFixedLengthVector())
4682     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
4683 
4684   MVT ContainerVT = getContainerForFixedLengthVector(VT);
4685 
4686   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
4687 
4688   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
4689 }
4690 
4691 // Custom lower MGATHER to a legalized form for RVV. It will then be matched to
4692 // a RVV indexed load. The RVV indexed load instructions only support the
4693 // "unsigned unscaled" addressing mode; indices are implicitly zero-extended or
4694 // truncated to XLEN and are treated as byte offsets. Any signed or scaled
4695 // indexing is extended to the XLEN value type and scaled accordingly.
4696 SDValue RISCVTargetLowering::lowerMGATHER(SDValue Op, SelectionDAG &DAG) const {
4697   auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
4698   SDLoc DL(Op);
4699 
4700   SDValue Index = MGN->getIndex();
4701   SDValue Mask = MGN->getMask();
4702   SDValue PassThru = MGN->getPassThru();
4703 
4704   MVT VT = Op.getSimpleValueType();
4705   MVT IndexVT = Index.getSimpleValueType();
4706   MVT XLenVT = Subtarget.getXLenVT();
4707 
4708   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
4709          "Unexpected VTs!");
4710   assert(MGN->getBasePtr().getSimpleValueType() == XLenVT &&
4711          "Unexpected pointer type");
4712   // Targets have to explicitly opt-in for extending vector loads.
4713   assert(MGN->getExtensionType() == ISD::NON_EXTLOAD &&
4714          "Unexpected extending MGATHER");
4715 
4716   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4717   // the selection of the masked intrinsics doesn't do this for us.
4718   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4719 
4720   SDValue VL;
4721   MVT ContainerVT = VT;
4722   if (VT.isFixedLengthVector()) {
4723     // We need to use the larger of the result and index type to determine the
4724     // scalable type to use so we don't increase LMUL for any operand/result.
4725     if (VT.bitsGE(IndexVT)) {
4726       ContainerVT = getContainerForFixedLengthVector(VT);
4727       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
4728                                  ContainerVT.getVectorElementCount());
4729     } else {
4730       IndexVT = getContainerForFixedLengthVector(IndexVT);
4731       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
4732                                      IndexVT.getVectorElementCount());
4733     }
4734 
4735     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
4736 
4737     if (!IsUnmasked) {
4738       MVT MaskVT =
4739           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4740       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4741       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4742     }
4743 
4744     VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4745   } else
4746     VL = DAG.getRegister(RISCV::X0, XLenVT);
4747 
4748   unsigned IntID =
4749       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
4750   SmallVector<SDValue, 8> Ops{MGN->getChain(),
4751                               DAG.getTargetConstant(IntID, DL, XLenVT)};
4752   if (!IsUnmasked)
4753     Ops.push_back(PassThru);
4754   Ops.push_back(MGN->getBasePtr());
4755   Ops.push_back(Index);
4756   if (!IsUnmasked)
4757     Ops.push_back(Mask);
4758   Ops.push_back(VL);
4759 
4760   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4761   SDValue Result =
4762       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4763                               MGN->getMemoryVT(), MGN->getMemOperand());
4764   SDValue Chain = Result.getValue(1);
4765 
4766   if (VT.isFixedLengthVector())
4767     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4768 
4769   return DAG.getMergeValues({Result, Chain}, DL);
4770 }
4771 
4772 // Custom lower MSCATTER to a legalized form for RVV. It will then be matched to
4773 // a RVV indexed store. The RVV indexed store instructions only support the
4774 // "unsigned unscaled" addressing mode; indices are implicitly zero-extended or
4775 // truncated to XLEN and are treated as byte offsets. Any signed or scaled
4776 // indexing is extended to the XLEN value type and scaled accordingly.
4777 SDValue RISCVTargetLowering::lowerMSCATTER(SDValue Op,
4778                                            SelectionDAG &DAG) const {
4779   auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
4780   SDLoc DL(Op);
4781   SDValue Index = MSN->getIndex();
4782   SDValue Mask = MSN->getMask();
4783   SDValue Val = MSN->getValue();
4784 
4785   MVT VT = Val.getSimpleValueType();
4786   MVT IndexVT = Index.getSimpleValueType();
4787   MVT XLenVT = Subtarget.getXLenVT();
4788 
4789   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
4790          "Unexpected VTs!");
4791   assert(MSN->getBasePtr().getSimpleValueType() == XLenVT &&
4792          "Unexpected pointer type");
4793   // Targets have to explicitly opt-in for extending vector loads and
4794   // truncating vector stores.
4795   assert(!MSN->isTruncatingStore() && "Unexpected extending MSCATTER");
4796 
4797   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4798   // the selection of the masked intrinsics doesn't do this for us.
4799   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4800 
4801   SDValue VL;
4802   if (VT.isFixedLengthVector()) {
4803     // We need to use the larger of the value and index type to determine the
4804     // scalable type to use so we don't increase LMUL for any operand/result.
4805     MVT ContainerVT;
4806     if (VT.bitsGE(IndexVT)) {
4807       ContainerVT = getContainerForFixedLengthVector(VT);
4808       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
4809                                  ContainerVT.getVectorElementCount());
4810     } else {
4811       IndexVT = getContainerForFixedLengthVector(IndexVT);
4812       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4813                                      IndexVT.getVectorElementCount());
4814     }
4815 
4816     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
4817     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4818 
4819     if (!IsUnmasked) {
4820       MVT MaskVT =
4821           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4822       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4823     }
4824 
4825     VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4826   } else
4827     VL = DAG.getRegister(RISCV::X0, XLenVT);
4828 
4829   unsigned IntID =
4830       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
4831   SmallVector<SDValue, 8> Ops{MSN->getChain(),
4832                               DAG.getTargetConstant(IntID, DL, XLenVT)};
4833   Ops.push_back(Val);
4834   Ops.push_back(MSN->getBasePtr());
4835   Ops.push_back(Index);
4836   if (!IsUnmasked)
4837     Ops.push_back(Mask);
4838   Ops.push_back(VL);
4839 
4840   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, MSN->getVTList(), Ops,
4841                                  MSN->getMemoryVT(), MSN->getMemOperand());
4842 }
4843 
4844 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
4845                                                SelectionDAG &DAG) const {
4846   const MVT XLenVT = Subtarget.getXLenVT();
4847   SDLoc DL(Op);
4848   SDValue Chain = Op->getOperand(0);
4849   SDValue SysRegNo = DAG.getConstant(
4850       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
4851   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
4852   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
4853 
4854   // Encoding used for rounding mode in RISCV differs from that used in
4855   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
4856   // table, which consists of a sequence of 4-bit fields, each representing
4857   // corresponding FLT_ROUNDS mode.
4858   static const int Table =
4859       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
4860       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
4861       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
4862       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
4863       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
4864 
4865   SDValue Shift =
4866       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
4867   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
4868                                 DAG.getConstant(Table, DL, XLenVT), Shift);
4869   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
4870                                DAG.getConstant(7, DL, XLenVT));
4871 
4872   return DAG.getMergeValues({Masked, Chain}, DL);
4873 }
4874 
4875 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
4876                                                SelectionDAG &DAG) const {
4877   const MVT XLenVT = Subtarget.getXLenVT();
4878   SDLoc DL(Op);
4879   SDValue Chain = Op->getOperand(0);
4880   SDValue RMValue = Op->getOperand(1);
4881   SDValue SysRegNo = DAG.getConstant(
4882       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
4883 
4884   // Encoding used for rounding mode in RISCV differs from that used in
4885   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
4886   // a table, which consists of a sequence of 4-bit fields, each representing
4887   // corresponding RISCV mode.
4888   static const unsigned Table =
4889       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
4890       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
4891       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
4892       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
4893       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
4894 
4895   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
4896                               DAG.getConstant(2, DL, XLenVT));
4897   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
4898                                 DAG.getConstant(Table, DL, XLenVT), Shift);
4899   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
4900                         DAG.getConstant(0x7, DL, XLenVT));
4901   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
4902                      RMValue);
4903 }
4904 
4905 // Returns the opcode of the target-specific SDNode that implements the 32-bit
4906 // form of the given Opcode.
4907 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
4908   switch (Opcode) {
4909   default:
4910     llvm_unreachable("Unexpected opcode");
4911   case ISD::SHL:
4912     return RISCVISD::SLLW;
4913   case ISD::SRA:
4914     return RISCVISD::SRAW;
4915   case ISD::SRL:
4916     return RISCVISD::SRLW;
4917   case ISD::SDIV:
4918     return RISCVISD::DIVW;
4919   case ISD::UDIV:
4920     return RISCVISD::DIVUW;
4921   case ISD::UREM:
4922     return RISCVISD::REMUW;
4923   case ISD::ROTL:
4924     return RISCVISD::ROLW;
4925   case ISD::ROTR:
4926     return RISCVISD::RORW;
4927   case RISCVISD::GREV:
4928     return RISCVISD::GREVW;
4929   case RISCVISD::GORC:
4930     return RISCVISD::GORCW;
4931   }
4932 }
4933 
4934 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
4935 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
4936 // otherwise be promoted to i64, making it difficult to select the
4937 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
4938 // type i8/i16/i32 is lost.
4939 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
4940                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
4941   SDLoc DL(N);
4942   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
4943   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
4944   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
4945   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
4946   // ReplaceNodeResults requires we maintain the same type for the return value.
4947   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
4948 }
4949 
4950 // Converts the given 32-bit operation to a i64 operation with signed extension
4951 // semantic to reduce the signed extension instructions.
4952 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
4953   SDLoc DL(N);
4954   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
4955   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
4956   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
4957   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
4958                                DAG.getValueType(MVT::i32));
4959   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
4960 }
4961 
4962 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
4963                                              SmallVectorImpl<SDValue> &Results,
4964                                              SelectionDAG &DAG) const {
4965   SDLoc DL(N);
4966   switch (N->getOpcode()) {
4967   default:
4968     llvm_unreachable("Don't know how to custom type legalize this operation!");
4969   case ISD::STRICT_FP_TO_SINT:
4970   case ISD::STRICT_FP_TO_UINT:
4971   case ISD::FP_TO_SINT:
4972   case ISD::FP_TO_UINT: {
4973     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
4974            "Unexpected custom legalisation");
4975     bool IsStrict = N->isStrictFPOpcode();
4976     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
4977                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
4978     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
4979     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
4980         TargetLowering::TypeSoftenFloat) {
4981       // FIXME: Support strict FP.
4982       if (IsStrict)
4983         return;
4984       if (!isTypeLegal(Op0.getValueType()))
4985         return;
4986       unsigned Opc =
4987           IsSigned ? RISCVISD::FCVT_W_RTZ_RV64 : RISCVISD::FCVT_WU_RTZ_RV64;
4988       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0);
4989       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
4990       return;
4991     }
4992     // If the FP type needs to be softened, emit a library call using the 'si'
4993     // version. If we left it to default legalization we'd end up with 'di'. If
4994     // the FP type doesn't need to be softened just let generic type
4995     // legalization promote the result type.
4996     RTLIB::Libcall LC;
4997     if (IsSigned)
4998       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
4999     else
5000       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
5001     MakeLibCallOptions CallOptions;
5002     EVT OpVT = Op0.getValueType();
5003     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
5004     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
5005     SDValue Result;
5006     std::tie(Result, Chain) =
5007         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
5008     Results.push_back(Result);
5009     if (IsStrict)
5010       Results.push_back(Chain);
5011     break;
5012   }
5013   case ISD::READCYCLECOUNTER: {
5014     assert(!Subtarget.is64Bit() &&
5015            "READCYCLECOUNTER only has custom type legalization on riscv32");
5016 
5017     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5018     SDValue RCW =
5019         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
5020 
5021     Results.push_back(
5022         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
5023     Results.push_back(RCW.getValue(2));
5024     break;
5025   }
5026   case ISD::MUL: {
5027     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
5028     unsigned XLen = Subtarget.getXLen();
5029     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
5030     if (Size > XLen) {
5031       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
5032       SDValue LHS = N->getOperand(0);
5033       SDValue RHS = N->getOperand(1);
5034       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
5035 
5036       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
5037       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
5038       // We need exactly one side to be unsigned.
5039       if (LHSIsU == RHSIsU)
5040         return;
5041 
5042       auto MakeMULPair = [&](SDValue S, SDValue U) {
5043         MVT XLenVT = Subtarget.getXLenVT();
5044         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
5045         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
5046         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
5047         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
5048         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
5049       };
5050 
5051       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
5052       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
5053 
5054       // The other operand should be signed, but still prefer MULH when
5055       // possible.
5056       if (RHSIsU && LHSIsS && !RHSIsS)
5057         Results.push_back(MakeMULPair(LHS, RHS));
5058       else if (LHSIsU && RHSIsS && !LHSIsS)
5059         Results.push_back(MakeMULPair(RHS, LHS));
5060 
5061       return;
5062     }
5063     LLVM_FALLTHROUGH;
5064   }
5065   case ISD::ADD:
5066   case ISD::SUB:
5067     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5068            "Unexpected custom legalisation");
5069     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
5070     break;
5071   case ISD::SHL:
5072   case ISD::SRA:
5073   case ISD::SRL:
5074     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5075            "Unexpected custom legalisation");
5076     if (N->getOperand(1).getOpcode() != ISD::Constant) {
5077       Results.push_back(customLegalizeToWOp(N, DAG));
5078       break;
5079     }
5080 
5081     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
5082     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
5083     // shift amount.
5084     if (N->getOpcode() == ISD::SHL) {
5085       SDLoc DL(N);
5086       SDValue NewOp0 =
5087           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5088       SDValue NewOp1 =
5089           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
5090       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
5091       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
5092                                    DAG.getValueType(MVT::i32));
5093       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5094     }
5095 
5096     break;
5097   case ISD::ROTL:
5098   case ISD::ROTR:
5099     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5100            "Unexpected custom legalisation");
5101     Results.push_back(customLegalizeToWOp(N, DAG));
5102     break;
5103   case ISD::CTTZ:
5104   case ISD::CTTZ_ZERO_UNDEF:
5105   case ISD::CTLZ:
5106   case ISD::CTLZ_ZERO_UNDEF: {
5107     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5108            "Unexpected custom legalisation");
5109 
5110     SDValue NewOp0 =
5111         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5112     bool IsCTZ =
5113         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
5114     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
5115     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
5116     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5117     return;
5118   }
5119   case ISD::SDIV:
5120   case ISD::UDIV:
5121   case ISD::UREM: {
5122     MVT VT = N->getSimpleValueType(0);
5123     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
5124            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
5125            "Unexpected custom legalisation");
5126     // Don't promote division/remainder by constant since we should expand those
5127     // to multiply by magic constant.
5128     // FIXME: What if the expansion is disabled for minsize.
5129     if (N->getOperand(1).getOpcode() == ISD::Constant)
5130       return;
5131 
5132     // If the input is i32, use ANY_EXTEND since the W instructions don't read
5133     // the upper 32 bits. For other types we need to sign or zero extend
5134     // based on the opcode.
5135     unsigned ExtOpc = ISD::ANY_EXTEND;
5136     if (VT != MVT::i32)
5137       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
5138                                            : ISD::ZERO_EXTEND;
5139 
5140     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
5141     break;
5142   }
5143   case ISD::UADDO:
5144   case ISD::USUBO: {
5145     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5146            "Unexpected custom legalisation");
5147     bool IsAdd = N->getOpcode() == ISD::UADDO;
5148     // Create an ADDW or SUBW.
5149     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5150     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5151     SDValue Res =
5152         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
5153     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
5154                       DAG.getValueType(MVT::i32));
5155 
5156     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
5157     // Since the inputs are sign extended from i32, this is equivalent to
5158     // comparing the lower 32 bits.
5159     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5160     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
5161                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
5162 
5163     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5164     Results.push_back(Overflow);
5165     return;
5166   }
5167   case ISD::UADDSAT:
5168   case ISD::USUBSAT: {
5169     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5170            "Unexpected custom legalisation");
5171     if (Subtarget.hasStdExtZbb()) {
5172       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
5173       // sign extend allows overflow of the lower 32 bits to be detected on
5174       // the promoted size.
5175       SDValue LHS =
5176           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5177       SDValue RHS =
5178           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
5179       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
5180       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5181       return;
5182     }
5183 
5184     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
5185     // promotion for UADDO/USUBO.
5186     Results.push_back(expandAddSubSat(N, DAG));
5187     return;
5188   }
5189   case ISD::BITCAST: {
5190     EVT VT = N->getValueType(0);
5191     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
5192     SDValue Op0 = N->getOperand(0);
5193     EVT Op0VT = Op0.getValueType();
5194     MVT XLenVT = Subtarget.getXLenVT();
5195     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
5196       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
5197       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
5198     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
5199                Subtarget.hasStdExtF()) {
5200       SDValue FPConv =
5201           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
5202       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
5203     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
5204                isTypeLegal(Op0VT)) {
5205       // Custom-legalize bitcasts from fixed-length vector types to illegal
5206       // scalar types in order to improve codegen. Bitcast the vector to a
5207       // one-element vector type whose element type is the same as the result
5208       // type, and extract the first element.
5209       LLVMContext &Context = *DAG.getContext();
5210       SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0);
5211       Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
5212                                     DAG.getConstant(0, DL, XLenVT)));
5213     }
5214     break;
5215   }
5216   case RISCVISD::GREV:
5217   case RISCVISD::GORC: {
5218     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5219            "Unexpected custom legalisation");
5220     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5221     // This is similar to customLegalizeToWOp, except that we pass the second
5222     // operand (a TargetConstant) straight through: it is already of type
5223     // XLenVT.
5224     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5225     SDValue NewOp0 =
5226         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5227     SDValue NewOp1 =
5228         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5229     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5230     // ReplaceNodeResults requires we maintain the same type for the return
5231     // value.
5232     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5233     break;
5234   }
5235   case RISCVISD::SHFL: {
5236     // There is no SHFLIW instruction, but we can just promote the operation.
5237     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5238            "Unexpected custom legalisation");
5239     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5240     SDValue NewOp0 =
5241         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5242     SDValue NewOp1 =
5243         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5244     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
5245     // ReplaceNodeResults requires we maintain the same type for the return
5246     // value.
5247     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5248     break;
5249   }
5250   case ISD::BSWAP:
5251   case ISD::BITREVERSE: {
5252     MVT VT = N->getSimpleValueType(0);
5253     MVT XLenVT = Subtarget.getXLenVT();
5254     assert((VT == MVT::i8 || VT == MVT::i16 ||
5255             (VT == MVT::i32 && Subtarget.is64Bit())) &&
5256            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
5257     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
5258     unsigned Imm = VT.getSizeInBits() - 1;
5259     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
5260     if (N->getOpcode() == ISD::BSWAP)
5261       Imm &= ~0x7U;
5262     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
5263     SDValue GREVI =
5264         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
5265     // ReplaceNodeResults requires we maintain the same type for the return
5266     // value.
5267     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
5268     break;
5269   }
5270   case ISD::FSHL:
5271   case ISD::FSHR: {
5272     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5273            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
5274     SDValue NewOp0 =
5275         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5276     SDValue NewOp1 =
5277         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5278     SDValue NewOp2 =
5279         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5280     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
5281     // Mask the shift amount to 5 bits.
5282     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5283                          DAG.getConstant(0x1f, DL, MVT::i64));
5284     unsigned Opc =
5285         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
5286     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
5287     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
5288     break;
5289   }
5290   case ISD::EXTRACT_VECTOR_ELT: {
5291     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
5292     // type is illegal (currently only vXi64 RV32).
5293     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
5294     // transferred to the destination register. We issue two of these from the
5295     // upper- and lower- halves of the SEW-bit vector element, slid down to the
5296     // first element.
5297     SDValue Vec = N->getOperand(0);
5298     SDValue Idx = N->getOperand(1);
5299 
5300     // The vector type hasn't been legalized yet so we can't issue target
5301     // specific nodes if it needs legalization.
5302     // FIXME: We would manually legalize if it's important.
5303     if (!isTypeLegal(Vec.getValueType()))
5304       return;
5305 
5306     MVT VecVT = Vec.getSimpleValueType();
5307 
5308     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
5309            VecVT.getVectorElementType() == MVT::i64 &&
5310            "Unexpected EXTRACT_VECTOR_ELT legalization");
5311 
5312     // If this is a fixed vector, we need to convert it to a scalable vector.
5313     MVT ContainerVT = VecVT;
5314     if (VecVT.isFixedLengthVector()) {
5315       ContainerVT = getContainerForFixedLengthVector(VecVT);
5316       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5317     }
5318 
5319     MVT XLenVT = Subtarget.getXLenVT();
5320 
5321     // Use a VL of 1 to avoid processing more elements than we need.
5322     MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5323     SDValue VL = DAG.getConstant(1, DL, XLenVT);
5324     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5325 
5326     // Unless the index is known to be 0, we must slide the vector down to get
5327     // the desired element into index 0.
5328     if (!isNullConstant(Idx)) {
5329       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5330                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
5331     }
5332 
5333     // Extract the lower XLEN bits of the correct vector element.
5334     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5335 
5336     // To extract the upper XLEN bits of the vector element, shift the first
5337     // element right by 32 bits and re-extract the lower XLEN bits.
5338     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5339                                      DAG.getConstant(32, DL, XLenVT), VL);
5340     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
5341                                  ThirtyTwoV, Mask, VL);
5342 
5343     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5344 
5345     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5346     break;
5347   }
5348   case ISD::INTRINSIC_WO_CHAIN: {
5349     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5350     switch (IntNo) {
5351     default:
5352       llvm_unreachable(
5353           "Don't know how to custom type legalize this intrinsic!");
5354     case Intrinsic::riscv_orc_b: {
5355       // Lower to the GORCI encoding for orc.b with the operand extended.
5356       SDValue NewOp =
5357           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5358       // If Zbp is enabled, use GORCIW which will sign extend the result.
5359       unsigned Opc =
5360           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
5361       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
5362                                 DAG.getConstant(7, DL, MVT::i64));
5363       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5364       return;
5365     }
5366     case Intrinsic::riscv_grev:
5367     case Intrinsic::riscv_gorc: {
5368       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5369              "Unexpected custom legalisation");
5370       SDValue NewOp1 =
5371           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5372       SDValue NewOp2 =
5373           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5374       unsigned Opc =
5375           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
5376       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5377       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5378       break;
5379     }
5380     case Intrinsic::riscv_shfl:
5381     case Intrinsic::riscv_unshfl: {
5382       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5383              "Unexpected custom legalisation");
5384       SDValue NewOp1 =
5385           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5386       SDValue NewOp2 =
5387           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5388       unsigned Opc =
5389           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
5390       if (isa<ConstantSDNode>(N->getOperand(2))) {
5391         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5392                              DAG.getConstant(0xf, DL, MVT::i64));
5393         Opc =
5394             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
5395       }
5396       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5397       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5398       break;
5399     }
5400     case Intrinsic::riscv_bcompress:
5401     case Intrinsic::riscv_bdecompress: {
5402       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5403              "Unexpected custom legalisation");
5404       SDValue NewOp1 =
5405           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5406       SDValue NewOp2 =
5407           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5408       unsigned Opc = IntNo == Intrinsic::riscv_bcompress
5409                          ? RISCVISD::BCOMPRESSW
5410                          : RISCVISD::BDECOMPRESSW;
5411       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5412       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5413       break;
5414     }
5415     case Intrinsic::riscv_vmv_x_s: {
5416       EVT VT = N->getValueType(0);
5417       MVT XLenVT = Subtarget.getXLenVT();
5418       if (VT.bitsLT(XLenVT)) {
5419         // Simple case just extract using vmv.x.s and truncate.
5420         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
5421                                       Subtarget.getXLenVT(), N->getOperand(1));
5422         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
5423         return;
5424       }
5425 
5426       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
5427              "Unexpected custom legalization");
5428 
5429       // We need to do the move in two steps.
5430       SDValue Vec = N->getOperand(1);
5431       MVT VecVT = Vec.getSimpleValueType();
5432 
5433       // First extract the lower XLEN bits of the element.
5434       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5435 
5436       // To extract the upper XLEN bits of the vector element, shift the first
5437       // element right by 32 bits and re-extract the lower XLEN bits.
5438       SDValue VL = DAG.getConstant(1, DL, XLenVT);
5439       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5440       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5441       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
5442                                        DAG.getConstant(32, DL, XLenVT), VL);
5443       SDValue LShr32 =
5444           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
5445       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5446 
5447       Results.push_back(
5448           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5449       break;
5450     }
5451     }
5452     break;
5453   }
5454   case ISD::VECREDUCE_ADD:
5455   case ISD::VECREDUCE_AND:
5456   case ISD::VECREDUCE_OR:
5457   case ISD::VECREDUCE_XOR:
5458   case ISD::VECREDUCE_SMAX:
5459   case ISD::VECREDUCE_UMAX:
5460   case ISD::VECREDUCE_SMIN:
5461   case ISD::VECREDUCE_UMIN:
5462     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
5463       Results.push_back(V);
5464     break;
5465   case ISD::FLT_ROUNDS_: {
5466     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
5467     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
5468     Results.push_back(Res.getValue(0));
5469     Results.push_back(Res.getValue(1));
5470     break;
5471   }
5472   }
5473 }
5474 
5475 // A structure to hold one of the bit-manipulation patterns below. Together, a
5476 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
5477 //   (or (and (shl x, 1), 0xAAAAAAAA),
5478 //       (and (srl x, 1), 0x55555555))
5479 struct RISCVBitmanipPat {
5480   SDValue Op;
5481   unsigned ShAmt;
5482   bool IsSHL;
5483 
5484   bool formsPairWith(const RISCVBitmanipPat &Other) const {
5485     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
5486   }
5487 };
5488 
5489 // Matches patterns of the form
5490 //   (and (shl x, C2), (C1 << C2))
5491 //   (and (srl x, C2), C1)
5492 //   (shl (and x, C1), C2)
5493 //   (srl (and x, (C1 << C2)), C2)
5494 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
5495 // The expected masks for each shift amount are specified in BitmanipMasks where
5496 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
5497 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
5498 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
5499 // XLen is 64.
5500 static Optional<RISCVBitmanipPat>
5501 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
5502   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
5503          "Unexpected number of masks");
5504   Optional<uint64_t> Mask;
5505   // Optionally consume a mask around the shift operation.
5506   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
5507     Mask = Op.getConstantOperandVal(1);
5508     Op = Op.getOperand(0);
5509   }
5510   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
5511     return None;
5512   bool IsSHL = Op.getOpcode() == ISD::SHL;
5513 
5514   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5515     return None;
5516   uint64_t ShAmt = Op.getConstantOperandVal(1);
5517 
5518   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
5519   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
5520     return None;
5521   // If we don't have enough masks for 64 bit, then we must be trying to
5522   // match SHFL so we're only allowed to shift 1/4 of the width.
5523   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
5524     return None;
5525 
5526   SDValue Src = Op.getOperand(0);
5527 
5528   // The expected mask is shifted left when the AND is found around SHL
5529   // patterns.
5530   //   ((x >> 1) & 0x55555555)
5531   //   ((x << 1) & 0xAAAAAAAA)
5532   bool SHLExpMask = IsSHL;
5533 
5534   if (!Mask) {
5535     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
5536     // the mask is all ones: consume that now.
5537     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
5538       Mask = Src.getConstantOperandVal(1);
5539       Src = Src.getOperand(0);
5540       // The expected mask is now in fact shifted left for SRL, so reverse the
5541       // decision.
5542       //   ((x & 0xAAAAAAAA) >> 1)
5543       //   ((x & 0x55555555) << 1)
5544       SHLExpMask = !SHLExpMask;
5545     } else {
5546       // Use a default shifted mask of all-ones if there's no AND, truncated
5547       // down to the expected width. This simplifies the logic later on.
5548       Mask = maskTrailingOnes<uint64_t>(Width);
5549       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
5550     }
5551   }
5552 
5553   unsigned MaskIdx = Log2_32(ShAmt);
5554   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
5555 
5556   if (SHLExpMask)
5557     ExpMask <<= ShAmt;
5558 
5559   if (Mask != ExpMask)
5560     return None;
5561 
5562   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
5563 }
5564 
5565 // Matches any of the following bit-manipulation patterns:
5566 //   (and (shl x, 1), (0x55555555 << 1))
5567 //   (and (srl x, 1), 0x55555555)
5568 //   (shl (and x, 0x55555555), 1)
5569 //   (srl (and x, (0x55555555 << 1)), 1)
5570 // where the shift amount and mask may vary thus:
5571 //   [1]  = 0x55555555 / 0xAAAAAAAA
5572 //   [2]  = 0x33333333 / 0xCCCCCCCC
5573 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
5574 //   [8]  = 0x00FF00FF / 0xFF00FF00
5575 //   [16] = 0x0000FFFF / 0xFFFFFFFF
5576 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
5577 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
5578   // These are the unshifted masks which we use to match bit-manipulation
5579   // patterns. They may be shifted left in certain circumstances.
5580   static const uint64_t BitmanipMasks[] = {
5581       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
5582       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
5583 
5584   return matchRISCVBitmanipPat(Op, BitmanipMasks);
5585 }
5586 
5587 // Match the following pattern as a GREVI(W) operation
5588 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
5589 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
5590                                const RISCVSubtarget &Subtarget) {
5591   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
5592   EVT VT = Op.getValueType();
5593 
5594   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
5595     auto LHS = matchGREVIPat(Op.getOperand(0));
5596     auto RHS = matchGREVIPat(Op.getOperand(1));
5597     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
5598       SDLoc DL(Op);
5599       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
5600                          DAG.getConstant(LHS->ShAmt, DL, VT));
5601     }
5602   }
5603   return SDValue();
5604 }
5605 
5606 // Matches any the following pattern as a GORCI(W) operation
5607 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
5608 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
5609 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
5610 // Note that with the variant of 3.,
5611 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
5612 // the inner pattern will first be matched as GREVI and then the outer
5613 // pattern will be matched to GORC via the first rule above.
5614 // 4.  (or (rotl/rotr x, bitwidth/2), x)
5615 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
5616                                const RISCVSubtarget &Subtarget) {
5617   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
5618   EVT VT = Op.getValueType();
5619 
5620   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
5621     SDLoc DL(Op);
5622     SDValue Op0 = Op.getOperand(0);
5623     SDValue Op1 = Op.getOperand(1);
5624 
5625     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
5626       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
5627           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
5628           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
5629         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
5630       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
5631       if ((Reverse.getOpcode() == ISD::ROTL ||
5632            Reverse.getOpcode() == ISD::ROTR) &&
5633           Reverse.getOperand(0) == X &&
5634           isa<ConstantSDNode>(Reverse.getOperand(1))) {
5635         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
5636         if (RotAmt == (VT.getSizeInBits() / 2))
5637           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
5638                              DAG.getConstant(RotAmt, DL, VT));
5639       }
5640       return SDValue();
5641     };
5642 
5643     // Check for either commutable permutation of (or (GREVI x, shamt), x)
5644     if (SDValue V = MatchOROfReverse(Op0, Op1))
5645       return V;
5646     if (SDValue V = MatchOROfReverse(Op1, Op0))
5647       return V;
5648 
5649     // OR is commutable so canonicalize its OR operand to the left
5650     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
5651       std::swap(Op0, Op1);
5652     if (Op0.getOpcode() != ISD::OR)
5653       return SDValue();
5654     SDValue OrOp0 = Op0.getOperand(0);
5655     SDValue OrOp1 = Op0.getOperand(1);
5656     auto LHS = matchGREVIPat(OrOp0);
5657     // OR is commutable so swap the operands and try again: x might have been
5658     // on the left
5659     if (!LHS) {
5660       std::swap(OrOp0, OrOp1);
5661       LHS = matchGREVIPat(OrOp0);
5662     }
5663     auto RHS = matchGREVIPat(Op1);
5664     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
5665       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
5666                          DAG.getConstant(LHS->ShAmt, DL, VT));
5667     }
5668   }
5669   return SDValue();
5670 }
5671 
5672 // Matches any of the following bit-manipulation patterns:
5673 //   (and (shl x, 1), (0x22222222 << 1))
5674 //   (and (srl x, 1), 0x22222222)
5675 //   (shl (and x, 0x22222222), 1)
5676 //   (srl (and x, (0x22222222 << 1)), 1)
5677 // where the shift amount and mask may vary thus:
5678 //   [1]  = 0x22222222 / 0x44444444
5679 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
5680 //   [4]  = 0x00F000F0 / 0x0F000F00
5681 //   [8]  = 0x0000FF00 / 0x00FF0000
5682 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
5683 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
5684   // These are the unshifted masks which we use to match bit-manipulation
5685   // patterns. They may be shifted left in certain circumstances.
5686   static const uint64_t BitmanipMasks[] = {
5687       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
5688       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
5689 
5690   return matchRISCVBitmanipPat(Op, BitmanipMasks);
5691 }
5692 
5693 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
5694 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
5695                                const RISCVSubtarget &Subtarget) {
5696   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
5697   EVT VT = Op.getValueType();
5698 
5699   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
5700     return SDValue();
5701 
5702   SDValue Op0 = Op.getOperand(0);
5703   SDValue Op1 = Op.getOperand(1);
5704 
5705   // Or is commutable so canonicalize the second OR to the LHS.
5706   if (Op0.getOpcode() != ISD::OR)
5707     std::swap(Op0, Op1);
5708   if (Op0.getOpcode() != ISD::OR)
5709     return SDValue();
5710 
5711   // We found an inner OR, so our operands are the operands of the inner OR
5712   // and the other operand of the outer OR.
5713   SDValue A = Op0.getOperand(0);
5714   SDValue B = Op0.getOperand(1);
5715   SDValue C = Op1;
5716 
5717   auto Match1 = matchSHFLPat(A);
5718   auto Match2 = matchSHFLPat(B);
5719 
5720   // If neither matched, we failed.
5721   if (!Match1 && !Match2)
5722     return SDValue();
5723 
5724   // We had at least one match. if one failed, try the remaining C operand.
5725   if (!Match1) {
5726     std::swap(A, C);
5727     Match1 = matchSHFLPat(A);
5728     if (!Match1)
5729       return SDValue();
5730   } else if (!Match2) {
5731     std::swap(B, C);
5732     Match2 = matchSHFLPat(B);
5733     if (!Match2)
5734       return SDValue();
5735   }
5736   assert(Match1 && Match2);
5737 
5738   // Make sure our matches pair up.
5739   if (!Match1->formsPairWith(*Match2))
5740     return SDValue();
5741 
5742   // All the remains is to make sure C is an AND with the same input, that masks
5743   // out the bits that are being shuffled.
5744   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
5745       C.getOperand(0) != Match1->Op)
5746     return SDValue();
5747 
5748   uint64_t Mask = C.getConstantOperandVal(1);
5749 
5750   static const uint64_t BitmanipMasks[] = {
5751       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
5752       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
5753   };
5754 
5755   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
5756   unsigned MaskIdx = Log2_32(Match1->ShAmt);
5757   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
5758 
5759   if (Mask != ExpMask)
5760     return SDValue();
5761 
5762   SDLoc DL(Op);
5763   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
5764                      DAG.getConstant(Match1->ShAmt, DL, VT));
5765 }
5766 
5767 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
5768 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
5769 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
5770 // not undo itself, but they are redundant.
5771 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
5772   SDValue Src = N->getOperand(0);
5773 
5774   if (Src.getOpcode() != N->getOpcode())
5775     return SDValue();
5776 
5777   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
5778       !isa<ConstantSDNode>(Src.getOperand(1)))
5779     return SDValue();
5780 
5781   unsigned ShAmt1 = N->getConstantOperandVal(1);
5782   unsigned ShAmt2 = Src.getConstantOperandVal(1);
5783   Src = Src.getOperand(0);
5784 
5785   unsigned CombinedShAmt;
5786   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
5787     CombinedShAmt = ShAmt1 | ShAmt2;
5788   else
5789     CombinedShAmt = ShAmt1 ^ ShAmt2;
5790 
5791   if (CombinedShAmt == 0)
5792     return Src;
5793 
5794   SDLoc DL(N);
5795   return DAG.getNode(
5796       N->getOpcode(), DL, N->getValueType(0), Src,
5797       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
5798 }
5799 
5800 // Combine a constant select operand into its use:
5801 //
5802 // (and (select cond, -1, c), x)
5803 //   -> (select cond, x, (and x, c))  [AllOnes=1]
5804 // (or  (select cond, 0, c), x)
5805 //   -> (select cond, x, (or x, c))  [AllOnes=0]
5806 // (xor (select cond, 0, c), x)
5807 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
5808 // (add (select cond, 0, c), x)
5809 //   -> (select cond, x, (add x, c))  [AllOnes=0]
5810 // (sub x, (select cond, 0, c))
5811 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
5812 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
5813                                    SelectionDAG &DAG, bool AllOnes) {
5814   EVT VT = N->getValueType(0);
5815 
5816   // Skip vectors.
5817   if (VT.isVector())
5818     return SDValue();
5819 
5820   if ((Slct.getOpcode() != ISD::SELECT &&
5821        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
5822       !Slct.hasOneUse())
5823     return SDValue();
5824 
5825   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
5826     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
5827   };
5828 
5829   bool SwapSelectOps;
5830   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
5831   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
5832   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
5833   SDValue NonConstantVal;
5834   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
5835     SwapSelectOps = false;
5836     NonConstantVal = FalseVal;
5837   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
5838     SwapSelectOps = true;
5839     NonConstantVal = TrueVal;
5840   } else
5841     return SDValue();
5842 
5843   // Slct is now know to be the desired identity constant when CC is true.
5844   TrueVal = OtherOp;
5845   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
5846   // Unless SwapSelectOps says the condition should be false.
5847   if (SwapSelectOps)
5848     std::swap(TrueVal, FalseVal);
5849 
5850   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
5851     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
5852                        {Slct.getOperand(0), Slct.getOperand(1),
5853                         Slct.getOperand(2), TrueVal, FalseVal});
5854 
5855   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
5856                      {Slct.getOperand(0), TrueVal, FalseVal});
5857 }
5858 
5859 // Attempt combineSelectAndUse on each operand of a commutative operator N.
5860 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
5861                                               bool AllOnes) {
5862   SDValue N0 = N->getOperand(0);
5863   SDValue N1 = N->getOperand(1);
5864   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
5865     return Result;
5866   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
5867     return Result;
5868   return SDValue();
5869 }
5870 
5871 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG) {
5872   // fold (add (select lhs, rhs, cc, 0, y), x) ->
5873   //      (select lhs, rhs, cc, x, (add x, y))
5874   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
5875 }
5876 
5877 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
5878   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
5879   //      (select lhs, rhs, cc, x, (sub x, y))
5880   SDValue N0 = N->getOperand(0);
5881   SDValue N1 = N->getOperand(1);
5882   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
5883 }
5884 
5885 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
5886   // fold (and (select lhs, rhs, cc, -1, y), x) ->
5887   //      (select lhs, rhs, cc, x, (and x, y))
5888   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
5889 }
5890 
5891 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
5892                                 const RISCVSubtarget &Subtarget) {
5893   if (Subtarget.hasStdExtZbp()) {
5894     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
5895       return GREV;
5896     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
5897       return GORC;
5898     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
5899       return SHFL;
5900   }
5901 
5902   // fold (or (select cond, 0, y), x) ->
5903   //      (select cond, x, (or x, y))
5904   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
5905 }
5906 
5907 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
5908   // fold (xor (select cond, 0, y), x) ->
5909   //      (select cond, x, (xor x, y))
5910   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
5911 }
5912 
5913 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
5914 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
5915 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
5916 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
5917 // ADDW/SUBW/MULW.
5918 static SDValue performANY_EXTENDCombine(SDNode *N,
5919                                         TargetLowering::DAGCombinerInfo &DCI,
5920                                         const RISCVSubtarget &Subtarget) {
5921   if (!Subtarget.is64Bit())
5922     return SDValue();
5923 
5924   SelectionDAG &DAG = DCI.DAG;
5925 
5926   SDValue Src = N->getOperand(0);
5927   EVT VT = N->getValueType(0);
5928   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
5929     return SDValue();
5930 
5931   // The opcode must be one that can implicitly sign_extend.
5932   // FIXME: Additional opcodes.
5933   switch (Src.getOpcode()) {
5934   default:
5935     return SDValue();
5936   case ISD::MUL:
5937     if (!Subtarget.hasStdExtM())
5938       return SDValue();
5939     LLVM_FALLTHROUGH;
5940   case ISD::ADD:
5941   case ISD::SUB:
5942     break;
5943   }
5944 
5945   // Only handle cases where the result is used by a CopyToReg. That likely
5946   // means the value is a liveout of the basic block. This helps prevent
5947   // infinite combine loops like PR51206.
5948   if (none_of(N->uses(),
5949               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
5950     return SDValue();
5951 
5952   SmallVector<SDNode *, 4> SetCCs;
5953   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
5954                             UE = Src.getNode()->use_end();
5955        UI != UE; ++UI) {
5956     SDNode *User = *UI;
5957     if (User == N)
5958       continue;
5959     if (UI.getUse().getResNo() != Src.getResNo())
5960       continue;
5961     // All i32 setccs are legalized by sign extending operands.
5962     if (User->getOpcode() == ISD::SETCC) {
5963       SetCCs.push_back(User);
5964       continue;
5965     }
5966     // We don't know if we can extend this user.
5967     break;
5968   }
5969 
5970   // If we don't have any SetCCs, this isn't worthwhile.
5971   if (SetCCs.empty())
5972     return SDValue();
5973 
5974   SDLoc DL(N);
5975   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
5976   DCI.CombineTo(N, SExt);
5977 
5978   // Promote all the setccs.
5979   for (SDNode *SetCC : SetCCs) {
5980     SmallVector<SDValue, 4> Ops;
5981 
5982     for (unsigned j = 0; j != 2; ++j) {
5983       SDValue SOp = SetCC->getOperand(j);
5984       if (SOp == Src)
5985         Ops.push_back(SExt);
5986       else
5987         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
5988     }
5989 
5990     Ops.push_back(SetCC->getOperand(2));
5991     DCI.CombineTo(SetCC,
5992                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5993   }
5994   return SDValue(N, 0);
5995 }
5996 
5997 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
5998                                                DAGCombinerInfo &DCI) const {
5999   SelectionDAG &DAG = DCI.DAG;
6000 
6001   // Helper to call SimplifyDemandedBits on an operand of N where only some low
6002   // bits are demanded. N will be added to the Worklist if it was not deleted.
6003   // Caller should return SDValue(N, 0) if this returns true.
6004   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
6005     SDValue Op = N->getOperand(OpNo);
6006     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
6007     if (!SimplifyDemandedBits(Op, Mask, DCI))
6008       return false;
6009 
6010     if (N->getOpcode() != ISD::DELETED_NODE)
6011       DCI.AddToWorklist(N);
6012     return true;
6013   };
6014 
6015   switch (N->getOpcode()) {
6016   default:
6017     break;
6018   case RISCVISD::SplitF64: {
6019     SDValue Op0 = N->getOperand(0);
6020     // If the input to SplitF64 is just BuildPairF64 then the operation is
6021     // redundant. Instead, use BuildPairF64's operands directly.
6022     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
6023       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
6024 
6025     SDLoc DL(N);
6026 
6027     // It's cheaper to materialise two 32-bit integers than to load a double
6028     // from the constant pool and transfer it to integer registers through the
6029     // stack.
6030     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
6031       APInt V = C->getValueAPF().bitcastToAPInt();
6032       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
6033       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
6034       return DCI.CombineTo(N, Lo, Hi);
6035     }
6036 
6037     // This is a target-specific version of a DAGCombine performed in
6038     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6039     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6040     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6041     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6042         !Op0.getNode()->hasOneUse())
6043       break;
6044     SDValue NewSplitF64 =
6045         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
6046                     Op0.getOperand(0));
6047     SDValue Lo = NewSplitF64.getValue(0);
6048     SDValue Hi = NewSplitF64.getValue(1);
6049     APInt SignBit = APInt::getSignMask(32);
6050     if (Op0.getOpcode() == ISD::FNEG) {
6051       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
6052                                   DAG.getConstant(SignBit, DL, MVT::i32));
6053       return DCI.CombineTo(N, Lo, NewHi);
6054     }
6055     assert(Op0.getOpcode() == ISD::FABS);
6056     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
6057                                 DAG.getConstant(~SignBit, DL, MVT::i32));
6058     return DCI.CombineTo(N, Lo, NewHi);
6059   }
6060   case RISCVISD::SLLW:
6061   case RISCVISD::SRAW:
6062   case RISCVISD::SRLW:
6063   case RISCVISD::ROLW:
6064   case RISCVISD::RORW: {
6065     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6066     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6067         SimplifyDemandedLowBitsHelper(1, 5))
6068       return SDValue(N, 0);
6069     break;
6070   }
6071   case RISCVISD::CLZW:
6072   case RISCVISD::CTZW: {
6073     // Only the lower 32 bits of the first operand are read
6074     if (SimplifyDemandedLowBitsHelper(0, 32))
6075       return SDValue(N, 0);
6076     break;
6077   }
6078   case RISCVISD::FSL:
6079   case RISCVISD::FSR: {
6080     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
6081     unsigned BitWidth = N->getOperand(2).getValueSizeInBits();
6082     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6083     if (SimplifyDemandedLowBitsHelper(2, Log2_32(BitWidth) + 1))
6084       return SDValue(N, 0);
6085     break;
6086   }
6087   case RISCVISD::FSLW:
6088   case RISCVISD::FSRW: {
6089     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
6090     // read.
6091     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6092         SimplifyDemandedLowBitsHelper(1, 32) ||
6093         SimplifyDemandedLowBitsHelper(2, 6))
6094       return SDValue(N, 0);
6095     break;
6096   }
6097   case RISCVISD::GREV:
6098   case RISCVISD::GORC: {
6099     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
6100     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6101     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6102     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
6103       return SDValue(N, 0);
6104 
6105     return combineGREVI_GORCI(N, DCI.DAG);
6106   }
6107   case RISCVISD::GREVW:
6108   case RISCVISD::GORCW: {
6109     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6110     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6111         SimplifyDemandedLowBitsHelper(1, 5))
6112       return SDValue(N, 0);
6113 
6114     return combineGREVI_GORCI(N, DCI.DAG);
6115   }
6116   case RISCVISD::SHFL:
6117   case RISCVISD::UNSHFL: {
6118     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
6119     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
6120     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6121     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
6122       return SDValue(N, 0);
6123 
6124     break;
6125   }
6126   case RISCVISD::SHFLW:
6127   case RISCVISD::UNSHFLW: {
6128     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
6129     SDValue LHS = N->getOperand(0);
6130     SDValue RHS = N->getOperand(1);
6131     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
6132     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
6133     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6134         SimplifyDemandedLowBitsHelper(1, 4))
6135       return SDValue(N, 0);
6136 
6137     break;
6138   }
6139   case RISCVISD::BCOMPRESSW:
6140   case RISCVISD::BDECOMPRESSW: {
6141     // Only the lower 32 bits of LHS and RHS are read.
6142     if (SimplifyDemandedLowBitsHelper(0, 32) ||
6143         SimplifyDemandedLowBitsHelper(1, 32))
6144       return SDValue(N, 0);
6145 
6146     break;
6147   }
6148   case RISCVISD::FMV_X_ANYEXTH:
6149   case RISCVISD::FMV_X_ANYEXTW_RV64: {
6150     SDLoc DL(N);
6151     SDValue Op0 = N->getOperand(0);
6152     MVT VT = N->getSimpleValueType(0);
6153     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
6154     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
6155     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
6156     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
6157          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
6158         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
6159          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
6160       assert(Op0.getOperand(0).getValueType() == VT &&
6161              "Unexpected value type!");
6162       return Op0.getOperand(0);
6163     }
6164 
6165     // This is a target-specific version of a DAGCombine performed in
6166     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6167     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6168     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6169     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6170         !Op0.getNode()->hasOneUse())
6171       break;
6172     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
6173     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
6174     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
6175     if (Op0.getOpcode() == ISD::FNEG)
6176       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
6177                          DAG.getConstant(SignBit, DL, VT));
6178 
6179     assert(Op0.getOpcode() == ISD::FABS);
6180     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
6181                        DAG.getConstant(~SignBit, DL, VT));
6182   }
6183   case ISD::ADD:
6184     return performADDCombine(N, DAG);
6185   case ISD::SUB:
6186     return performSUBCombine(N, DAG);
6187   case ISD::AND:
6188     return performANDCombine(N, DAG);
6189   case ISD::OR:
6190     return performORCombine(N, DAG, Subtarget);
6191   case ISD::XOR:
6192     return performXORCombine(N, DAG);
6193   case ISD::ANY_EXTEND:
6194     return performANY_EXTENDCombine(N, DCI, Subtarget);
6195   case ISD::ZERO_EXTEND:
6196     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
6197     // type legalization. This is safe because fp_to_uint produces poison if
6198     // it overflows.
6199     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() &&
6200         N->getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
6201         isTypeLegal(N->getOperand(0).getOperand(0).getValueType()))
6202       return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
6203                          N->getOperand(0).getOperand(0));
6204     return SDValue();
6205   case RISCVISD::SELECT_CC: {
6206     // Transform
6207     SDValue LHS = N->getOperand(0);
6208     SDValue RHS = N->getOperand(1);
6209     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
6210     if (!ISD::isIntEqualitySetCC(CCVal))
6211       break;
6212 
6213     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
6214     //      (select_cc X, Y, lt, trueV, falseV)
6215     // Sometimes the setcc is introduced after select_cc has been formed.
6216     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6217         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6218       // If we're looking for eq 0 instead of ne 0, we need to invert the
6219       // condition.
6220       bool Invert = CCVal == ISD::SETEQ;
6221       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6222       if (Invert)
6223         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6224 
6225       SDLoc DL(N);
6226       RHS = LHS.getOperand(1);
6227       LHS = LHS.getOperand(0);
6228       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
6229 
6230       SDValue TargetCC = DAG.getCondCode(CCVal);
6231       return DAG.getNode(
6232           RISCVISD::SELECT_CC, DL, N->getValueType(0),
6233           {LHS, RHS, TargetCC, N->getOperand(3), N->getOperand(4)});
6234     }
6235 
6236     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
6237     //      (select_cc X, Y, eq/ne, trueV, falseV)
6238     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
6239       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
6240                          {LHS.getOperand(0), LHS.getOperand(1),
6241                           N->getOperand(2), N->getOperand(3),
6242                           N->getOperand(4)});
6243     // (select_cc X, 1, setne, trueV, falseV) ->
6244     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
6245     // This can occur when legalizing some floating point comparisons.
6246     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
6247     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
6248       SDLoc DL(N);
6249       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6250       SDValue TargetCC = DAG.getCondCode(CCVal);
6251       RHS = DAG.getConstant(0, DL, LHS.getValueType());
6252       return DAG.getNode(
6253           RISCVISD::SELECT_CC, DL, N->getValueType(0),
6254           {LHS, RHS, TargetCC, N->getOperand(3), N->getOperand(4)});
6255     }
6256 
6257     break;
6258   }
6259   case RISCVISD::BR_CC: {
6260     SDValue LHS = N->getOperand(1);
6261     SDValue RHS = N->getOperand(2);
6262     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
6263     if (!ISD::isIntEqualitySetCC(CCVal))
6264       break;
6265 
6266     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
6267     //      (br_cc X, Y, lt, dest)
6268     // Sometimes the setcc is introduced after br_cc has been formed.
6269     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6270         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6271       // If we're looking for eq 0 instead of ne 0, we need to invert the
6272       // condition.
6273       bool Invert = CCVal == ISD::SETEQ;
6274       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6275       if (Invert)
6276         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6277 
6278       SDLoc DL(N);
6279       RHS = LHS.getOperand(1);
6280       LHS = LHS.getOperand(0);
6281       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
6282 
6283       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
6284                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
6285                          N->getOperand(4));
6286     }
6287 
6288     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
6289     //      (br_cc X, Y, eq/ne, trueV, falseV)
6290     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
6291       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
6292                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
6293                          N->getOperand(3), N->getOperand(4));
6294 
6295     // (br_cc X, 1, setne, br_cc) ->
6296     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
6297     // This can occur when legalizing some floating point comparisons.
6298     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
6299     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
6300       SDLoc DL(N);
6301       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6302       SDValue TargetCC = DAG.getCondCode(CCVal);
6303       RHS = DAG.getConstant(0, DL, LHS.getValueType());
6304       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
6305                          N->getOperand(0), LHS, RHS, TargetCC,
6306                          N->getOperand(4));
6307     }
6308     break;
6309   }
6310   case ISD::FCOPYSIGN: {
6311     EVT VT = N->getValueType(0);
6312     if (!VT.isVector())
6313       break;
6314     // There is a form of VFSGNJ which injects the negated sign of its second
6315     // operand. Try and bubble any FNEG up after the extend/round to produce
6316     // this optimized pattern. Avoid modifying cases where FP_ROUND and
6317     // TRUNC=1.
6318     SDValue In2 = N->getOperand(1);
6319     // Avoid cases where the extend/round has multiple uses, as duplicating
6320     // those is typically more expensive than removing a fneg.
6321     if (!In2.hasOneUse())
6322       break;
6323     if (In2.getOpcode() != ISD::FP_EXTEND &&
6324         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
6325       break;
6326     In2 = In2.getOperand(0);
6327     if (In2.getOpcode() != ISD::FNEG)
6328       break;
6329     SDLoc DL(N);
6330     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
6331     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
6332                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
6333   }
6334   case ISD::MGATHER:
6335   case ISD::MSCATTER: {
6336     if (!DCI.isBeforeLegalize())
6337       break;
6338     MaskedGatherScatterSDNode *MGSN = cast<MaskedGatherScatterSDNode>(N);
6339     SDValue Index = MGSN->getIndex();
6340     EVT IndexVT = Index.getValueType();
6341     MVT XLenVT = Subtarget.getXLenVT();
6342     // RISCV indexed loads only support the "unsigned unscaled" addressing
6343     // mode, so anything else must be manually legalized.
6344     bool NeedsIdxLegalization = MGSN->isIndexScaled() ||
6345                                 (MGSN->isIndexSigned() &&
6346                                  IndexVT.getVectorElementType().bitsLT(XLenVT));
6347     if (!NeedsIdxLegalization)
6348       break;
6349 
6350     SDLoc DL(N);
6351 
6352     // Any index legalization should first promote to XLenVT, so we don't lose
6353     // bits when scaling. This may create an illegal index type so we let
6354     // LLVM's legalization take care of the splitting.
6355     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
6356       IndexVT = IndexVT.changeVectorElementType(XLenVT);
6357       Index = DAG.getNode(MGSN->isIndexSigned() ? ISD::SIGN_EXTEND
6358                                                 : ISD::ZERO_EXTEND,
6359                           DL, IndexVT, Index);
6360     }
6361 
6362     unsigned Scale = N->getConstantOperandVal(5);
6363     if (MGSN->isIndexScaled() && Scale != 1) {
6364       // Manually scale the indices by the element size.
6365       // TODO: Sanitize the scale operand here?
6366       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
6367       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
6368       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
6369     }
6370 
6371     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
6372     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) {
6373       return DAG.getMaskedGather(
6374           N->getVTList(), MGSN->getMemoryVT(), DL,
6375           {MGSN->getChain(), MGN->getPassThru(), MGSN->getMask(),
6376            MGSN->getBasePtr(), Index, MGN->getScale()},
6377           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
6378     }
6379     const auto *MSN = cast<MaskedScatterSDNode>(N);
6380     return DAG.getMaskedScatter(
6381         N->getVTList(), MGSN->getMemoryVT(), DL,
6382         {MGSN->getChain(), MSN->getValue(), MGSN->getMask(), MGSN->getBasePtr(),
6383          Index, MGSN->getScale()},
6384         MGSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
6385   }
6386   case RISCVISD::SRA_VL:
6387   case RISCVISD::SRL_VL:
6388   case RISCVISD::SHL_VL: {
6389     SDValue ShAmt = N->getOperand(1);
6390     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
6391       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
6392       SDLoc DL(N);
6393       SDValue VL = N->getOperand(3);
6394       EVT VT = N->getValueType(0);
6395       ShAmt =
6396           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
6397       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
6398                          N->getOperand(2), N->getOperand(3));
6399     }
6400     break;
6401   }
6402   case ISD::SRA:
6403   case ISD::SRL:
6404   case ISD::SHL: {
6405     SDValue ShAmt = N->getOperand(1);
6406     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
6407       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
6408       SDLoc DL(N);
6409       EVT VT = N->getValueType(0);
6410       ShAmt =
6411           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
6412       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
6413     }
6414     break;
6415   }
6416   case RISCVISD::MUL_VL: {
6417     // Try to form VWMUL or VWMULU.
6418     // FIXME: Look for splat of extended scalar as well.
6419     // FIXME: Support VWMULSU.
6420     SDValue Op0 = N->getOperand(0);
6421     SDValue Op1 = N->getOperand(1);
6422     bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
6423     bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
6424     if ((!IsSignExt && !IsZeroExt) || Op0.getOpcode() != Op1.getOpcode())
6425       return SDValue();
6426 
6427     // Make sure the extends have a single use.
6428     if (!Op0.hasOneUse() || !Op1.hasOneUse())
6429       return SDValue();
6430 
6431     SDValue Mask = N->getOperand(2);
6432     SDValue VL = N->getOperand(3);
6433     if (Op0.getOperand(1) != Mask || Op1.getOperand(1) != Mask ||
6434         Op0.getOperand(2) != VL || Op1.getOperand(2) != VL)
6435       return SDValue();
6436 
6437     Op0 = Op0.getOperand(0);
6438     Op1 = Op1.getOperand(0);
6439 
6440     MVT VT = N->getSimpleValueType(0);
6441     MVT NarrowVT =
6442         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() / 2),
6443                          VT.getVectorElementCount());
6444 
6445     SDLoc DL(N);
6446 
6447     // Re-introduce narrower extends if needed.
6448     unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
6449     if (Op0.getValueType() != NarrowVT)
6450       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
6451     if (Op1.getValueType() != NarrowVT)
6452       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
6453 
6454     unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
6455     return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
6456   }
6457   }
6458 
6459   return SDValue();
6460 }
6461 
6462 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
6463     const SDNode *N, CombineLevel Level) const {
6464   // The following folds are only desirable if `(OP _, c1 << c2)` can be
6465   // materialised in fewer instructions than `(OP _, c1)`:
6466   //
6467   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
6468   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
6469   SDValue N0 = N->getOperand(0);
6470   EVT Ty = N0.getValueType();
6471   if (Ty.isScalarInteger() &&
6472       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
6473     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6474     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
6475     if (C1 && C2) {
6476       const APInt &C1Int = C1->getAPIntValue();
6477       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
6478 
6479       // We can materialise `c1 << c2` into an add immediate, so it's "free",
6480       // and the combine should happen, to potentially allow further combines
6481       // later.
6482       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
6483           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
6484         return true;
6485 
6486       // We can materialise `c1` in an add immediate, so it's "free", and the
6487       // combine should be prevented.
6488       if (C1Int.getMinSignedBits() <= 64 &&
6489           isLegalAddImmediate(C1Int.getSExtValue()))
6490         return false;
6491 
6492       // Neither constant will fit into an immediate, so find materialisation
6493       // costs.
6494       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
6495                                               Subtarget.getFeatureBits(),
6496                                               /*CompressionCost*/true);
6497       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
6498           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
6499           /*CompressionCost*/true);
6500 
6501       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
6502       // combine should be prevented.
6503       if (C1Cost < ShiftedC1Cost)
6504         return false;
6505     }
6506   }
6507   return true;
6508 }
6509 
6510 bool RISCVTargetLowering::targetShrinkDemandedConstant(
6511     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
6512     TargetLoweringOpt &TLO) const {
6513   // Delay this optimization as late as possible.
6514   if (!TLO.LegalOps)
6515     return false;
6516 
6517   EVT VT = Op.getValueType();
6518   if (VT.isVector())
6519     return false;
6520 
6521   // Only handle AND for now.
6522   if (Op.getOpcode() != ISD::AND)
6523     return false;
6524 
6525   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6526   if (!C)
6527     return false;
6528 
6529   const APInt &Mask = C->getAPIntValue();
6530 
6531   // Clear all non-demanded bits initially.
6532   APInt ShrunkMask = Mask & DemandedBits;
6533 
6534   // Try to make a smaller immediate by setting undemanded bits.
6535 
6536   APInt ExpandedMask = Mask | ~DemandedBits;
6537 
6538   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
6539     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
6540   };
6541   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
6542     if (NewMask == Mask)
6543       return true;
6544     SDLoc DL(Op);
6545     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
6546     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
6547     return TLO.CombineTo(Op, NewOp);
6548   };
6549 
6550   // If the shrunk mask fits in sign extended 12 bits, let the target
6551   // independent code apply it.
6552   if (ShrunkMask.isSignedIntN(12))
6553     return false;
6554 
6555   // Preserve (and X, 0xffff) when zext.h is supported.
6556   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
6557     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
6558     if (IsLegalMask(NewMask))
6559       return UseMask(NewMask);
6560   }
6561 
6562   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
6563   if (VT == MVT::i64) {
6564     APInt NewMask = APInt(64, 0xffffffff);
6565     if (IsLegalMask(NewMask))
6566       return UseMask(NewMask);
6567   }
6568 
6569   // For the remaining optimizations, we need to be able to make a negative
6570   // number through a combination of mask and undemanded bits.
6571   if (!ExpandedMask.isNegative())
6572     return false;
6573 
6574   // What is the fewest number of bits we need to represent the negative number.
6575   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
6576 
6577   // Try to make a 12 bit negative immediate. If that fails try to make a 32
6578   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
6579   APInt NewMask = ShrunkMask;
6580   if (MinSignedBits <= 12)
6581     NewMask.setBitsFrom(11);
6582   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
6583     NewMask.setBitsFrom(31);
6584   else
6585     return false;
6586 
6587   // Sanity check that our new mask is a subset of the demanded mask.
6588   assert(IsLegalMask(NewMask));
6589   return UseMask(NewMask);
6590 }
6591 
6592 static void computeGREV(APInt &Src, unsigned ShAmt) {
6593   ShAmt &= Src.getBitWidth() - 1;
6594   uint64_t x = Src.getZExtValue();
6595   if (ShAmt & 1)
6596     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
6597   if (ShAmt & 2)
6598     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
6599   if (ShAmt & 4)
6600     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
6601   if (ShAmt & 8)
6602     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
6603   if (ShAmt & 16)
6604     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
6605   if (ShAmt & 32)
6606     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
6607   Src = x;
6608 }
6609 
6610 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
6611                                                         KnownBits &Known,
6612                                                         const APInt &DemandedElts,
6613                                                         const SelectionDAG &DAG,
6614                                                         unsigned Depth) const {
6615   unsigned BitWidth = Known.getBitWidth();
6616   unsigned Opc = Op.getOpcode();
6617   assert((Opc >= ISD::BUILTIN_OP_END ||
6618           Opc == ISD::INTRINSIC_WO_CHAIN ||
6619           Opc == ISD::INTRINSIC_W_CHAIN ||
6620           Opc == ISD::INTRINSIC_VOID) &&
6621          "Should use MaskedValueIsZero if you don't know whether Op"
6622          " is a target node!");
6623 
6624   Known.resetAll();
6625   switch (Opc) {
6626   default: break;
6627   case RISCVISD::SELECT_CC: {
6628     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
6629     // If we don't know any bits, early out.
6630     if (Known.isUnknown())
6631       break;
6632     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
6633 
6634     // Only known if known in both the LHS and RHS.
6635     Known = KnownBits::commonBits(Known, Known2);
6636     break;
6637   }
6638   case RISCVISD::REMUW: {
6639     KnownBits Known2;
6640     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6641     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6642     // We only care about the lower 32 bits.
6643     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
6644     // Restore the original width by sign extending.
6645     Known = Known.sext(BitWidth);
6646     break;
6647   }
6648   case RISCVISD::DIVUW: {
6649     KnownBits Known2;
6650     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6651     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6652     // We only care about the lower 32 bits.
6653     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
6654     // Restore the original width by sign extending.
6655     Known = Known.sext(BitWidth);
6656     break;
6657   }
6658   case RISCVISD::CTZW: {
6659     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
6660     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
6661     unsigned LowBits = Log2_32(PossibleTZ) + 1;
6662     Known.Zero.setBitsFrom(LowBits);
6663     break;
6664   }
6665   case RISCVISD::CLZW: {
6666     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
6667     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
6668     unsigned LowBits = Log2_32(PossibleLZ) + 1;
6669     Known.Zero.setBitsFrom(LowBits);
6670     break;
6671   }
6672   case RISCVISD::GREV:
6673   case RISCVISD::GREVW: {
6674     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
6675       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
6676       if (Opc == RISCVISD::GREVW)
6677         Known = Known.trunc(32);
6678       unsigned ShAmt = C->getZExtValue();
6679       computeGREV(Known.Zero, ShAmt);
6680       computeGREV(Known.One, ShAmt);
6681       if (Opc == RISCVISD::GREVW)
6682         Known = Known.sext(BitWidth);
6683     }
6684     break;
6685   }
6686   case RISCVISD::READ_VLENB:
6687     // We assume VLENB is at least 16 bytes.
6688     Known.Zero.setLowBits(4);
6689     // We assume VLENB is no more than 65536 / 8 bytes.
6690     Known.Zero.setBitsFrom(14);
6691     break;
6692   case ISD::INTRINSIC_W_CHAIN: {
6693     unsigned IntNo = Op.getConstantOperandVal(1);
6694     switch (IntNo) {
6695     default:
6696       // We can't do anything for most intrinsics.
6697       break;
6698     case Intrinsic::riscv_vsetvli:
6699     case Intrinsic::riscv_vsetvlimax:
6700       // Assume that VL output is positive and would fit in an int32_t.
6701       // TODO: VLEN might be capped at 16 bits in a future V spec update.
6702       if (BitWidth >= 32)
6703         Known.Zero.setBitsFrom(31);
6704       break;
6705     }
6706     break;
6707   }
6708   }
6709 }
6710 
6711 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
6712     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
6713     unsigned Depth) const {
6714   switch (Op.getOpcode()) {
6715   default:
6716     break;
6717   case RISCVISD::SELECT_CC: {
6718     unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
6719     if (Tmp == 1) return 1;  // Early out.
6720     unsigned Tmp2 = DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
6721     return std::min(Tmp, Tmp2);
6722   }
6723   case RISCVISD::SLLW:
6724   case RISCVISD::SRAW:
6725   case RISCVISD::SRLW:
6726   case RISCVISD::DIVW:
6727   case RISCVISD::DIVUW:
6728   case RISCVISD::REMUW:
6729   case RISCVISD::ROLW:
6730   case RISCVISD::RORW:
6731   case RISCVISD::GREVW:
6732   case RISCVISD::GORCW:
6733   case RISCVISD::FSLW:
6734   case RISCVISD::FSRW:
6735   case RISCVISD::SHFLW:
6736   case RISCVISD::UNSHFLW:
6737   case RISCVISD::BCOMPRESSW:
6738   case RISCVISD::BDECOMPRESSW:
6739   case RISCVISD::FCVT_W_RTZ_RV64:
6740   case RISCVISD::FCVT_WU_RTZ_RV64:
6741     // TODO: As the result is sign-extended, this is conservatively correct. A
6742     // more precise answer could be calculated for SRAW depending on known
6743     // bits in the shift amount.
6744     return 33;
6745   case RISCVISD::SHFL:
6746   case RISCVISD::UNSHFL: {
6747     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
6748     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
6749     // will stay within the upper 32 bits. If there were more than 32 sign bits
6750     // before there will be at least 33 sign bits after.
6751     if (Op.getValueType() == MVT::i64 &&
6752         isa<ConstantSDNode>(Op.getOperand(1)) &&
6753         (Op.getConstantOperandVal(1) & 0x10) == 0) {
6754       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
6755       if (Tmp > 32)
6756         return 33;
6757     }
6758     break;
6759   }
6760   case RISCVISD::VMV_X_S:
6761     // The number of sign bits of the scalar result is computed by obtaining the
6762     // element type of the input vector operand, subtracting its width from the
6763     // XLEN, and then adding one (sign bit within the element type). If the
6764     // element type is wider than XLen, the least-significant XLEN bits are
6765     // taken.
6766     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
6767       return 1;
6768     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
6769   }
6770 
6771   return 1;
6772 }
6773 
6774 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
6775                                                   MachineBasicBlock *BB) {
6776   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
6777 
6778   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
6779   // Should the count have wrapped while it was being read, we need to try
6780   // again.
6781   // ...
6782   // read:
6783   // rdcycleh x3 # load high word of cycle
6784   // rdcycle  x2 # load low word of cycle
6785   // rdcycleh x4 # load high word of cycle
6786   // bne x3, x4, read # check if high word reads match, otherwise try again
6787   // ...
6788 
6789   MachineFunction &MF = *BB->getParent();
6790   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6791   MachineFunction::iterator It = ++BB->getIterator();
6792 
6793   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
6794   MF.insert(It, LoopMBB);
6795 
6796   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
6797   MF.insert(It, DoneMBB);
6798 
6799   // Transfer the remainder of BB and its successor edges to DoneMBB.
6800   DoneMBB->splice(DoneMBB->begin(), BB,
6801                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6802   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
6803 
6804   BB->addSuccessor(LoopMBB);
6805 
6806   MachineRegisterInfo &RegInfo = MF.getRegInfo();
6807   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
6808   Register LoReg = MI.getOperand(0).getReg();
6809   Register HiReg = MI.getOperand(1).getReg();
6810   DebugLoc DL = MI.getDebugLoc();
6811 
6812   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
6813   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
6814       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
6815       .addReg(RISCV::X0);
6816   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
6817       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
6818       .addReg(RISCV::X0);
6819   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
6820       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
6821       .addReg(RISCV::X0);
6822 
6823   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
6824       .addReg(HiReg)
6825       .addReg(ReadAgainReg)
6826       .addMBB(LoopMBB);
6827 
6828   LoopMBB->addSuccessor(LoopMBB);
6829   LoopMBB->addSuccessor(DoneMBB);
6830 
6831   MI.eraseFromParent();
6832 
6833   return DoneMBB;
6834 }
6835 
6836 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
6837                                              MachineBasicBlock *BB) {
6838   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
6839 
6840   MachineFunction &MF = *BB->getParent();
6841   DebugLoc DL = MI.getDebugLoc();
6842   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
6843   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
6844   Register LoReg = MI.getOperand(0).getReg();
6845   Register HiReg = MI.getOperand(1).getReg();
6846   Register SrcReg = MI.getOperand(2).getReg();
6847   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
6848   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
6849 
6850   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
6851                           RI);
6852   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
6853   MachineMemOperand *MMOLo =
6854       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
6855   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
6856       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
6857   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
6858       .addFrameIndex(FI)
6859       .addImm(0)
6860       .addMemOperand(MMOLo);
6861   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
6862       .addFrameIndex(FI)
6863       .addImm(4)
6864       .addMemOperand(MMOHi);
6865   MI.eraseFromParent(); // The pseudo instruction is gone now.
6866   return BB;
6867 }
6868 
6869 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
6870                                                  MachineBasicBlock *BB) {
6871   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
6872          "Unexpected instruction");
6873 
6874   MachineFunction &MF = *BB->getParent();
6875   DebugLoc DL = MI.getDebugLoc();
6876   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
6877   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
6878   Register DstReg = MI.getOperand(0).getReg();
6879   Register LoReg = MI.getOperand(1).getReg();
6880   Register HiReg = MI.getOperand(2).getReg();
6881   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
6882   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
6883 
6884   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
6885   MachineMemOperand *MMOLo =
6886       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
6887   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
6888       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
6889   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
6890       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
6891       .addFrameIndex(FI)
6892       .addImm(0)
6893       .addMemOperand(MMOLo);
6894   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
6895       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
6896       .addFrameIndex(FI)
6897       .addImm(4)
6898       .addMemOperand(MMOHi);
6899   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
6900   MI.eraseFromParent(); // The pseudo instruction is gone now.
6901   return BB;
6902 }
6903 
6904 static bool isSelectPseudo(MachineInstr &MI) {
6905   switch (MI.getOpcode()) {
6906   default:
6907     return false;
6908   case RISCV::Select_GPR_Using_CC_GPR:
6909   case RISCV::Select_FPR16_Using_CC_GPR:
6910   case RISCV::Select_FPR32_Using_CC_GPR:
6911   case RISCV::Select_FPR64_Using_CC_GPR:
6912     return true;
6913   }
6914 }
6915 
6916 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
6917                                            MachineBasicBlock *BB,
6918                                            const RISCVSubtarget &Subtarget) {
6919   // To "insert" Select_* instructions, we actually have to insert the triangle
6920   // control-flow pattern.  The incoming instructions know the destination vreg
6921   // to set, the condition code register to branch on, the true/false values to
6922   // select between, and the condcode to use to select the appropriate branch.
6923   //
6924   // We produce the following control flow:
6925   //     HeadMBB
6926   //     |  \
6927   //     |  IfFalseMBB
6928   //     | /
6929   //    TailMBB
6930   //
6931   // When we find a sequence of selects we attempt to optimize their emission
6932   // by sharing the control flow. Currently we only handle cases where we have
6933   // multiple selects with the exact same condition (same LHS, RHS and CC).
6934   // The selects may be interleaved with other instructions if the other
6935   // instructions meet some requirements we deem safe:
6936   // - They are debug instructions. Otherwise,
6937   // - They do not have side-effects, do not access memory and their inputs do
6938   //   not depend on the results of the select pseudo-instructions.
6939   // The TrueV/FalseV operands of the selects cannot depend on the result of
6940   // previous selects in the sequence.
6941   // These conditions could be further relaxed. See the X86 target for a
6942   // related approach and more information.
6943   Register LHS = MI.getOperand(1).getReg();
6944   Register RHS = MI.getOperand(2).getReg();
6945   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
6946 
6947   SmallVector<MachineInstr *, 4> SelectDebugValues;
6948   SmallSet<Register, 4> SelectDests;
6949   SelectDests.insert(MI.getOperand(0).getReg());
6950 
6951   MachineInstr *LastSelectPseudo = &MI;
6952 
6953   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
6954        SequenceMBBI != E; ++SequenceMBBI) {
6955     if (SequenceMBBI->isDebugInstr())
6956       continue;
6957     else if (isSelectPseudo(*SequenceMBBI)) {
6958       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
6959           SequenceMBBI->getOperand(2).getReg() != RHS ||
6960           SequenceMBBI->getOperand(3).getImm() != CC ||
6961           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
6962           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
6963         break;
6964       LastSelectPseudo = &*SequenceMBBI;
6965       SequenceMBBI->collectDebugValues(SelectDebugValues);
6966       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
6967     } else {
6968       if (SequenceMBBI->hasUnmodeledSideEffects() ||
6969           SequenceMBBI->mayLoadOrStore())
6970         break;
6971       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
6972             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
6973           }))
6974         break;
6975     }
6976   }
6977 
6978   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
6979   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6980   DebugLoc DL = MI.getDebugLoc();
6981   MachineFunction::iterator I = ++BB->getIterator();
6982 
6983   MachineBasicBlock *HeadMBB = BB;
6984   MachineFunction *F = BB->getParent();
6985   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
6986   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
6987 
6988   F->insert(I, IfFalseMBB);
6989   F->insert(I, TailMBB);
6990 
6991   // Transfer debug instructions associated with the selects to TailMBB.
6992   for (MachineInstr *DebugInstr : SelectDebugValues) {
6993     TailMBB->push_back(DebugInstr->removeFromParent());
6994   }
6995 
6996   // Move all instructions after the sequence to TailMBB.
6997   TailMBB->splice(TailMBB->end(), HeadMBB,
6998                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
6999   // Update machine-CFG edges by transferring all successors of the current
7000   // block to the new block which will contain the Phi nodes for the selects.
7001   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
7002   // Set the successors for HeadMBB.
7003   HeadMBB->addSuccessor(IfFalseMBB);
7004   HeadMBB->addSuccessor(TailMBB);
7005 
7006   // Insert appropriate branch.
7007   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
7008     .addReg(LHS)
7009     .addReg(RHS)
7010     .addMBB(TailMBB);
7011 
7012   // IfFalseMBB just falls through to TailMBB.
7013   IfFalseMBB->addSuccessor(TailMBB);
7014 
7015   // Create PHIs for all of the select pseudo-instructions.
7016   auto SelectMBBI = MI.getIterator();
7017   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
7018   auto InsertionPoint = TailMBB->begin();
7019   while (SelectMBBI != SelectEnd) {
7020     auto Next = std::next(SelectMBBI);
7021     if (isSelectPseudo(*SelectMBBI)) {
7022       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
7023       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
7024               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
7025           .addReg(SelectMBBI->getOperand(4).getReg())
7026           .addMBB(HeadMBB)
7027           .addReg(SelectMBBI->getOperand(5).getReg())
7028           .addMBB(IfFalseMBB);
7029       SelectMBBI->eraseFromParent();
7030     }
7031     SelectMBBI = Next;
7032   }
7033 
7034   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
7035   return TailMBB;
7036 }
7037 
7038 MachineBasicBlock *
7039 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
7040                                                  MachineBasicBlock *BB) const {
7041   switch (MI.getOpcode()) {
7042   default:
7043     llvm_unreachable("Unexpected instr type to insert");
7044   case RISCV::ReadCycleWide:
7045     assert(!Subtarget.is64Bit() &&
7046            "ReadCycleWrite is only to be used on riscv32");
7047     return emitReadCycleWidePseudo(MI, BB);
7048   case RISCV::Select_GPR_Using_CC_GPR:
7049   case RISCV::Select_FPR16_Using_CC_GPR:
7050   case RISCV::Select_FPR32_Using_CC_GPR:
7051   case RISCV::Select_FPR64_Using_CC_GPR:
7052     return emitSelectPseudo(MI, BB, Subtarget);
7053   case RISCV::BuildPairF64Pseudo:
7054     return emitBuildPairF64Pseudo(MI, BB);
7055   case RISCV::SplitF64Pseudo:
7056     return emitSplitF64Pseudo(MI, BB);
7057   }
7058 }
7059 
7060 // Calling Convention Implementation.
7061 // The expectations for frontend ABI lowering vary from target to target.
7062 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
7063 // details, but this is a longer term goal. For now, we simply try to keep the
7064 // role of the frontend as simple and well-defined as possible. The rules can
7065 // be summarised as:
7066 // * Never split up large scalar arguments. We handle them here.
7067 // * If a hardfloat calling convention is being used, and the struct may be
7068 // passed in a pair of registers (fp+fp, int+fp), and both registers are
7069 // available, then pass as two separate arguments. If either the GPRs or FPRs
7070 // are exhausted, then pass according to the rule below.
7071 // * If a struct could never be passed in registers or directly in a stack
7072 // slot (as it is larger than 2*XLEN and the floating point rules don't
7073 // apply), then pass it using a pointer with the byval attribute.
7074 // * If a struct is less than 2*XLEN, then coerce to either a two-element
7075 // word-sized array or a 2*XLEN scalar (depending on alignment).
7076 // * The frontend can determine whether a struct is returned by reference or
7077 // not based on its size and fields. If it will be returned by reference, the
7078 // frontend must modify the prototype so a pointer with the sret annotation is
7079 // passed as the first argument. This is not necessary for large scalar
7080 // returns.
7081 // * Struct return values and varargs should be coerced to structs containing
7082 // register-size fields in the same situations they would be for fixed
7083 // arguments.
7084 
7085 static const MCPhysReg ArgGPRs[] = {
7086   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
7087   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
7088 };
7089 static const MCPhysReg ArgFPR16s[] = {
7090   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
7091   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
7092 };
7093 static const MCPhysReg ArgFPR32s[] = {
7094   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
7095   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
7096 };
7097 static const MCPhysReg ArgFPR64s[] = {
7098   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
7099   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
7100 };
7101 // This is an interim calling convention and it may be changed in the future.
7102 static const MCPhysReg ArgVRs[] = {
7103     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
7104     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
7105     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
7106 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
7107                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
7108                                      RISCV::V20M2, RISCV::V22M2};
7109 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
7110                                      RISCV::V20M4};
7111 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
7112 
7113 // Pass a 2*XLEN argument that has been split into two XLEN values through
7114 // registers or the stack as necessary.
7115 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
7116                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
7117                                 MVT ValVT2, MVT LocVT2,
7118                                 ISD::ArgFlagsTy ArgFlags2) {
7119   unsigned XLenInBytes = XLen / 8;
7120   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7121     // At least one half can be passed via register.
7122     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
7123                                      VA1.getLocVT(), CCValAssign::Full));
7124   } else {
7125     // Both halves must be passed on the stack, with proper alignment.
7126     Align StackAlign =
7127         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
7128     State.addLoc(
7129         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
7130                             State.AllocateStack(XLenInBytes, StackAlign),
7131                             VA1.getLocVT(), CCValAssign::Full));
7132     State.addLoc(CCValAssign::getMem(
7133         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7134         LocVT2, CCValAssign::Full));
7135     return false;
7136   }
7137 
7138   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7139     // The second half can also be passed via register.
7140     State.addLoc(
7141         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
7142   } else {
7143     // The second half is passed via the stack, without additional alignment.
7144     State.addLoc(CCValAssign::getMem(
7145         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7146         LocVT2, CCValAssign::Full));
7147   }
7148 
7149   return false;
7150 }
7151 
7152 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
7153                                Optional<unsigned> FirstMaskArgument,
7154                                CCState &State, const RISCVTargetLowering &TLI) {
7155   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
7156   if (RC == &RISCV::VRRegClass) {
7157     // Assign the first mask argument to V0.
7158     // This is an interim calling convention and it may be changed in the
7159     // future.
7160     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
7161       return State.AllocateReg(RISCV::V0);
7162     return State.AllocateReg(ArgVRs);
7163   }
7164   if (RC == &RISCV::VRM2RegClass)
7165     return State.AllocateReg(ArgVRM2s);
7166   if (RC == &RISCV::VRM4RegClass)
7167     return State.AllocateReg(ArgVRM4s);
7168   if (RC == &RISCV::VRM8RegClass)
7169     return State.AllocateReg(ArgVRM8s);
7170   llvm_unreachable("Unhandled register class for ValueType");
7171 }
7172 
7173 // Implements the RISC-V calling convention. Returns true upon failure.
7174 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
7175                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
7176                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
7177                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
7178                      Optional<unsigned> FirstMaskArgument) {
7179   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
7180   assert(XLen == 32 || XLen == 64);
7181   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
7182 
7183   // Any return value split in to more than two values can't be returned
7184   // directly. Vectors are returned via the available vector registers.
7185   if (!LocVT.isVector() && IsRet && ValNo > 1)
7186     return true;
7187 
7188   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
7189   // variadic argument, or if no F16/F32 argument registers are available.
7190   bool UseGPRForF16_F32 = true;
7191   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
7192   // variadic argument, or if no F64 argument registers are available.
7193   bool UseGPRForF64 = true;
7194 
7195   switch (ABI) {
7196   default:
7197     llvm_unreachable("Unexpected ABI");
7198   case RISCVABI::ABI_ILP32:
7199   case RISCVABI::ABI_LP64:
7200     break;
7201   case RISCVABI::ABI_ILP32F:
7202   case RISCVABI::ABI_LP64F:
7203     UseGPRForF16_F32 = !IsFixed;
7204     break;
7205   case RISCVABI::ABI_ILP32D:
7206   case RISCVABI::ABI_LP64D:
7207     UseGPRForF16_F32 = !IsFixed;
7208     UseGPRForF64 = !IsFixed;
7209     break;
7210   }
7211 
7212   // FPR16, FPR32, and FPR64 alias each other.
7213   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
7214     UseGPRForF16_F32 = true;
7215     UseGPRForF64 = true;
7216   }
7217 
7218   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
7219   // similar local variables rather than directly checking against the target
7220   // ABI.
7221 
7222   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
7223     LocVT = XLenVT;
7224     LocInfo = CCValAssign::BCvt;
7225   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
7226     LocVT = MVT::i64;
7227     LocInfo = CCValAssign::BCvt;
7228   }
7229 
7230   // If this is a variadic argument, the RISC-V calling convention requires
7231   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
7232   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
7233   // be used regardless of whether the original argument was split during
7234   // legalisation or not. The argument will not be passed by registers if the
7235   // original type is larger than 2*XLEN, so the register alignment rule does
7236   // not apply.
7237   unsigned TwoXLenInBytes = (2 * XLen) / 8;
7238   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
7239       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
7240     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
7241     // Skip 'odd' register if necessary.
7242     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
7243       State.AllocateReg(ArgGPRs);
7244   }
7245 
7246   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
7247   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
7248       State.getPendingArgFlags();
7249 
7250   assert(PendingLocs.size() == PendingArgFlags.size() &&
7251          "PendingLocs and PendingArgFlags out of sync");
7252 
7253   // Handle passing f64 on RV32D with a soft float ABI or when floating point
7254   // registers are exhausted.
7255   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
7256     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
7257            "Can't lower f64 if it is split");
7258     // Depending on available argument GPRS, f64 may be passed in a pair of
7259     // GPRs, split between a GPR and the stack, or passed completely on the
7260     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
7261     // cases.
7262     Register Reg = State.AllocateReg(ArgGPRs);
7263     LocVT = MVT::i32;
7264     if (!Reg) {
7265       unsigned StackOffset = State.AllocateStack(8, Align(8));
7266       State.addLoc(
7267           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
7268       return false;
7269     }
7270     if (!State.AllocateReg(ArgGPRs))
7271       State.AllocateStack(4, Align(4));
7272     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7273     return false;
7274   }
7275 
7276   // Fixed-length vectors are located in the corresponding scalable-vector
7277   // container types.
7278   if (ValVT.isFixedLengthVector())
7279     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
7280 
7281   // Split arguments might be passed indirectly, so keep track of the pending
7282   // values. Split vectors are passed via a mix of registers and indirectly, so
7283   // treat them as we would any other argument.
7284   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
7285     LocVT = XLenVT;
7286     LocInfo = CCValAssign::Indirect;
7287     PendingLocs.push_back(
7288         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
7289     PendingArgFlags.push_back(ArgFlags);
7290     if (!ArgFlags.isSplitEnd()) {
7291       return false;
7292     }
7293   }
7294 
7295   // If the split argument only had two elements, it should be passed directly
7296   // in registers or on the stack.
7297   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
7298       PendingLocs.size() <= 2) {
7299     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
7300     // Apply the normal calling convention rules to the first half of the
7301     // split argument.
7302     CCValAssign VA = PendingLocs[0];
7303     ISD::ArgFlagsTy AF = PendingArgFlags[0];
7304     PendingLocs.clear();
7305     PendingArgFlags.clear();
7306     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
7307                                ArgFlags);
7308   }
7309 
7310   // Allocate to a register if possible, or else a stack slot.
7311   Register Reg;
7312   unsigned StoreSizeBytes = XLen / 8;
7313   Align StackAlign = Align(XLen / 8);
7314 
7315   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
7316     Reg = State.AllocateReg(ArgFPR16s);
7317   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
7318     Reg = State.AllocateReg(ArgFPR32s);
7319   else if (ValVT == MVT::f64 && !UseGPRForF64)
7320     Reg = State.AllocateReg(ArgFPR64s);
7321   else if (ValVT.isVector()) {
7322     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
7323     if (!Reg) {
7324       // For return values, the vector must be passed fully via registers or
7325       // via the stack.
7326       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
7327       // but we're using all of them.
7328       if (IsRet)
7329         return true;
7330       // Try using a GPR to pass the address
7331       if ((Reg = State.AllocateReg(ArgGPRs))) {
7332         LocVT = XLenVT;
7333         LocInfo = CCValAssign::Indirect;
7334       } else if (ValVT.isScalableVector()) {
7335         report_fatal_error("Unable to pass scalable vector types on the stack");
7336       } else {
7337         // Pass fixed-length vectors on the stack.
7338         LocVT = ValVT;
7339         StoreSizeBytes = ValVT.getStoreSize();
7340         // Align vectors to their element sizes, being careful for vXi1
7341         // vectors.
7342         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
7343       }
7344     }
7345   } else {
7346     Reg = State.AllocateReg(ArgGPRs);
7347   }
7348 
7349   unsigned StackOffset =
7350       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
7351 
7352   // If we reach this point and PendingLocs is non-empty, we must be at the
7353   // end of a split argument that must be passed indirectly.
7354   if (!PendingLocs.empty()) {
7355     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
7356     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
7357 
7358     for (auto &It : PendingLocs) {
7359       if (Reg)
7360         It.convertToReg(Reg);
7361       else
7362         It.convertToMem(StackOffset);
7363       State.addLoc(It);
7364     }
7365     PendingLocs.clear();
7366     PendingArgFlags.clear();
7367     return false;
7368   }
7369 
7370   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
7371           (TLI.getSubtarget().hasStdExtV() && ValVT.isVector())) &&
7372          "Expected an XLenVT or vector types at this stage");
7373 
7374   if (Reg) {
7375     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7376     return false;
7377   }
7378 
7379   // When a floating-point value is passed on the stack, no bit-conversion is
7380   // needed.
7381   if (ValVT.isFloatingPoint()) {
7382     LocVT = ValVT;
7383     LocInfo = CCValAssign::Full;
7384   }
7385   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
7386   return false;
7387 }
7388 
7389 template <typename ArgTy>
7390 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
7391   for (const auto &ArgIdx : enumerate(Args)) {
7392     MVT ArgVT = ArgIdx.value().VT;
7393     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
7394       return ArgIdx.index();
7395   }
7396   return None;
7397 }
7398 
7399 void RISCVTargetLowering::analyzeInputArgs(
7400     MachineFunction &MF, CCState &CCInfo,
7401     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
7402     RISCVCCAssignFn Fn) const {
7403   unsigned NumArgs = Ins.size();
7404   FunctionType *FType = MF.getFunction().getFunctionType();
7405 
7406   Optional<unsigned> FirstMaskArgument;
7407   if (Subtarget.hasStdExtV())
7408     FirstMaskArgument = preAssignMask(Ins);
7409 
7410   for (unsigned i = 0; i != NumArgs; ++i) {
7411     MVT ArgVT = Ins[i].VT;
7412     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
7413 
7414     Type *ArgTy = nullptr;
7415     if (IsRet)
7416       ArgTy = FType->getReturnType();
7417     else if (Ins[i].isOrigArg())
7418       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
7419 
7420     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
7421     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
7422            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
7423            FirstMaskArgument)) {
7424       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
7425                         << EVT(ArgVT).getEVTString() << '\n');
7426       llvm_unreachable(nullptr);
7427     }
7428   }
7429 }
7430 
7431 void RISCVTargetLowering::analyzeOutputArgs(
7432     MachineFunction &MF, CCState &CCInfo,
7433     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
7434     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
7435   unsigned NumArgs = Outs.size();
7436 
7437   Optional<unsigned> FirstMaskArgument;
7438   if (Subtarget.hasStdExtV())
7439     FirstMaskArgument = preAssignMask(Outs);
7440 
7441   for (unsigned i = 0; i != NumArgs; i++) {
7442     MVT ArgVT = Outs[i].VT;
7443     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
7444     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
7445 
7446     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
7447     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
7448            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
7449            FirstMaskArgument)) {
7450       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
7451                         << EVT(ArgVT).getEVTString() << "\n");
7452       llvm_unreachable(nullptr);
7453     }
7454   }
7455 }
7456 
7457 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
7458 // values.
7459 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
7460                                    const CCValAssign &VA, const SDLoc &DL,
7461                                    const RISCVSubtarget &Subtarget) {
7462   switch (VA.getLocInfo()) {
7463   default:
7464     llvm_unreachable("Unexpected CCValAssign::LocInfo");
7465   case CCValAssign::Full:
7466     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
7467       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
7468     break;
7469   case CCValAssign::BCvt:
7470     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
7471       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
7472     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
7473       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
7474     else
7475       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
7476     break;
7477   }
7478   return Val;
7479 }
7480 
7481 // The caller is responsible for loading the full value if the argument is
7482 // passed with CCValAssign::Indirect.
7483 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
7484                                 const CCValAssign &VA, const SDLoc &DL,
7485                                 const RISCVTargetLowering &TLI) {
7486   MachineFunction &MF = DAG.getMachineFunction();
7487   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7488   EVT LocVT = VA.getLocVT();
7489   SDValue Val;
7490   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
7491   Register VReg = RegInfo.createVirtualRegister(RC);
7492   RegInfo.addLiveIn(VA.getLocReg(), VReg);
7493   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
7494 
7495   if (VA.getLocInfo() == CCValAssign::Indirect)
7496     return Val;
7497 
7498   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
7499 }
7500 
7501 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
7502                                    const CCValAssign &VA, const SDLoc &DL,
7503                                    const RISCVSubtarget &Subtarget) {
7504   EVT LocVT = VA.getLocVT();
7505 
7506   switch (VA.getLocInfo()) {
7507   default:
7508     llvm_unreachable("Unexpected CCValAssign::LocInfo");
7509   case CCValAssign::Full:
7510     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
7511       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
7512     break;
7513   case CCValAssign::BCvt:
7514     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
7515       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
7516     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
7517       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
7518     else
7519       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
7520     break;
7521   }
7522   return Val;
7523 }
7524 
7525 // The caller is responsible for loading the full value if the argument is
7526 // passed with CCValAssign::Indirect.
7527 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
7528                                 const CCValAssign &VA, const SDLoc &DL) {
7529   MachineFunction &MF = DAG.getMachineFunction();
7530   MachineFrameInfo &MFI = MF.getFrameInfo();
7531   EVT LocVT = VA.getLocVT();
7532   EVT ValVT = VA.getValVT();
7533   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
7534   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
7535                                  /*Immutable=*/true);
7536   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7537   SDValue Val;
7538 
7539   ISD::LoadExtType ExtType;
7540   switch (VA.getLocInfo()) {
7541   default:
7542     llvm_unreachable("Unexpected CCValAssign::LocInfo");
7543   case CCValAssign::Full:
7544   case CCValAssign::Indirect:
7545   case CCValAssign::BCvt:
7546     ExtType = ISD::NON_EXTLOAD;
7547     break;
7548   }
7549   Val = DAG.getExtLoad(
7550       ExtType, DL, LocVT, Chain, FIN,
7551       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
7552   return Val;
7553 }
7554 
7555 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
7556                                        const CCValAssign &VA, const SDLoc &DL) {
7557   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
7558          "Unexpected VA");
7559   MachineFunction &MF = DAG.getMachineFunction();
7560   MachineFrameInfo &MFI = MF.getFrameInfo();
7561   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7562 
7563   if (VA.isMemLoc()) {
7564     // f64 is passed on the stack.
7565     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
7566     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
7567     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
7568                        MachinePointerInfo::getFixedStack(MF, FI));
7569   }
7570 
7571   assert(VA.isRegLoc() && "Expected register VA assignment");
7572 
7573   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7574   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
7575   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
7576   SDValue Hi;
7577   if (VA.getLocReg() == RISCV::X17) {
7578     // Second half of f64 is passed on the stack.
7579     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
7580     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
7581     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
7582                      MachinePointerInfo::getFixedStack(MF, FI));
7583   } else {
7584     // Second half of f64 is passed in another GPR.
7585     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7586     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
7587     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
7588   }
7589   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
7590 }
7591 
7592 // FastCC has less than 1% performance improvement for some particular
7593 // benchmark. But theoretically, it may has benenfit for some cases.
7594 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
7595                             unsigned ValNo, MVT ValVT, MVT LocVT,
7596                             CCValAssign::LocInfo LocInfo,
7597                             ISD::ArgFlagsTy ArgFlags, CCState &State,
7598                             bool IsFixed, bool IsRet, Type *OrigTy,
7599                             const RISCVTargetLowering &TLI,
7600                             Optional<unsigned> FirstMaskArgument) {
7601 
7602   // X5 and X6 might be used for save-restore libcall.
7603   static const MCPhysReg GPRList[] = {
7604       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
7605       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
7606       RISCV::X29, RISCV::X30, RISCV::X31};
7607 
7608   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
7609     if (unsigned Reg = State.AllocateReg(GPRList)) {
7610       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7611       return false;
7612     }
7613   }
7614 
7615   if (LocVT == MVT::f16) {
7616     static const MCPhysReg FPR16List[] = {
7617         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
7618         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
7619         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
7620         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
7621     if (unsigned Reg = State.AllocateReg(FPR16List)) {
7622       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7623       return false;
7624     }
7625   }
7626 
7627   if (LocVT == MVT::f32) {
7628     static const MCPhysReg FPR32List[] = {
7629         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
7630         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
7631         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
7632         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
7633     if (unsigned Reg = State.AllocateReg(FPR32List)) {
7634       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7635       return false;
7636     }
7637   }
7638 
7639   if (LocVT == MVT::f64) {
7640     static const MCPhysReg FPR64List[] = {
7641         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
7642         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
7643         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
7644         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
7645     if (unsigned Reg = State.AllocateReg(FPR64List)) {
7646       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7647       return false;
7648     }
7649   }
7650 
7651   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
7652     unsigned Offset4 = State.AllocateStack(4, Align(4));
7653     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
7654     return false;
7655   }
7656 
7657   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
7658     unsigned Offset5 = State.AllocateStack(8, Align(8));
7659     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
7660     return false;
7661   }
7662 
7663   if (LocVT.isVector()) {
7664     if (unsigned Reg =
7665             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
7666       // Fixed-length vectors are located in the corresponding scalable-vector
7667       // container types.
7668       if (ValVT.isFixedLengthVector())
7669         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
7670       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7671     } else {
7672       // Try and pass the address via a "fast" GPR.
7673       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
7674         LocInfo = CCValAssign::Indirect;
7675         LocVT = TLI.getSubtarget().getXLenVT();
7676         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
7677       } else if (ValVT.isFixedLengthVector()) {
7678         auto StackAlign =
7679             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
7680         unsigned StackOffset =
7681             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
7682         State.addLoc(
7683             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
7684       } else {
7685         // Can't pass scalable vectors on the stack.
7686         return true;
7687       }
7688     }
7689 
7690     return false;
7691   }
7692 
7693   return true; // CC didn't match.
7694 }
7695 
7696 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
7697                          CCValAssign::LocInfo LocInfo,
7698                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
7699 
7700   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
7701     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
7702     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
7703     static const MCPhysReg GPRList[] = {
7704         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
7705         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
7706     if (unsigned Reg = State.AllocateReg(GPRList)) {
7707       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7708       return false;
7709     }
7710   }
7711 
7712   if (LocVT == MVT::f32) {
7713     // Pass in STG registers: F1, ..., F6
7714     //                        fs0 ... fs5
7715     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
7716                                           RISCV::F18_F, RISCV::F19_F,
7717                                           RISCV::F20_F, RISCV::F21_F};
7718     if (unsigned Reg = State.AllocateReg(FPR32List)) {
7719       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7720       return false;
7721     }
7722   }
7723 
7724   if (LocVT == MVT::f64) {
7725     // Pass in STG registers: D1, ..., D6
7726     //                        fs6 ... fs11
7727     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
7728                                           RISCV::F24_D, RISCV::F25_D,
7729                                           RISCV::F26_D, RISCV::F27_D};
7730     if (unsigned Reg = State.AllocateReg(FPR64List)) {
7731       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7732       return false;
7733     }
7734   }
7735 
7736   report_fatal_error("No registers left in GHC calling convention");
7737   return true;
7738 }
7739 
7740 // Transform physical registers into virtual registers.
7741 SDValue RISCVTargetLowering::LowerFormalArguments(
7742     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
7743     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
7744     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7745 
7746   MachineFunction &MF = DAG.getMachineFunction();
7747 
7748   switch (CallConv) {
7749   default:
7750     report_fatal_error("Unsupported calling convention");
7751   case CallingConv::C:
7752   case CallingConv::Fast:
7753     break;
7754   case CallingConv::GHC:
7755     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
7756         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
7757       report_fatal_error(
7758         "GHC calling convention requires the F and D instruction set extensions");
7759   }
7760 
7761   const Function &Func = MF.getFunction();
7762   if (Func.hasFnAttribute("interrupt")) {
7763     if (!Func.arg_empty())
7764       report_fatal_error(
7765         "Functions with the interrupt attribute cannot have arguments!");
7766 
7767     StringRef Kind =
7768       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
7769 
7770     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
7771       report_fatal_error(
7772         "Function interrupt attribute argument not supported!");
7773   }
7774 
7775   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7776   MVT XLenVT = Subtarget.getXLenVT();
7777   unsigned XLenInBytes = Subtarget.getXLen() / 8;
7778   // Used with vargs to acumulate store chains.
7779   std::vector<SDValue> OutChains;
7780 
7781   // Assign locations to all of the incoming arguments.
7782   SmallVector<CCValAssign, 16> ArgLocs;
7783   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
7784 
7785   if (CallConv == CallingConv::GHC)
7786     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
7787   else
7788     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
7789                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
7790                                                    : CC_RISCV);
7791 
7792   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
7793     CCValAssign &VA = ArgLocs[i];
7794     SDValue ArgValue;
7795     // Passing f64 on RV32D with a soft float ABI must be handled as a special
7796     // case.
7797     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
7798       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
7799     else if (VA.isRegLoc())
7800       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
7801     else
7802       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
7803 
7804     if (VA.getLocInfo() == CCValAssign::Indirect) {
7805       // If the original argument was split and passed by reference (e.g. i128
7806       // on RV32), we need to load all parts of it here (using the same
7807       // address). Vectors may be partly split to registers and partly to the
7808       // stack, in which case the base address is partly offset and subsequent
7809       // stores are relative to that.
7810       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
7811                                    MachinePointerInfo()));
7812       unsigned ArgIndex = Ins[i].OrigArgIndex;
7813       unsigned ArgPartOffset = Ins[i].PartOffset;
7814       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
7815       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
7816         CCValAssign &PartVA = ArgLocs[i + 1];
7817         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
7818         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
7819         if (PartVA.getValVT().isScalableVector())
7820           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
7821         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
7822         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
7823                                      MachinePointerInfo()));
7824         ++i;
7825       }
7826       continue;
7827     }
7828     InVals.push_back(ArgValue);
7829   }
7830 
7831   if (IsVarArg) {
7832     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
7833     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
7834     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
7835     MachineFrameInfo &MFI = MF.getFrameInfo();
7836     MachineRegisterInfo &RegInfo = MF.getRegInfo();
7837     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
7838 
7839     // Offset of the first variable argument from stack pointer, and size of
7840     // the vararg save area. For now, the varargs save area is either zero or
7841     // large enough to hold a0-a7.
7842     int VaArgOffset, VarArgsSaveSize;
7843 
7844     // If all registers are allocated, then all varargs must be passed on the
7845     // stack and we don't need to save any argregs.
7846     if (ArgRegs.size() == Idx) {
7847       VaArgOffset = CCInfo.getNextStackOffset();
7848       VarArgsSaveSize = 0;
7849     } else {
7850       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
7851       VaArgOffset = -VarArgsSaveSize;
7852     }
7853 
7854     // Record the frame index of the first variable argument
7855     // which is a value necessary to VASTART.
7856     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
7857     RVFI->setVarArgsFrameIndex(FI);
7858 
7859     // If saving an odd number of registers then create an extra stack slot to
7860     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
7861     // offsets to even-numbered registered remain 2*XLEN-aligned.
7862     if (Idx % 2) {
7863       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
7864       VarArgsSaveSize += XLenInBytes;
7865     }
7866 
7867     // Copy the integer registers that may have been used for passing varargs
7868     // to the vararg save area.
7869     for (unsigned I = Idx; I < ArgRegs.size();
7870          ++I, VaArgOffset += XLenInBytes) {
7871       const Register Reg = RegInfo.createVirtualRegister(RC);
7872       RegInfo.addLiveIn(ArgRegs[I], Reg);
7873       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
7874       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
7875       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
7876       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
7877                                    MachinePointerInfo::getFixedStack(MF, FI));
7878       cast<StoreSDNode>(Store.getNode())
7879           ->getMemOperand()
7880           ->setValue((Value *)nullptr);
7881       OutChains.push_back(Store);
7882     }
7883     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
7884   }
7885 
7886   // All stores are grouped in one node to allow the matching between
7887   // the size of Ins and InVals. This only happens for vararg functions.
7888   if (!OutChains.empty()) {
7889     OutChains.push_back(Chain);
7890     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
7891   }
7892 
7893   return Chain;
7894 }
7895 
7896 /// isEligibleForTailCallOptimization - Check whether the call is eligible
7897 /// for tail call optimization.
7898 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
7899 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
7900     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
7901     const SmallVector<CCValAssign, 16> &ArgLocs) const {
7902 
7903   auto &Callee = CLI.Callee;
7904   auto CalleeCC = CLI.CallConv;
7905   auto &Outs = CLI.Outs;
7906   auto &Caller = MF.getFunction();
7907   auto CallerCC = Caller.getCallingConv();
7908 
7909   // Exception-handling functions need a special set of instructions to
7910   // indicate a return to the hardware. Tail-calling another function would
7911   // probably break this.
7912   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
7913   // should be expanded as new function attributes are introduced.
7914   if (Caller.hasFnAttribute("interrupt"))
7915     return false;
7916 
7917   // Do not tail call opt if the stack is used to pass parameters.
7918   if (CCInfo.getNextStackOffset() != 0)
7919     return false;
7920 
7921   // Do not tail call opt if any parameters need to be passed indirectly.
7922   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
7923   // passed indirectly. So the address of the value will be passed in a
7924   // register, or if not available, then the address is put on the stack. In
7925   // order to pass indirectly, space on the stack often needs to be allocated
7926   // in order to store the value. In this case the CCInfo.getNextStackOffset()
7927   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
7928   // are passed CCValAssign::Indirect.
7929   for (auto &VA : ArgLocs)
7930     if (VA.getLocInfo() == CCValAssign::Indirect)
7931       return false;
7932 
7933   // Do not tail call opt if either caller or callee uses struct return
7934   // semantics.
7935   auto IsCallerStructRet = Caller.hasStructRetAttr();
7936   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
7937   if (IsCallerStructRet || IsCalleeStructRet)
7938     return false;
7939 
7940   // Externally-defined functions with weak linkage should not be
7941   // tail-called. The behaviour of branch instructions in this situation (as
7942   // used for tail calls) is implementation-defined, so we cannot rely on the
7943   // linker replacing the tail call with a return.
7944   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
7945     const GlobalValue *GV = G->getGlobal();
7946     if (GV->hasExternalWeakLinkage())
7947       return false;
7948   }
7949 
7950   // The callee has to preserve all registers the caller needs to preserve.
7951   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
7952   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
7953   if (CalleeCC != CallerCC) {
7954     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
7955     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
7956       return false;
7957   }
7958 
7959   // Byval parameters hand the function a pointer directly into the stack area
7960   // we want to reuse during a tail call. Working around this *is* possible
7961   // but less efficient and uglier in LowerCall.
7962   for (auto &Arg : Outs)
7963     if (Arg.Flags.isByVal())
7964       return false;
7965 
7966   return true;
7967 }
7968 
7969 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
7970   return DAG.getDataLayout().getPrefTypeAlign(
7971       VT.getTypeForEVT(*DAG.getContext()));
7972 }
7973 
7974 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
7975 // and output parameter nodes.
7976 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
7977                                        SmallVectorImpl<SDValue> &InVals) const {
7978   SelectionDAG &DAG = CLI.DAG;
7979   SDLoc &DL = CLI.DL;
7980   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
7981   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
7982   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
7983   SDValue Chain = CLI.Chain;
7984   SDValue Callee = CLI.Callee;
7985   bool &IsTailCall = CLI.IsTailCall;
7986   CallingConv::ID CallConv = CLI.CallConv;
7987   bool IsVarArg = CLI.IsVarArg;
7988   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7989   MVT XLenVT = Subtarget.getXLenVT();
7990 
7991   MachineFunction &MF = DAG.getMachineFunction();
7992 
7993   // Analyze the operands of the call, assigning locations to each operand.
7994   SmallVector<CCValAssign, 16> ArgLocs;
7995   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
7996 
7997   if (CallConv == CallingConv::GHC)
7998     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
7999   else
8000     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
8001                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
8002                                                     : CC_RISCV);
8003 
8004   // Check if it's really possible to do a tail call.
8005   if (IsTailCall)
8006     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
8007 
8008   if (IsTailCall)
8009     ++NumTailCalls;
8010   else if (CLI.CB && CLI.CB->isMustTailCall())
8011     report_fatal_error("failed to perform tail call elimination on a call "
8012                        "site marked musttail");
8013 
8014   // Get a count of how many bytes are to be pushed on the stack.
8015   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
8016 
8017   // Create local copies for byval args
8018   SmallVector<SDValue, 8> ByValArgs;
8019   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8020     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8021     if (!Flags.isByVal())
8022       continue;
8023 
8024     SDValue Arg = OutVals[i];
8025     unsigned Size = Flags.getByValSize();
8026     Align Alignment = Flags.getNonZeroByValAlign();
8027 
8028     int FI =
8029         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
8030     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
8031     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
8032 
8033     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
8034                           /*IsVolatile=*/false,
8035                           /*AlwaysInline=*/false, IsTailCall,
8036                           MachinePointerInfo(), MachinePointerInfo());
8037     ByValArgs.push_back(FIPtr);
8038   }
8039 
8040   if (!IsTailCall)
8041     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
8042 
8043   // Copy argument values to their designated locations.
8044   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
8045   SmallVector<SDValue, 8> MemOpChains;
8046   SDValue StackPtr;
8047   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
8048     CCValAssign &VA = ArgLocs[i];
8049     SDValue ArgValue = OutVals[i];
8050     ISD::ArgFlagsTy Flags = Outs[i].Flags;
8051 
8052     // Handle passing f64 on RV32D with a soft float ABI as a special case.
8053     bool IsF64OnRV32DSoftABI =
8054         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
8055     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
8056       SDValue SplitF64 = DAG.getNode(
8057           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
8058       SDValue Lo = SplitF64.getValue(0);
8059       SDValue Hi = SplitF64.getValue(1);
8060 
8061       Register RegLo = VA.getLocReg();
8062       RegsToPass.push_back(std::make_pair(RegLo, Lo));
8063 
8064       if (RegLo == RISCV::X17) {
8065         // Second half of f64 is passed on the stack.
8066         // Work out the address of the stack slot.
8067         if (!StackPtr.getNode())
8068           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8069         // Emit the store.
8070         MemOpChains.push_back(
8071             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
8072       } else {
8073         // Second half of f64 is passed in another GPR.
8074         assert(RegLo < RISCV::X31 && "Invalid register pair");
8075         Register RegHigh = RegLo + 1;
8076         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
8077       }
8078       continue;
8079     }
8080 
8081     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
8082     // as any other MemLoc.
8083 
8084     // Promote the value if needed.
8085     // For now, only handle fully promoted and indirect arguments.
8086     if (VA.getLocInfo() == CCValAssign::Indirect) {
8087       // Store the argument in a stack slot and pass its address.
8088       Align StackAlign =
8089           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
8090                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
8091       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
8092       // If the original argument was split (e.g. i128), we need
8093       // to store the required parts of it here (and pass just one address).
8094       // Vectors may be partly split to registers and partly to the stack, in
8095       // which case the base address is partly offset and subsequent stores are
8096       // relative to that.
8097       unsigned ArgIndex = Outs[i].OrigArgIndex;
8098       unsigned ArgPartOffset = Outs[i].PartOffset;
8099       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8100       // Calculate the total size to store. We don't have access to what we're
8101       // actually storing other than performing the loop and collecting the
8102       // info.
8103       SmallVector<std::pair<SDValue, SDValue>> Parts;
8104       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
8105         SDValue PartValue = OutVals[i + 1];
8106         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
8107         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8108         EVT PartVT = PartValue.getValueType();
8109         if (PartVT.isScalableVector())
8110           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8111         StoredSize += PartVT.getStoreSize();
8112         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
8113         Parts.push_back(std::make_pair(PartValue, Offset));
8114         ++i;
8115       }
8116       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
8117       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
8118       MemOpChains.push_back(
8119           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
8120                        MachinePointerInfo::getFixedStack(MF, FI)));
8121       for (const auto &Part : Parts) {
8122         SDValue PartValue = Part.first;
8123         SDValue PartOffset = Part.second;
8124         SDValue Address =
8125             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
8126         MemOpChains.push_back(
8127             DAG.getStore(Chain, DL, PartValue, Address,
8128                          MachinePointerInfo::getFixedStack(MF, FI)));
8129       }
8130       ArgValue = SpillSlot;
8131     } else {
8132       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
8133     }
8134 
8135     // Use local copy if it is a byval arg.
8136     if (Flags.isByVal())
8137       ArgValue = ByValArgs[j++];
8138 
8139     if (VA.isRegLoc()) {
8140       // Queue up the argument copies and emit them at the end.
8141       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
8142     } else {
8143       assert(VA.isMemLoc() && "Argument not register or memory");
8144       assert(!IsTailCall && "Tail call not allowed if stack is used "
8145                             "for passing parameters");
8146 
8147       // Work out the address of the stack slot.
8148       if (!StackPtr.getNode())
8149         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8150       SDValue Address =
8151           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
8152                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
8153 
8154       // Emit the store.
8155       MemOpChains.push_back(
8156           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
8157     }
8158   }
8159 
8160   // Join the stores, which are independent of one another.
8161   if (!MemOpChains.empty())
8162     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
8163 
8164   SDValue Glue;
8165 
8166   // Build a sequence of copy-to-reg nodes, chained and glued together.
8167   for (auto &Reg : RegsToPass) {
8168     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
8169     Glue = Chain.getValue(1);
8170   }
8171 
8172   // Validate that none of the argument registers have been marked as
8173   // reserved, if so report an error. Do the same for the return address if this
8174   // is not a tailcall.
8175   validateCCReservedRegs(RegsToPass, MF);
8176   if (!IsTailCall &&
8177       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
8178     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8179         MF.getFunction(),
8180         "Return address register required, but has been reserved."});
8181 
8182   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
8183   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
8184   // split it and then direct call can be matched by PseudoCALL.
8185   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
8186     const GlobalValue *GV = S->getGlobal();
8187 
8188     unsigned OpFlags = RISCVII::MO_CALL;
8189     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
8190       OpFlags = RISCVII::MO_PLT;
8191 
8192     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
8193   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
8194     unsigned OpFlags = RISCVII::MO_CALL;
8195 
8196     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
8197                                                  nullptr))
8198       OpFlags = RISCVII::MO_PLT;
8199 
8200     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
8201   }
8202 
8203   // The first call operand is the chain and the second is the target address.
8204   SmallVector<SDValue, 8> Ops;
8205   Ops.push_back(Chain);
8206   Ops.push_back(Callee);
8207 
8208   // Add argument registers to the end of the list so that they are
8209   // known live into the call.
8210   for (auto &Reg : RegsToPass)
8211     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
8212 
8213   if (!IsTailCall) {
8214     // Add a register mask operand representing the call-preserved registers.
8215     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
8216     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
8217     assert(Mask && "Missing call preserved mask for calling convention");
8218     Ops.push_back(DAG.getRegisterMask(Mask));
8219   }
8220 
8221   // Glue the call to the argument copies, if any.
8222   if (Glue.getNode())
8223     Ops.push_back(Glue);
8224 
8225   // Emit the call.
8226   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8227 
8228   if (IsTailCall) {
8229     MF.getFrameInfo().setHasTailCall();
8230     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
8231   }
8232 
8233   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
8234   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
8235   Glue = Chain.getValue(1);
8236 
8237   // Mark the end of the call, which is glued to the call itself.
8238   Chain = DAG.getCALLSEQ_END(Chain,
8239                              DAG.getConstant(NumBytes, DL, PtrVT, true),
8240                              DAG.getConstant(0, DL, PtrVT, true),
8241                              Glue, DL);
8242   Glue = Chain.getValue(1);
8243 
8244   // Assign locations to each value returned by this call.
8245   SmallVector<CCValAssign, 16> RVLocs;
8246   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
8247   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
8248 
8249   // Copy all of the result registers out of their specified physreg.
8250   for (auto &VA : RVLocs) {
8251     // Copy the value out
8252     SDValue RetValue =
8253         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
8254     // Glue the RetValue to the end of the call sequence
8255     Chain = RetValue.getValue(1);
8256     Glue = RetValue.getValue(2);
8257 
8258     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
8259       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
8260       SDValue RetValue2 =
8261           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
8262       Chain = RetValue2.getValue(1);
8263       Glue = RetValue2.getValue(2);
8264       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
8265                              RetValue2);
8266     }
8267 
8268     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
8269 
8270     InVals.push_back(RetValue);
8271   }
8272 
8273   return Chain;
8274 }
8275 
8276 bool RISCVTargetLowering::CanLowerReturn(
8277     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
8278     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
8279   SmallVector<CCValAssign, 16> RVLocs;
8280   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
8281 
8282   Optional<unsigned> FirstMaskArgument;
8283   if (Subtarget.hasStdExtV())
8284     FirstMaskArgument = preAssignMask(Outs);
8285 
8286   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8287     MVT VT = Outs[i].VT;
8288     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8289     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8290     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
8291                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
8292                  *this, FirstMaskArgument))
8293       return false;
8294   }
8295   return true;
8296 }
8297 
8298 SDValue
8299 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
8300                                  bool IsVarArg,
8301                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
8302                                  const SmallVectorImpl<SDValue> &OutVals,
8303                                  const SDLoc &DL, SelectionDAG &DAG) const {
8304   const MachineFunction &MF = DAG.getMachineFunction();
8305   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
8306 
8307   // Stores the assignment of the return value to a location.
8308   SmallVector<CCValAssign, 16> RVLocs;
8309 
8310   // Info about the registers and stack slot.
8311   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
8312                  *DAG.getContext());
8313 
8314   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
8315                     nullptr, CC_RISCV);
8316 
8317   if (CallConv == CallingConv::GHC && !RVLocs.empty())
8318     report_fatal_error("GHC functions return void only");
8319 
8320   SDValue Glue;
8321   SmallVector<SDValue, 4> RetOps(1, Chain);
8322 
8323   // Copy the result values into the output registers.
8324   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
8325     SDValue Val = OutVals[i];
8326     CCValAssign &VA = RVLocs[i];
8327     assert(VA.isRegLoc() && "Can only return in registers!");
8328 
8329     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
8330       // Handle returning f64 on RV32D with a soft float ABI.
8331       assert(VA.isRegLoc() && "Expected return via registers");
8332       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
8333                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
8334       SDValue Lo = SplitF64.getValue(0);
8335       SDValue Hi = SplitF64.getValue(1);
8336       Register RegLo = VA.getLocReg();
8337       assert(RegLo < RISCV::X31 && "Invalid register pair");
8338       Register RegHi = RegLo + 1;
8339 
8340       if (STI.isRegisterReservedByUser(RegLo) ||
8341           STI.isRegisterReservedByUser(RegHi))
8342         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8343             MF.getFunction(),
8344             "Return value register required, but has been reserved."});
8345 
8346       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
8347       Glue = Chain.getValue(1);
8348       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
8349       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
8350       Glue = Chain.getValue(1);
8351       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
8352     } else {
8353       // Handle a 'normal' return.
8354       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
8355       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
8356 
8357       if (STI.isRegisterReservedByUser(VA.getLocReg()))
8358         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8359             MF.getFunction(),
8360             "Return value register required, but has been reserved."});
8361 
8362       // Guarantee that all emitted copies are stuck together.
8363       Glue = Chain.getValue(1);
8364       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
8365     }
8366   }
8367 
8368   RetOps[0] = Chain; // Update chain.
8369 
8370   // Add the glue node if we have it.
8371   if (Glue.getNode()) {
8372     RetOps.push_back(Glue);
8373   }
8374 
8375   unsigned RetOpc = RISCVISD::RET_FLAG;
8376   // Interrupt service routines use different return instructions.
8377   const Function &Func = DAG.getMachineFunction().getFunction();
8378   if (Func.hasFnAttribute("interrupt")) {
8379     if (!Func.getReturnType()->isVoidTy())
8380       report_fatal_error(
8381           "Functions with the interrupt attribute must have void return type!");
8382 
8383     MachineFunction &MF = DAG.getMachineFunction();
8384     StringRef Kind =
8385       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8386 
8387     if (Kind == "user")
8388       RetOpc = RISCVISD::URET_FLAG;
8389     else if (Kind == "supervisor")
8390       RetOpc = RISCVISD::SRET_FLAG;
8391     else
8392       RetOpc = RISCVISD::MRET_FLAG;
8393   }
8394 
8395   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
8396 }
8397 
8398 void RISCVTargetLowering::validateCCReservedRegs(
8399     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
8400     MachineFunction &MF) const {
8401   const Function &F = MF.getFunction();
8402   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
8403 
8404   if (llvm::any_of(Regs, [&STI](auto Reg) {
8405         return STI.isRegisterReservedByUser(Reg.first);
8406       }))
8407     F.getContext().diagnose(DiagnosticInfoUnsupported{
8408         F, "Argument register required, but has been reserved."});
8409 }
8410 
8411 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
8412   return CI->isTailCall();
8413 }
8414 
8415 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
8416 #define NODE_NAME_CASE(NODE)                                                   \
8417   case RISCVISD::NODE:                                                         \
8418     return "RISCVISD::" #NODE;
8419   // clang-format off
8420   switch ((RISCVISD::NodeType)Opcode) {
8421   case RISCVISD::FIRST_NUMBER:
8422     break;
8423   NODE_NAME_CASE(RET_FLAG)
8424   NODE_NAME_CASE(URET_FLAG)
8425   NODE_NAME_CASE(SRET_FLAG)
8426   NODE_NAME_CASE(MRET_FLAG)
8427   NODE_NAME_CASE(CALL)
8428   NODE_NAME_CASE(SELECT_CC)
8429   NODE_NAME_CASE(BR_CC)
8430   NODE_NAME_CASE(BuildPairF64)
8431   NODE_NAME_CASE(SplitF64)
8432   NODE_NAME_CASE(TAIL)
8433   NODE_NAME_CASE(MULHSU)
8434   NODE_NAME_CASE(SLLW)
8435   NODE_NAME_CASE(SRAW)
8436   NODE_NAME_CASE(SRLW)
8437   NODE_NAME_CASE(DIVW)
8438   NODE_NAME_CASE(DIVUW)
8439   NODE_NAME_CASE(REMUW)
8440   NODE_NAME_CASE(ROLW)
8441   NODE_NAME_CASE(RORW)
8442   NODE_NAME_CASE(CLZW)
8443   NODE_NAME_CASE(CTZW)
8444   NODE_NAME_CASE(FSLW)
8445   NODE_NAME_CASE(FSRW)
8446   NODE_NAME_CASE(FSL)
8447   NODE_NAME_CASE(FSR)
8448   NODE_NAME_CASE(FMV_H_X)
8449   NODE_NAME_CASE(FMV_X_ANYEXTH)
8450   NODE_NAME_CASE(FMV_W_X_RV64)
8451   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
8452   NODE_NAME_CASE(FCVT_X_RTZ)
8453   NODE_NAME_CASE(FCVT_XU_RTZ)
8454   NODE_NAME_CASE(FCVT_W_RTZ_RV64)
8455   NODE_NAME_CASE(FCVT_WU_RTZ_RV64)
8456   NODE_NAME_CASE(READ_CYCLE_WIDE)
8457   NODE_NAME_CASE(GREV)
8458   NODE_NAME_CASE(GREVW)
8459   NODE_NAME_CASE(GORC)
8460   NODE_NAME_CASE(GORCW)
8461   NODE_NAME_CASE(SHFL)
8462   NODE_NAME_CASE(SHFLW)
8463   NODE_NAME_CASE(UNSHFL)
8464   NODE_NAME_CASE(UNSHFLW)
8465   NODE_NAME_CASE(BCOMPRESS)
8466   NODE_NAME_CASE(BCOMPRESSW)
8467   NODE_NAME_CASE(BDECOMPRESS)
8468   NODE_NAME_CASE(BDECOMPRESSW)
8469   NODE_NAME_CASE(VMV_V_X_VL)
8470   NODE_NAME_CASE(VFMV_V_F_VL)
8471   NODE_NAME_CASE(VMV_X_S)
8472   NODE_NAME_CASE(VMV_S_X_VL)
8473   NODE_NAME_CASE(VFMV_S_F_VL)
8474   NODE_NAME_CASE(SPLAT_VECTOR_I64)
8475   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
8476   NODE_NAME_CASE(READ_VLENB)
8477   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
8478   NODE_NAME_CASE(VSLIDEUP_VL)
8479   NODE_NAME_CASE(VSLIDE1UP_VL)
8480   NODE_NAME_CASE(VSLIDEDOWN_VL)
8481   NODE_NAME_CASE(VSLIDE1DOWN_VL)
8482   NODE_NAME_CASE(VID_VL)
8483   NODE_NAME_CASE(VFNCVT_ROD_VL)
8484   NODE_NAME_CASE(VECREDUCE_ADD_VL)
8485   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
8486   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
8487   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
8488   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
8489   NODE_NAME_CASE(VECREDUCE_AND_VL)
8490   NODE_NAME_CASE(VECREDUCE_OR_VL)
8491   NODE_NAME_CASE(VECREDUCE_XOR_VL)
8492   NODE_NAME_CASE(VECREDUCE_FADD_VL)
8493   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
8494   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
8495   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
8496   NODE_NAME_CASE(ADD_VL)
8497   NODE_NAME_CASE(AND_VL)
8498   NODE_NAME_CASE(MUL_VL)
8499   NODE_NAME_CASE(OR_VL)
8500   NODE_NAME_CASE(SDIV_VL)
8501   NODE_NAME_CASE(SHL_VL)
8502   NODE_NAME_CASE(SREM_VL)
8503   NODE_NAME_CASE(SRA_VL)
8504   NODE_NAME_CASE(SRL_VL)
8505   NODE_NAME_CASE(SUB_VL)
8506   NODE_NAME_CASE(UDIV_VL)
8507   NODE_NAME_CASE(UREM_VL)
8508   NODE_NAME_CASE(XOR_VL)
8509   NODE_NAME_CASE(SADDSAT_VL)
8510   NODE_NAME_CASE(UADDSAT_VL)
8511   NODE_NAME_CASE(SSUBSAT_VL)
8512   NODE_NAME_CASE(USUBSAT_VL)
8513   NODE_NAME_CASE(FADD_VL)
8514   NODE_NAME_CASE(FSUB_VL)
8515   NODE_NAME_CASE(FMUL_VL)
8516   NODE_NAME_CASE(FDIV_VL)
8517   NODE_NAME_CASE(FNEG_VL)
8518   NODE_NAME_CASE(FABS_VL)
8519   NODE_NAME_CASE(FSQRT_VL)
8520   NODE_NAME_CASE(FMA_VL)
8521   NODE_NAME_CASE(FCOPYSIGN_VL)
8522   NODE_NAME_CASE(SMIN_VL)
8523   NODE_NAME_CASE(SMAX_VL)
8524   NODE_NAME_CASE(UMIN_VL)
8525   NODE_NAME_CASE(UMAX_VL)
8526   NODE_NAME_CASE(FMINNUM_VL)
8527   NODE_NAME_CASE(FMAXNUM_VL)
8528   NODE_NAME_CASE(MULHS_VL)
8529   NODE_NAME_CASE(MULHU_VL)
8530   NODE_NAME_CASE(FP_TO_SINT_VL)
8531   NODE_NAME_CASE(FP_TO_UINT_VL)
8532   NODE_NAME_CASE(SINT_TO_FP_VL)
8533   NODE_NAME_CASE(UINT_TO_FP_VL)
8534   NODE_NAME_CASE(FP_EXTEND_VL)
8535   NODE_NAME_CASE(FP_ROUND_VL)
8536   NODE_NAME_CASE(VWMUL_VL)
8537   NODE_NAME_CASE(VWMULU_VL)
8538   NODE_NAME_CASE(SETCC_VL)
8539   NODE_NAME_CASE(VSELECT_VL)
8540   NODE_NAME_CASE(VMAND_VL)
8541   NODE_NAME_CASE(VMOR_VL)
8542   NODE_NAME_CASE(VMXOR_VL)
8543   NODE_NAME_CASE(VMCLR_VL)
8544   NODE_NAME_CASE(VMSET_VL)
8545   NODE_NAME_CASE(VRGATHER_VX_VL)
8546   NODE_NAME_CASE(VRGATHER_VV_VL)
8547   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
8548   NODE_NAME_CASE(VSEXT_VL)
8549   NODE_NAME_CASE(VZEXT_VL)
8550   NODE_NAME_CASE(VPOPC_VL)
8551   NODE_NAME_CASE(VLE_VL)
8552   NODE_NAME_CASE(VSE_VL)
8553   NODE_NAME_CASE(READ_CSR)
8554   NODE_NAME_CASE(WRITE_CSR)
8555   NODE_NAME_CASE(SWAP_CSR)
8556   }
8557   // clang-format on
8558   return nullptr;
8559 #undef NODE_NAME_CASE
8560 }
8561 
8562 /// getConstraintType - Given a constraint letter, return the type of
8563 /// constraint it is for this target.
8564 RISCVTargetLowering::ConstraintType
8565 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
8566   if (Constraint.size() == 1) {
8567     switch (Constraint[0]) {
8568     default:
8569       break;
8570     case 'f':
8571       return C_RegisterClass;
8572     case 'I':
8573     case 'J':
8574     case 'K':
8575       return C_Immediate;
8576     case 'A':
8577       return C_Memory;
8578     case 'S': // A symbolic address
8579       return C_Other;
8580     }
8581   } else {
8582     if (Constraint == "vr" || Constraint == "vm")
8583       return C_RegisterClass;
8584   }
8585   return TargetLowering::getConstraintType(Constraint);
8586 }
8587 
8588 std::pair<unsigned, const TargetRegisterClass *>
8589 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
8590                                                   StringRef Constraint,
8591                                                   MVT VT) const {
8592   // First, see if this is a constraint that directly corresponds to a
8593   // RISCV register class.
8594   if (Constraint.size() == 1) {
8595     switch (Constraint[0]) {
8596     case 'r':
8597       return std::make_pair(0U, &RISCV::GPRRegClass);
8598     case 'f':
8599       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
8600         return std::make_pair(0U, &RISCV::FPR16RegClass);
8601       if (Subtarget.hasStdExtF() && VT == MVT::f32)
8602         return std::make_pair(0U, &RISCV::FPR32RegClass);
8603       if (Subtarget.hasStdExtD() && VT == MVT::f64)
8604         return std::make_pair(0U, &RISCV::FPR64RegClass);
8605       break;
8606     default:
8607       break;
8608     }
8609   } else {
8610     if (Constraint == "vr") {
8611       for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
8612                              &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
8613         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
8614           return std::make_pair(0U, RC);
8615       }
8616     } else if (Constraint == "vm") {
8617       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
8618         return std::make_pair(0U, &RISCV::VMRegClass);
8619     }
8620   }
8621 
8622   // Clang will correctly decode the usage of register name aliases into their
8623   // official names. However, other frontends like `rustc` do not. This allows
8624   // users of these frontends to use the ABI names for registers in LLVM-style
8625   // register constraints.
8626   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
8627                                .Case("{zero}", RISCV::X0)
8628                                .Case("{ra}", RISCV::X1)
8629                                .Case("{sp}", RISCV::X2)
8630                                .Case("{gp}", RISCV::X3)
8631                                .Case("{tp}", RISCV::X4)
8632                                .Case("{t0}", RISCV::X5)
8633                                .Case("{t1}", RISCV::X6)
8634                                .Case("{t2}", RISCV::X7)
8635                                .Cases("{s0}", "{fp}", RISCV::X8)
8636                                .Case("{s1}", RISCV::X9)
8637                                .Case("{a0}", RISCV::X10)
8638                                .Case("{a1}", RISCV::X11)
8639                                .Case("{a2}", RISCV::X12)
8640                                .Case("{a3}", RISCV::X13)
8641                                .Case("{a4}", RISCV::X14)
8642                                .Case("{a5}", RISCV::X15)
8643                                .Case("{a6}", RISCV::X16)
8644                                .Case("{a7}", RISCV::X17)
8645                                .Case("{s2}", RISCV::X18)
8646                                .Case("{s3}", RISCV::X19)
8647                                .Case("{s4}", RISCV::X20)
8648                                .Case("{s5}", RISCV::X21)
8649                                .Case("{s6}", RISCV::X22)
8650                                .Case("{s7}", RISCV::X23)
8651                                .Case("{s8}", RISCV::X24)
8652                                .Case("{s9}", RISCV::X25)
8653                                .Case("{s10}", RISCV::X26)
8654                                .Case("{s11}", RISCV::X27)
8655                                .Case("{t3}", RISCV::X28)
8656                                .Case("{t4}", RISCV::X29)
8657                                .Case("{t5}", RISCV::X30)
8658                                .Case("{t6}", RISCV::X31)
8659                                .Default(RISCV::NoRegister);
8660   if (XRegFromAlias != RISCV::NoRegister)
8661     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
8662 
8663   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
8664   // TableGen record rather than the AsmName to choose registers for InlineAsm
8665   // constraints, plus we want to match those names to the widest floating point
8666   // register type available, manually select floating point registers here.
8667   //
8668   // The second case is the ABI name of the register, so that frontends can also
8669   // use the ABI names in register constraint lists.
8670   if (Subtarget.hasStdExtF()) {
8671     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
8672                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
8673                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
8674                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
8675                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
8676                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
8677                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
8678                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
8679                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
8680                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
8681                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
8682                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
8683                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
8684                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
8685                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
8686                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
8687                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
8688                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
8689                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
8690                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
8691                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
8692                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
8693                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
8694                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
8695                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
8696                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
8697                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
8698                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
8699                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
8700                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
8701                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
8702                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
8703                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
8704                         .Default(RISCV::NoRegister);
8705     if (FReg != RISCV::NoRegister) {
8706       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
8707       if (Subtarget.hasStdExtD()) {
8708         unsigned RegNo = FReg - RISCV::F0_F;
8709         unsigned DReg = RISCV::F0_D + RegNo;
8710         return std::make_pair(DReg, &RISCV::FPR64RegClass);
8711       }
8712       return std::make_pair(FReg, &RISCV::FPR32RegClass);
8713     }
8714   }
8715 
8716   if (Subtarget.hasStdExtV()) {
8717     Register VReg = StringSwitch<Register>(Constraint.lower())
8718                         .Case("{v0}", RISCV::V0)
8719                         .Case("{v1}", RISCV::V1)
8720                         .Case("{v2}", RISCV::V2)
8721                         .Case("{v3}", RISCV::V3)
8722                         .Case("{v4}", RISCV::V4)
8723                         .Case("{v5}", RISCV::V5)
8724                         .Case("{v6}", RISCV::V6)
8725                         .Case("{v7}", RISCV::V7)
8726                         .Case("{v8}", RISCV::V8)
8727                         .Case("{v9}", RISCV::V9)
8728                         .Case("{v10}", RISCV::V10)
8729                         .Case("{v11}", RISCV::V11)
8730                         .Case("{v12}", RISCV::V12)
8731                         .Case("{v13}", RISCV::V13)
8732                         .Case("{v14}", RISCV::V14)
8733                         .Case("{v15}", RISCV::V15)
8734                         .Case("{v16}", RISCV::V16)
8735                         .Case("{v17}", RISCV::V17)
8736                         .Case("{v18}", RISCV::V18)
8737                         .Case("{v19}", RISCV::V19)
8738                         .Case("{v20}", RISCV::V20)
8739                         .Case("{v21}", RISCV::V21)
8740                         .Case("{v22}", RISCV::V22)
8741                         .Case("{v23}", RISCV::V23)
8742                         .Case("{v24}", RISCV::V24)
8743                         .Case("{v25}", RISCV::V25)
8744                         .Case("{v26}", RISCV::V26)
8745                         .Case("{v27}", RISCV::V27)
8746                         .Case("{v28}", RISCV::V28)
8747                         .Case("{v29}", RISCV::V29)
8748                         .Case("{v30}", RISCV::V30)
8749                         .Case("{v31}", RISCV::V31)
8750                         .Default(RISCV::NoRegister);
8751     if (VReg != RISCV::NoRegister) {
8752       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
8753         return std::make_pair(VReg, &RISCV::VMRegClass);
8754       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
8755         return std::make_pair(VReg, &RISCV::VRRegClass);
8756       for (const auto *RC :
8757            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
8758         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
8759           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
8760           return std::make_pair(VReg, RC);
8761         }
8762       }
8763     }
8764   }
8765 
8766   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
8767 }
8768 
8769 unsigned
8770 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
8771   // Currently only support length 1 constraints.
8772   if (ConstraintCode.size() == 1) {
8773     switch (ConstraintCode[0]) {
8774     case 'A':
8775       return InlineAsm::Constraint_A;
8776     default:
8777       break;
8778     }
8779   }
8780 
8781   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
8782 }
8783 
8784 void RISCVTargetLowering::LowerAsmOperandForConstraint(
8785     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
8786     SelectionDAG &DAG) const {
8787   // Currently only support length 1 constraints.
8788   if (Constraint.length() == 1) {
8789     switch (Constraint[0]) {
8790     case 'I':
8791       // Validate & create a 12-bit signed immediate operand.
8792       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
8793         uint64_t CVal = C->getSExtValue();
8794         if (isInt<12>(CVal))
8795           Ops.push_back(
8796               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
8797       }
8798       return;
8799     case 'J':
8800       // Validate & create an integer zero operand.
8801       if (auto *C = dyn_cast<ConstantSDNode>(Op))
8802         if (C->getZExtValue() == 0)
8803           Ops.push_back(
8804               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
8805       return;
8806     case 'K':
8807       // Validate & create a 5-bit unsigned immediate operand.
8808       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
8809         uint64_t CVal = C->getZExtValue();
8810         if (isUInt<5>(CVal))
8811           Ops.push_back(
8812               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
8813       }
8814       return;
8815     case 'S':
8816       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
8817         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
8818                                                  GA->getValueType(0)));
8819       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
8820         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
8821                                                 BA->getValueType(0)));
8822       }
8823       return;
8824     default:
8825       break;
8826     }
8827   }
8828   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8829 }
8830 
8831 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
8832                                                    Instruction *Inst,
8833                                                    AtomicOrdering Ord) const {
8834   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
8835     return Builder.CreateFence(Ord);
8836   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
8837     return Builder.CreateFence(AtomicOrdering::Release);
8838   return nullptr;
8839 }
8840 
8841 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
8842                                                     Instruction *Inst,
8843                                                     AtomicOrdering Ord) const {
8844   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
8845     return Builder.CreateFence(AtomicOrdering::Acquire);
8846   return nullptr;
8847 }
8848 
8849 TargetLowering::AtomicExpansionKind
8850 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
8851   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
8852   // point operations can't be used in an lr/sc sequence without breaking the
8853   // forward-progress guarantee.
8854   if (AI->isFloatingPointOperation())
8855     return AtomicExpansionKind::CmpXChg;
8856 
8857   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
8858   if (Size == 8 || Size == 16)
8859     return AtomicExpansionKind::MaskedIntrinsic;
8860   return AtomicExpansionKind::None;
8861 }
8862 
8863 static Intrinsic::ID
8864 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
8865   if (XLen == 32) {
8866     switch (BinOp) {
8867     default:
8868       llvm_unreachable("Unexpected AtomicRMW BinOp");
8869     case AtomicRMWInst::Xchg:
8870       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
8871     case AtomicRMWInst::Add:
8872       return Intrinsic::riscv_masked_atomicrmw_add_i32;
8873     case AtomicRMWInst::Sub:
8874       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
8875     case AtomicRMWInst::Nand:
8876       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
8877     case AtomicRMWInst::Max:
8878       return Intrinsic::riscv_masked_atomicrmw_max_i32;
8879     case AtomicRMWInst::Min:
8880       return Intrinsic::riscv_masked_atomicrmw_min_i32;
8881     case AtomicRMWInst::UMax:
8882       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
8883     case AtomicRMWInst::UMin:
8884       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
8885     }
8886   }
8887 
8888   if (XLen == 64) {
8889     switch (BinOp) {
8890     default:
8891       llvm_unreachable("Unexpected AtomicRMW BinOp");
8892     case AtomicRMWInst::Xchg:
8893       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
8894     case AtomicRMWInst::Add:
8895       return Intrinsic::riscv_masked_atomicrmw_add_i64;
8896     case AtomicRMWInst::Sub:
8897       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
8898     case AtomicRMWInst::Nand:
8899       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
8900     case AtomicRMWInst::Max:
8901       return Intrinsic::riscv_masked_atomicrmw_max_i64;
8902     case AtomicRMWInst::Min:
8903       return Intrinsic::riscv_masked_atomicrmw_min_i64;
8904     case AtomicRMWInst::UMax:
8905       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
8906     case AtomicRMWInst::UMin:
8907       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
8908     }
8909   }
8910 
8911   llvm_unreachable("Unexpected XLen\n");
8912 }
8913 
8914 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
8915     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
8916     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
8917   unsigned XLen = Subtarget.getXLen();
8918   Value *Ordering =
8919       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
8920   Type *Tys[] = {AlignedAddr->getType()};
8921   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
8922       AI->getModule(),
8923       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
8924 
8925   if (XLen == 64) {
8926     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
8927     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
8928     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
8929   }
8930 
8931   Value *Result;
8932 
8933   // Must pass the shift amount needed to sign extend the loaded value prior
8934   // to performing a signed comparison for min/max. ShiftAmt is the number of
8935   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
8936   // is the number of bits to left+right shift the value in order to
8937   // sign-extend.
8938   if (AI->getOperation() == AtomicRMWInst::Min ||
8939       AI->getOperation() == AtomicRMWInst::Max) {
8940     const DataLayout &DL = AI->getModule()->getDataLayout();
8941     unsigned ValWidth =
8942         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
8943     Value *SextShamt =
8944         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
8945     Result = Builder.CreateCall(LrwOpScwLoop,
8946                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
8947   } else {
8948     Result =
8949         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
8950   }
8951 
8952   if (XLen == 64)
8953     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
8954   return Result;
8955 }
8956 
8957 TargetLowering::AtomicExpansionKind
8958 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
8959     AtomicCmpXchgInst *CI) const {
8960   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
8961   if (Size == 8 || Size == 16)
8962     return AtomicExpansionKind::MaskedIntrinsic;
8963   return AtomicExpansionKind::None;
8964 }
8965 
8966 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
8967     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
8968     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
8969   unsigned XLen = Subtarget.getXLen();
8970   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
8971   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
8972   if (XLen == 64) {
8973     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
8974     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
8975     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
8976     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
8977   }
8978   Type *Tys[] = {AlignedAddr->getType()};
8979   Function *MaskedCmpXchg =
8980       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
8981   Value *Result = Builder.CreateCall(
8982       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
8983   if (XLen == 64)
8984     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
8985   return Result;
8986 }
8987 
8988 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
8989   return false;
8990 }
8991 
8992 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
8993                                                      EVT VT) const {
8994   VT = VT.getScalarType();
8995 
8996   if (!VT.isSimple())
8997     return false;
8998 
8999   switch (VT.getSimpleVT().SimpleTy) {
9000   case MVT::f16:
9001     return Subtarget.hasStdExtZfh();
9002   case MVT::f32:
9003     return Subtarget.hasStdExtF();
9004   case MVT::f64:
9005     return Subtarget.hasStdExtD();
9006   default:
9007     break;
9008   }
9009 
9010   return false;
9011 }
9012 
9013 Register RISCVTargetLowering::getExceptionPointerRegister(
9014     const Constant *PersonalityFn) const {
9015   return RISCV::X10;
9016 }
9017 
9018 Register RISCVTargetLowering::getExceptionSelectorRegister(
9019     const Constant *PersonalityFn) const {
9020   return RISCV::X11;
9021 }
9022 
9023 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
9024   // Return false to suppress the unnecessary extensions if the LibCall
9025   // arguments or return value is f32 type for LP64 ABI.
9026   RISCVABI::ABI ABI = Subtarget.getTargetABI();
9027   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
9028     return false;
9029 
9030   return true;
9031 }
9032 
9033 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
9034   if (Subtarget.is64Bit() && Type == MVT::i32)
9035     return true;
9036 
9037   return IsSigned;
9038 }
9039 
9040 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
9041                                                  SDValue C) const {
9042   // Check integral scalar types.
9043   if (VT.isScalarInteger()) {
9044     // Omit the optimization if the sub target has the M extension and the data
9045     // size exceeds XLen.
9046     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
9047       return false;
9048     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
9049       // Break the MUL to a SLLI and an ADD/SUB.
9050       const APInt &Imm = ConstNode->getAPIntValue();
9051       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
9052           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
9053         return true;
9054       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
9055       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
9056           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
9057            (Imm - 8).isPowerOf2()))
9058         return true;
9059       // Omit the following optimization if the sub target has the M extension
9060       // and the data size >= XLen.
9061       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
9062         return false;
9063       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
9064       // a pair of LUI/ADDI.
9065       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
9066         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
9067         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
9068             (1 - ImmS).isPowerOf2())
9069         return true;
9070       }
9071     }
9072   }
9073 
9074   return false;
9075 }
9076 
9077 bool RISCVTargetLowering::isMulAddWithConstProfitable(
9078     const SDValue &AddNode, const SDValue &ConstNode) const {
9079   // Let the DAGCombiner decide for vectors.
9080   EVT VT = AddNode.getValueType();
9081   if (VT.isVector())
9082     return true;
9083 
9084   // Let the DAGCombiner decide for larger types.
9085   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
9086     return true;
9087 
9088   // It is worse if c1 is simm12 while c1*c2 is not.
9089   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
9090   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
9091   const APInt &C1 = C1Node->getAPIntValue();
9092   const APInt &C2 = C2Node->getAPIntValue();
9093   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
9094     return false;
9095 
9096   // Default to true and let the DAGCombiner decide.
9097   return true;
9098 }
9099 
9100 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
9101     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
9102     bool *Fast) const {
9103   if (!VT.isVector())
9104     return false;
9105 
9106   EVT ElemVT = VT.getVectorElementType();
9107   if (Alignment >= ElemVT.getStoreSize()) {
9108     if (Fast)
9109       *Fast = true;
9110     return true;
9111   }
9112 
9113   return false;
9114 }
9115 
9116 bool RISCVTargetLowering::splitValueIntoRegisterParts(
9117     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
9118     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
9119   bool IsABIRegCopy = CC.hasValue();
9120   EVT ValueVT = Val.getValueType();
9121   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9122     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
9123     // and cast to f32.
9124     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
9125     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
9126     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
9127                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
9128     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
9129     Parts[0] = Val;
9130     return true;
9131   }
9132 
9133   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9134     LLVMContext &Context = *DAG.getContext();
9135     EVT ValueEltVT = ValueVT.getVectorElementType();
9136     EVT PartEltVT = PartVT.getVectorElementType();
9137     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9138     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9139     if (PartVTBitSize % ValueVTBitSize == 0) {
9140       // If the element types are different, bitcast to the same element type of
9141       // PartVT first.
9142       if (ValueEltVT != PartEltVT) {
9143         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9144         assert(Count != 0 && "The number of element should not be zero.");
9145         EVT SameEltTypeVT =
9146             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9147         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
9148       }
9149       Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
9150                         Val, DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9151       Parts[0] = Val;
9152       return true;
9153     }
9154   }
9155   return false;
9156 }
9157 
9158 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
9159     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
9160     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
9161   bool IsABIRegCopy = CC.hasValue();
9162   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9163     SDValue Val = Parts[0];
9164 
9165     // Cast the f32 to i32, truncate to i16, and cast back to f16.
9166     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
9167     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
9168     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
9169     return Val;
9170   }
9171 
9172   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9173     LLVMContext &Context = *DAG.getContext();
9174     SDValue Val = Parts[0];
9175     EVT ValueEltVT = ValueVT.getVectorElementType();
9176     EVT PartEltVT = PartVT.getVectorElementType();
9177     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9178     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9179     if (PartVTBitSize % ValueVTBitSize == 0) {
9180       EVT SameEltTypeVT = ValueVT;
9181       // If the element types are different, convert it to the same element type
9182       // of PartVT.
9183       if (ValueEltVT != PartEltVT) {
9184         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9185         assert(Count != 0 && "The number of element should not be zero.");
9186         SameEltTypeVT =
9187             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9188       }
9189       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val,
9190                         DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9191       if (ValueEltVT != PartEltVT)
9192         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
9193       return Val;
9194     }
9195   }
9196   return SDValue();
9197 }
9198 
9199 #define GET_REGISTER_MATCHER
9200 #include "RISCVGenAsmMatcher.inc"
9201 
9202 Register
9203 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
9204                                        const MachineFunction &MF) const {
9205   Register Reg = MatchRegisterAltName(RegName);
9206   if (Reg == RISCV::NoRegister)
9207     Reg = MatchRegisterName(RegName);
9208   if (Reg == RISCV::NoRegister)
9209     report_fatal_error(
9210         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
9211   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
9212   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
9213     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
9214                              StringRef(RegName) + "\"."));
9215   return Reg;
9216 }
9217 
9218 namespace llvm {
9219 namespace RISCVVIntrinsicsTable {
9220 
9221 #define GET_RISCVVIntrinsicsTable_IMPL
9222 #include "RISCVGenSearchableTables.inc"
9223 
9224 } // namespace RISCVVIntrinsicsTable
9225 
9226 } // namespace llvm
9227