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