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 = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
4905       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, Op0);
4906       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
4907       return;
4908     }
4909     // If the FP type needs to be softened, emit a library call using the 'si'
4910     // version. If we left it to default legalization we'd end up with 'di'. If
4911     // the FP type doesn't need to be softened just let generic type
4912     // legalization promote the result type.
4913     RTLIB::Libcall LC;
4914     if (IsSigned)
4915       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
4916     else
4917       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
4918     MakeLibCallOptions CallOptions;
4919     EVT OpVT = Op0.getValueType();
4920     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
4921     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
4922     SDValue Result;
4923     std::tie(Result, Chain) =
4924         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
4925     Results.push_back(Result);
4926     if (IsStrict)
4927       Results.push_back(Chain);
4928     break;
4929   }
4930   case ISD::READCYCLECOUNTER: {
4931     assert(!Subtarget.is64Bit() &&
4932            "READCYCLECOUNTER only has custom type legalization on riscv32");
4933 
4934     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
4935     SDValue RCW =
4936         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
4937 
4938     Results.push_back(
4939         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
4940     Results.push_back(RCW.getValue(2));
4941     break;
4942   }
4943   case ISD::MUL: {
4944     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
4945     unsigned XLen = Subtarget.getXLen();
4946     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
4947     if (Size > XLen) {
4948       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
4949       SDValue LHS = N->getOperand(0);
4950       SDValue RHS = N->getOperand(1);
4951       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
4952 
4953       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
4954       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
4955       // We need exactly one side to be unsigned.
4956       if (LHSIsU == RHSIsU)
4957         return;
4958 
4959       auto MakeMULPair = [&](SDValue S, SDValue U) {
4960         MVT XLenVT = Subtarget.getXLenVT();
4961         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
4962         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
4963         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
4964         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
4965         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
4966       };
4967 
4968       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
4969       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
4970 
4971       // The other operand should be signed, but still prefer MULH when
4972       // possible.
4973       if (RHSIsU && LHSIsS && !RHSIsS)
4974         Results.push_back(MakeMULPair(LHS, RHS));
4975       else if (LHSIsU && RHSIsS && !LHSIsS)
4976         Results.push_back(MakeMULPair(RHS, LHS));
4977 
4978       return;
4979     }
4980     LLVM_FALLTHROUGH;
4981   }
4982   case ISD::ADD:
4983   case ISD::SUB:
4984     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
4985            "Unexpected custom legalisation");
4986     if (N->getOperand(1).getOpcode() == ISD::Constant)
4987       return;
4988     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
4989     break;
4990   case ISD::SHL:
4991   case ISD::SRA:
4992   case ISD::SRL:
4993     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
4994            "Unexpected custom legalisation");
4995     if (N->getOperand(1).getOpcode() == ISD::Constant)
4996       return;
4997     Results.push_back(customLegalizeToWOp(N, DAG));
4998     break;
4999   case ISD::ROTL:
5000   case ISD::ROTR:
5001     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5002            "Unexpected custom legalisation");
5003     Results.push_back(customLegalizeToWOp(N, DAG));
5004     break;
5005   case ISD::CTTZ:
5006   case ISD::CTTZ_ZERO_UNDEF:
5007   case ISD::CTLZ:
5008   case ISD::CTLZ_ZERO_UNDEF: {
5009     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5010            "Unexpected custom legalisation");
5011 
5012     SDValue NewOp0 =
5013         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5014     bool IsCTZ =
5015         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
5016     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
5017     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
5018     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5019     return;
5020   }
5021   case ISD::SDIV:
5022   case ISD::UDIV:
5023   case ISD::UREM: {
5024     MVT VT = N->getSimpleValueType(0);
5025     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
5026            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
5027            "Unexpected custom legalisation");
5028     // Don't promote division/remainder by constant since we should expand those
5029     // to multiply by magic constant.
5030     // FIXME: What if the expansion is disabled for minsize.
5031     if (N->getOperand(1).getOpcode() == ISD::Constant)
5032       return;
5033 
5034     // If the input is i32, use ANY_EXTEND since the W instructions don't read
5035     // the upper 32 bits. For other types we need to sign or zero extend
5036     // based on the opcode.
5037     unsigned ExtOpc = ISD::ANY_EXTEND;
5038     if (VT != MVT::i32)
5039       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
5040                                            : ISD::ZERO_EXTEND;
5041 
5042     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
5043     break;
5044   }
5045   case ISD::UADDO:
5046   case ISD::USUBO: {
5047     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5048            "Unexpected custom legalisation");
5049     bool IsAdd = N->getOpcode() == ISD::UADDO;
5050     // Create an ADDW or SUBW.
5051     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5052     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5053     SDValue Res =
5054         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
5055     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
5056                       DAG.getValueType(MVT::i32));
5057 
5058     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
5059     // Since the inputs are sign extended from i32, this is equivalent to
5060     // comparing the lower 32 bits.
5061     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5062     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
5063                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
5064 
5065     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5066     Results.push_back(Overflow);
5067     return;
5068   }
5069   case ISD::UADDSAT:
5070   case ISD::USUBSAT: {
5071     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5072            "Unexpected custom legalisation");
5073     if (Subtarget.hasStdExtZbb()) {
5074       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
5075       // sign extend allows overflow of the lower 32 bits to be detected on
5076       // the promoted size.
5077       SDValue LHS =
5078           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
5079       SDValue RHS =
5080           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
5081       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
5082       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5083       return;
5084     }
5085 
5086     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
5087     // promotion for UADDO/USUBO.
5088     Results.push_back(expandAddSubSat(N, DAG));
5089     return;
5090   }
5091   case ISD::BITCAST: {
5092     EVT VT = N->getValueType(0);
5093     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
5094     SDValue Op0 = N->getOperand(0);
5095     EVT Op0VT = Op0.getValueType();
5096     MVT XLenVT = Subtarget.getXLenVT();
5097     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
5098       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
5099       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
5100     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
5101                Subtarget.hasStdExtF()) {
5102       SDValue FPConv =
5103           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
5104       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
5105     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
5106                isTypeLegal(Op0VT)) {
5107       // Custom-legalize bitcasts from fixed-length vector types to illegal
5108       // scalar types in order to improve codegen. Bitcast the vector to a
5109       // one-element vector type whose element type is the same as the result
5110       // type, and extract the first element.
5111       LLVMContext &Context = *DAG.getContext();
5112       SDValue BVec = DAG.getBitcast(EVT::getVectorVT(Context, VT, 1), Op0);
5113       Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
5114                                     DAG.getConstant(0, DL, XLenVT)));
5115     }
5116     break;
5117   }
5118   case RISCVISD::GREV:
5119   case RISCVISD::GORC: {
5120     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5121            "Unexpected custom legalisation");
5122     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5123     // This is similar to customLegalizeToWOp, except that we pass the second
5124     // operand (a TargetConstant) straight through: it is already of type
5125     // XLenVT.
5126     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
5127     SDValue NewOp0 =
5128         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5129     SDValue NewOp1 =
5130         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5131     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
5132     // ReplaceNodeResults requires we maintain the same type for the return
5133     // value.
5134     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5135     break;
5136   }
5137   case RISCVISD::SHFL: {
5138     // There is no SHFLIW instruction, but we can just promote the operation.
5139     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5140            "Unexpected custom legalisation");
5141     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
5142     SDValue NewOp0 =
5143         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5144     SDValue NewOp1 =
5145         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5146     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
5147     // ReplaceNodeResults requires we maintain the same type for the return
5148     // value.
5149     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
5150     break;
5151   }
5152   case ISD::BSWAP:
5153   case ISD::BITREVERSE: {
5154     MVT VT = N->getSimpleValueType(0);
5155     MVT XLenVT = Subtarget.getXLenVT();
5156     assert((VT == MVT::i8 || VT == MVT::i16 ||
5157             (VT == MVT::i32 && Subtarget.is64Bit())) &&
5158            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
5159     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
5160     unsigned Imm = VT.getSizeInBits() - 1;
5161     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
5162     if (N->getOpcode() == ISD::BSWAP)
5163       Imm &= ~0x7U;
5164     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
5165     SDValue GREVI =
5166         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
5167     // ReplaceNodeResults requires we maintain the same type for the return
5168     // value.
5169     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
5170     break;
5171   }
5172   case ISD::FSHL:
5173   case ISD::FSHR: {
5174     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5175            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
5176     SDValue NewOp0 =
5177         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
5178     SDValue NewOp1 =
5179         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5180     SDValue NewOp2 =
5181         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5182     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
5183     // Mask the shift amount to 5 bits.
5184     NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5185                          DAG.getConstant(0x1f, DL, MVT::i64));
5186     unsigned Opc =
5187         N->getOpcode() == ISD::FSHL ? RISCVISD::FSLW : RISCVISD::FSRW;
5188     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewOp2);
5189     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
5190     break;
5191   }
5192   case ISD::EXTRACT_VECTOR_ELT: {
5193     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
5194     // type is illegal (currently only vXi64 RV32).
5195     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
5196     // transferred to the destination register. We issue two of these from the
5197     // upper- and lower- halves of the SEW-bit vector element, slid down to the
5198     // first element.
5199     SDValue Vec = N->getOperand(0);
5200     SDValue Idx = N->getOperand(1);
5201 
5202     // The vector type hasn't been legalized yet so we can't issue target
5203     // specific nodes if it needs legalization.
5204     // FIXME: We would manually legalize if it's important.
5205     if (!isTypeLegal(Vec.getValueType()))
5206       return;
5207 
5208     MVT VecVT = Vec.getSimpleValueType();
5209 
5210     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
5211            VecVT.getVectorElementType() == MVT::i64 &&
5212            "Unexpected EXTRACT_VECTOR_ELT legalization");
5213 
5214     // If this is a fixed vector, we need to convert it to a scalable vector.
5215     MVT ContainerVT = VecVT;
5216     if (VecVT.isFixedLengthVector()) {
5217       ContainerVT = getContainerForFixedLengthVector(VecVT);
5218       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5219     }
5220 
5221     MVT XLenVT = Subtarget.getXLenVT();
5222 
5223     // Use a VL of 1 to avoid processing more elements than we need.
5224     MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5225     SDValue VL = DAG.getConstant(1, DL, XLenVT);
5226     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5227 
5228     // Unless the index is known to be 0, we must slide the vector down to get
5229     // the desired element into index 0.
5230     if (!isNullConstant(Idx)) {
5231       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5232                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
5233     }
5234 
5235     // Extract the lower XLEN bits of the correct vector element.
5236     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5237 
5238     // To extract the upper XLEN bits of the vector element, shift the first
5239     // element right by 32 bits and re-extract the lower XLEN bits.
5240     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5241                                      DAG.getConstant(32, DL, XLenVT), VL);
5242     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
5243                                  ThirtyTwoV, Mask, VL);
5244 
5245     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5246 
5247     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5248     break;
5249   }
5250   case ISD::INTRINSIC_WO_CHAIN: {
5251     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5252     switch (IntNo) {
5253     default:
5254       llvm_unreachable(
5255           "Don't know how to custom type legalize this intrinsic!");
5256     case Intrinsic::riscv_orc_b: {
5257       // Lower to the GORCI encoding for orc.b with the operand extended.
5258       SDValue NewOp =
5259           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5260       // If Zbp is enabled, use GORCIW which will sign extend the result.
5261       unsigned Opc =
5262           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
5263       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
5264                                 DAG.getConstant(7, DL, MVT::i64));
5265       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5266       return;
5267     }
5268     case Intrinsic::riscv_grev:
5269     case Intrinsic::riscv_gorc: {
5270       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5271              "Unexpected custom legalisation");
5272       SDValue NewOp1 =
5273           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5274       SDValue NewOp2 =
5275           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5276       unsigned Opc =
5277           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
5278       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5279       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5280       break;
5281     }
5282     case Intrinsic::riscv_shfl:
5283     case Intrinsic::riscv_unshfl: {
5284       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5285              "Unexpected custom legalisation");
5286       SDValue NewOp1 =
5287           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5288       SDValue NewOp2 =
5289           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5290       unsigned Opc =
5291           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
5292       if (isa<ConstantSDNode>(N->getOperand(2))) {
5293         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
5294                              DAG.getConstant(0xf, DL, MVT::i64));
5295         Opc =
5296             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
5297       }
5298       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5299       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5300       break;
5301     }
5302     case Intrinsic::riscv_bcompress:
5303     case Intrinsic::riscv_bdecompress: {
5304       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
5305              "Unexpected custom legalisation");
5306       SDValue NewOp1 =
5307           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
5308       SDValue NewOp2 =
5309           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
5310       unsigned Opc = IntNo == Intrinsic::riscv_bcompress
5311                          ? RISCVISD::BCOMPRESSW
5312                          : RISCVISD::BDECOMPRESSW;
5313       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
5314       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
5315       break;
5316     }
5317     case Intrinsic::riscv_vmv_x_s: {
5318       EVT VT = N->getValueType(0);
5319       MVT XLenVT = Subtarget.getXLenVT();
5320       if (VT.bitsLT(XLenVT)) {
5321         // Simple case just extract using vmv.x.s and truncate.
5322         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
5323                                       Subtarget.getXLenVT(), N->getOperand(1));
5324         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
5325         return;
5326       }
5327 
5328       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
5329              "Unexpected custom legalization");
5330 
5331       // We need to do the move in two steps.
5332       SDValue Vec = N->getOperand(1);
5333       MVT VecVT = Vec.getSimpleValueType();
5334 
5335       // First extract the lower XLEN bits of the element.
5336       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
5337 
5338       // To extract the upper XLEN bits of the vector element, shift the first
5339       // element right by 32 bits and re-extract the lower XLEN bits.
5340       SDValue VL = DAG.getConstant(1, DL, XLenVT);
5341       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5342       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5343       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
5344                                        DAG.getConstant(32, DL, XLenVT), VL);
5345       SDValue LShr32 =
5346           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
5347       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
5348 
5349       Results.push_back(
5350           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
5351       break;
5352     }
5353     }
5354     break;
5355   }
5356   case ISD::VECREDUCE_ADD:
5357   case ISD::VECREDUCE_AND:
5358   case ISD::VECREDUCE_OR:
5359   case ISD::VECREDUCE_XOR:
5360   case ISD::VECREDUCE_SMAX:
5361   case ISD::VECREDUCE_UMAX:
5362   case ISD::VECREDUCE_SMIN:
5363   case ISD::VECREDUCE_UMIN:
5364     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
5365       Results.push_back(V);
5366     break;
5367   case ISD::FLT_ROUNDS_: {
5368     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
5369     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
5370     Results.push_back(Res.getValue(0));
5371     Results.push_back(Res.getValue(1));
5372     break;
5373   }
5374   }
5375 }
5376 
5377 // A structure to hold one of the bit-manipulation patterns below. Together, a
5378 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
5379 //   (or (and (shl x, 1), 0xAAAAAAAA),
5380 //       (and (srl x, 1), 0x55555555))
5381 struct RISCVBitmanipPat {
5382   SDValue Op;
5383   unsigned ShAmt;
5384   bool IsSHL;
5385 
5386   bool formsPairWith(const RISCVBitmanipPat &Other) const {
5387     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
5388   }
5389 };
5390 
5391 // Matches patterns of the form
5392 //   (and (shl x, C2), (C1 << C2))
5393 //   (and (srl x, C2), C1)
5394 //   (shl (and x, C1), C2)
5395 //   (srl (and x, (C1 << C2)), C2)
5396 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
5397 // The expected masks for each shift amount are specified in BitmanipMasks where
5398 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
5399 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
5400 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
5401 // XLen is 64.
5402 static Optional<RISCVBitmanipPat>
5403 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
5404   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
5405          "Unexpected number of masks");
5406   Optional<uint64_t> Mask;
5407   // Optionally consume a mask around the shift operation.
5408   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
5409     Mask = Op.getConstantOperandVal(1);
5410     Op = Op.getOperand(0);
5411   }
5412   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
5413     return None;
5414   bool IsSHL = Op.getOpcode() == ISD::SHL;
5415 
5416   if (!isa<ConstantSDNode>(Op.getOperand(1)))
5417     return None;
5418   uint64_t ShAmt = Op.getConstantOperandVal(1);
5419 
5420   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
5421   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
5422     return None;
5423   // If we don't have enough masks for 64 bit, then we must be trying to
5424   // match SHFL so we're only allowed to shift 1/4 of the width.
5425   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
5426     return None;
5427 
5428   SDValue Src = Op.getOperand(0);
5429 
5430   // The expected mask is shifted left when the AND is found around SHL
5431   // patterns.
5432   //   ((x >> 1) & 0x55555555)
5433   //   ((x << 1) & 0xAAAAAAAA)
5434   bool SHLExpMask = IsSHL;
5435 
5436   if (!Mask) {
5437     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
5438     // the mask is all ones: consume that now.
5439     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
5440       Mask = Src.getConstantOperandVal(1);
5441       Src = Src.getOperand(0);
5442       // The expected mask is now in fact shifted left for SRL, so reverse the
5443       // decision.
5444       //   ((x & 0xAAAAAAAA) >> 1)
5445       //   ((x & 0x55555555) << 1)
5446       SHLExpMask = !SHLExpMask;
5447     } else {
5448       // Use a default shifted mask of all-ones if there's no AND, truncated
5449       // down to the expected width. This simplifies the logic later on.
5450       Mask = maskTrailingOnes<uint64_t>(Width);
5451       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
5452     }
5453   }
5454 
5455   unsigned MaskIdx = Log2_32(ShAmt);
5456   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
5457 
5458   if (SHLExpMask)
5459     ExpMask <<= ShAmt;
5460 
5461   if (Mask != ExpMask)
5462     return None;
5463 
5464   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
5465 }
5466 
5467 // Matches any of the following bit-manipulation patterns:
5468 //   (and (shl x, 1), (0x55555555 << 1))
5469 //   (and (srl x, 1), 0x55555555)
5470 //   (shl (and x, 0x55555555), 1)
5471 //   (srl (and x, (0x55555555 << 1)), 1)
5472 // where the shift amount and mask may vary thus:
5473 //   [1]  = 0x55555555 / 0xAAAAAAAA
5474 //   [2]  = 0x33333333 / 0xCCCCCCCC
5475 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
5476 //   [8]  = 0x00FF00FF / 0xFF00FF00
5477 //   [16] = 0x0000FFFF / 0xFFFFFFFF
5478 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
5479 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
5480   // These are the unshifted masks which we use to match bit-manipulation
5481   // patterns. They may be shifted left in certain circumstances.
5482   static const uint64_t BitmanipMasks[] = {
5483       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
5484       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
5485 
5486   return matchRISCVBitmanipPat(Op, BitmanipMasks);
5487 }
5488 
5489 // Match the following pattern as a GREVI(W) operation
5490 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
5491 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
5492                                const RISCVSubtarget &Subtarget) {
5493   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
5494   EVT VT = Op.getValueType();
5495 
5496   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
5497     auto LHS = matchGREVIPat(Op.getOperand(0));
5498     auto RHS = matchGREVIPat(Op.getOperand(1));
5499     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
5500       SDLoc DL(Op);
5501       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
5502                          DAG.getConstant(LHS->ShAmt, DL, VT));
5503     }
5504   }
5505   return SDValue();
5506 }
5507 
5508 // Matches any the following pattern as a GORCI(W) operation
5509 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
5510 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
5511 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
5512 // Note that with the variant of 3.,
5513 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
5514 // the inner pattern will first be matched as GREVI and then the outer
5515 // pattern will be matched to GORC via the first rule above.
5516 // 4.  (or (rotl/rotr x, bitwidth/2), x)
5517 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
5518                                const RISCVSubtarget &Subtarget) {
5519   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
5520   EVT VT = Op.getValueType();
5521 
5522   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
5523     SDLoc DL(Op);
5524     SDValue Op0 = Op.getOperand(0);
5525     SDValue Op1 = Op.getOperand(1);
5526 
5527     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
5528       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
5529           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
5530           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
5531         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
5532       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
5533       if ((Reverse.getOpcode() == ISD::ROTL ||
5534            Reverse.getOpcode() == ISD::ROTR) &&
5535           Reverse.getOperand(0) == X &&
5536           isa<ConstantSDNode>(Reverse.getOperand(1))) {
5537         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
5538         if (RotAmt == (VT.getSizeInBits() / 2))
5539           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
5540                              DAG.getConstant(RotAmt, DL, VT));
5541       }
5542       return SDValue();
5543     };
5544 
5545     // Check for either commutable permutation of (or (GREVI x, shamt), x)
5546     if (SDValue V = MatchOROfReverse(Op0, Op1))
5547       return V;
5548     if (SDValue V = MatchOROfReverse(Op1, Op0))
5549       return V;
5550 
5551     // OR is commutable so canonicalize its OR operand to the left
5552     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
5553       std::swap(Op0, Op1);
5554     if (Op0.getOpcode() != ISD::OR)
5555       return SDValue();
5556     SDValue OrOp0 = Op0.getOperand(0);
5557     SDValue OrOp1 = Op0.getOperand(1);
5558     auto LHS = matchGREVIPat(OrOp0);
5559     // OR is commutable so swap the operands and try again: x might have been
5560     // on the left
5561     if (!LHS) {
5562       std::swap(OrOp0, OrOp1);
5563       LHS = matchGREVIPat(OrOp0);
5564     }
5565     auto RHS = matchGREVIPat(Op1);
5566     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
5567       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
5568                          DAG.getConstant(LHS->ShAmt, DL, VT));
5569     }
5570   }
5571   return SDValue();
5572 }
5573 
5574 // Matches any of the following bit-manipulation patterns:
5575 //   (and (shl x, 1), (0x22222222 << 1))
5576 //   (and (srl x, 1), 0x22222222)
5577 //   (shl (and x, 0x22222222), 1)
5578 //   (srl (and x, (0x22222222 << 1)), 1)
5579 // where the shift amount and mask may vary thus:
5580 //   [1]  = 0x22222222 / 0x44444444
5581 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
5582 //   [4]  = 0x00F000F0 / 0x0F000F00
5583 //   [8]  = 0x0000FF00 / 0x00FF0000
5584 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
5585 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
5586   // These are the unshifted masks which we use to match bit-manipulation
5587   // patterns. They may be shifted left in certain circumstances.
5588   static const uint64_t BitmanipMasks[] = {
5589       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
5590       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
5591 
5592   return matchRISCVBitmanipPat(Op, BitmanipMasks);
5593 }
5594 
5595 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
5596 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
5597                                const RISCVSubtarget &Subtarget) {
5598   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
5599   EVT VT = Op.getValueType();
5600 
5601   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
5602     return SDValue();
5603 
5604   SDValue Op0 = Op.getOperand(0);
5605   SDValue Op1 = Op.getOperand(1);
5606 
5607   // Or is commutable so canonicalize the second OR to the LHS.
5608   if (Op0.getOpcode() != ISD::OR)
5609     std::swap(Op0, Op1);
5610   if (Op0.getOpcode() != ISD::OR)
5611     return SDValue();
5612 
5613   // We found an inner OR, so our operands are the operands of the inner OR
5614   // and the other operand of the outer OR.
5615   SDValue A = Op0.getOperand(0);
5616   SDValue B = Op0.getOperand(1);
5617   SDValue C = Op1;
5618 
5619   auto Match1 = matchSHFLPat(A);
5620   auto Match2 = matchSHFLPat(B);
5621 
5622   // If neither matched, we failed.
5623   if (!Match1 && !Match2)
5624     return SDValue();
5625 
5626   // We had at least one match. if one failed, try the remaining C operand.
5627   if (!Match1) {
5628     std::swap(A, C);
5629     Match1 = matchSHFLPat(A);
5630     if (!Match1)
5631       return SDValue();
5632   } else if (!Match2) {
5633     std::swap(B, C);
5634     Match2 = matchSHFLPat(B);
5635     if (!Match2)
5636       return SDValue();
5637   }
5638   assert(Match1 && Match2);
5639 
5640   // Make sure our matches pair up.
5641   if (!Match1->formsPairWith(*Match2))
5642     return SDValue();
5643 
5644   // All the remains is to make sure C is an AND with the same input, that masks
5645   // out the bits that are being shuffled.
5646   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
5647       C.getOperand(0) != Match1->Op)
5648     return SDValue();
5649 
5650   uint64_t Mask = C.getConstantOperandVal(1);
5651 
5652   static const uint64_t BitmanipMasks[] = {
5653       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
5654       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
5655   };
5656 
5657   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
5658   unsigned MaskIdx = Log2_32(Match1->ShAmt);
5659   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
5660 
5661   if (Mask != ExpMask)
5662     return SDValue();
5663 
5664   SDLoc DL(Op);
5665   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
5666                      DAG.getConstant(Match1->ShAmt, DL, VT));
5667 }
5668 
5669 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
5670 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
5671 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
5672 // not undo itself, but they are redundant.
5673 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
5674   SDValue Src = N->getOperand(0);
5675 
5676   if (Src.getOpcode() != N->getOpcode())
5677     return SDValue();
5678 
5679   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
5680       !isa<ConstantSDNode>(Src.getOperand(1)))
5681     return SDValue();
5682 
5683   unsigned ShAmt1 = N->getConstantOperandVal(1);
5684   unsigned ShAmt2 = Src.getConstantOperandVal(1);
5685   Src = Src.getOperand(0);
5686 
5687   unsigned CombinedShAmt;
5688   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
5689     CombinedShAmt = ShAmt1 | ShAmt2;
5690   else
5691     CombinedShAmt = ShAmt1 ^ ShAmt2;
5692 
5693   if (CombinedShAmt == 0)
5694     return Src;
5695 
5696   SDLoc DL(N);
5697   return DAG.getNode(
5698       N->getOpcode(), DL, N->getValueType(0), Src,
5699       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
5700 }
5701 
5702 // Combine a constant select operand into its use:
5703 //
5704 // (and (select_cc lhs, rhs, cc, -1, c), x)
5705 //   -> (select_cc lhs, rhs, cc, x, (and, x, c))  [AllOnes=1]
5706 // (or  (select_cc lhs, rhs, cc, 0, c), x)
5707 //   -> (select_cc lhs, rhs, cc, x, (or, x, c))  [AllOnes=0]
5708 // (xor (select_cc lhs, rhs, cc, 0, c), x)
5709 //   -> (select_cc lhs, rhs, cc, x, (xor, x, c))  [AllOnes=0]
5710 static SDValue combineSelectCCAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
5711                                      SelectionDAG &DAG, bool AllOnes) {
5712   EVT VT = N->getValueType(0);
5713 
5714   if (Slct.getOpcode() != RISCVISD::SELECT_CC || !Slct.hasOneUse())
5715     return SDValue();
5716 
5717   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
5718     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
5719   };
5720 
5721   bool SwapSelectOps;
5722   SDValue TrueVal = Slct.getOperand(3);
5723   SDValue FalseVal = Slct.getOperand(4);
5724   SDValue NonConstantVal;
5725   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
5726     SwapSelectOps = false;
5727     NonConstantVal = FalseVal;
5728   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
5729     SwapSelectOps = true;
5730     NonConstantVal = TrueVal;
5731   } else
5732     return SDValue();
5733 
5734   // Slct is now know to be the desired identity constant when CC is true.
5735   TrueVal = OtherOp;
5736   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
5737   // Unless SwapSelectOps says CC should be false.
5738   if (SwapSelectOps)
5739     std::swap(TrueVal, FalseVal);
5740 
5741   return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
5742                      {Slct.getOperand(0), Slct.getOperand(1),
5743                       Slct.getOperand(2), TrueVal, FalseVal});
5744 }
5745 
5746 // Attempt combineSelectAndUse on each operand of a commutative operator N.
5747 static SDValue combineSelectCCAndUseCommutative(SDNode *N, SelectionDAG &DAG,
5748                                                 bool AllOnes) {
5749   SDValue N0 = N->getOperand(0);
5750   SDValue N1 = N->getOperand(1);
5751   if (SDValue Result = combineSelectCCAndUse(N, N0, N1, DAG, AllOnes))
5752     return Result;
5753   if (SDValue Result = combineSelectCCAndUse(N, N1, N0, DAG, AllOnes))
5754     return Result;
5755   return SDValue();
5756 }
5757 
5758 static SDValue performANDCombine(SDNode *N,
5759                                  TargetLowering::DAGCombinerInfo &DCI,
5760                                  const RISCVSubtarget &Subtarget) {
5761   SelectionDAG &DAG = DCI.DAG;
5762 
5763   // fold (and (select_cc lhs, rhs, cc, -1, y), x) ->
5764   //      (select lhs, rhs, cc, x, (and x, y))
5765   return combineSelectCCAndUseCommutative(N, DAG, true);
5766 }
5767 
5768 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
5769                                 const RISCVSubtarget &Subtarget) {
5770   SelectionDAG &DAG = DCI.DAG;
5771   if (Subtarget.hasStdExtZbp()) {
5772     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
5773       return GREV;
5774     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
5775       return GORC;
5776     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
5777       return SHFL;
5778   }
5779 
5780   // fold (or (select_cc lhs, rhs, cc, 0, y), x) ->
5781   //      (select lhs, rhs, cc, x, (or x, y))
5782   return combineSelectCCAndUseCommutative(N, DAG, false);
5783 }
5784 
5785 static SDValue performXORCombine(SDNode *N,
5786                                  TargetLowering::DAGCombinerInfo &DCI,
5787                                  const RISCVSubtarget &Subtarget) {
5788   SelectionDAG &DAG = DCI.DAG;
5789 
5790   // fold (xor (select_cc lhs, rhs, cc, 0, y), x) ->
5791   //      (select lhs, rhs, cc, x, (xor x, y))
5792   return combineSelectCCAndUseCommutative(N, DAG, false);
5793 }
5794 
5795 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
5796 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
5797 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
5798 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
5799 // ADDW/SUBW/MULW.
5800 static SDValue performANY_EXTENDCombine(SDNode *N,
5801                                         TargetLowering::DAGCombinerInfo &DCI,
5802                                         const RISCVSubtarget &Subtarget) {
5803   if (!Subtarget.is64Bit())
5804     return SDValue();
5805 
5806   SelectionDAG &DAG = DCI.DAG;
5807 
5808   SDValue Src = N->getOperand(0);
5809   EVT VT = N->getValueType(0);
5810   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
5811     return SDValue();
5812 
5813   // The opcode must be one that can implicitly sign_extend.
5814   // FIXME: Additional opcodes.
5815   switch (Src.getOpcode()) {
5816   default:
5817     return SDValue();
5818   case ISD::MUL:
5819     if (!Subtarget.hasStdExtM())
5820       return SDValue();
5821     LLVM_FALLTHROUGH;
5822   case ISD::ADD:
5823   case ISD::SUB:
5824     break;
5825   }
5826 
5827   // Only handle cases where the result is used by a CopyToReg. That likely
5828   // means the value is a liveout of the basic block. This helps prevent
5829   // infinite combine loops like PR51206.
5830   if (none_of(N->uses(),
5831               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
5832     return SDValue();
5833 
5834   SmallVector<SDNode *, 4> SetCCs;
5835   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
5836                             UE = Src.getNode()->use_end();
5837        UI != UE; ++UI) {
5838     SDNode *User = *UI;
5839     if (User == N)
5840       continue;
5841     if (UI.getUse().getResNo() != Src.getResNo())
5842       continue;
5843     // All i32 setccs are legalized by sign extending operands.
5844     if (User->getOpcode() == ISD::SETCC) {
5845       SetCCs.push_back(User);
5846       continue;
5847     }
5848     // We don't know if we can extend this user.
5849     break;
5850   }
5851 
5852   // If we don't have any SetCCs, this isn't worthwhile.
5853   if (SetCCs.empty())
5854     return SDValue();
5855 
5856   SDLoc DL(N);
5857   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
5858   DCI.CombineTo(N, SExt);
5859 
5860   // Promote all the setccs.
5861   for (SDNode *SetCC : SetCCs) {
5862     SmallVector<SDValue, 4> Ops;
5863 
5864     for (unsigned j = 0; j != 2; ++j) {
5865       SDValue SOp = SetCC->getOperand(j);
5866       if (SOp == Src)
5867         Ops.push_back(SExt);
5868       else
5869         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
5870     }
5871 
5872     Ops.push_back(SetCC->getOperand(2));
5873     DCI.CombineTo(SetCC,
5874                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5875   }
5876   return SDValue(N, 0);
5877 }
5878 
5879 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
5880                                                DAGCombinerInfo &DCI) const {
5881   SelectionDAG &DAG = DCI.DAG;
5882 
5883   switch (N->getOpcode()) {
5884   default:
5885     break;
5886   case RISCVISD::SplitF64: {
5887     SDValue Op0 = N->getOperand(0);
5888     // If the input to SplitF64 is just BuildPairF64 then the operation is
5889     // redundant. Instead, use BuildPairF64's operands directly.
5890     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
5891       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
5892 
5893     SDLoc DL(N);
5894 
5895     // It's cheaper to materialise two 32-bit integers than to load a double
5896     // from the constant pool and transfer it to integer registers through the
5897     // stack.
5898     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
5899       APInt V = C->getValueAPF().bitcastToAPInt();
5900       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
5901       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
5902       return DCI.CombineTo(N, Lo, Hi);
5903     }
5904 
5905     // This is a target-specific version of a DAGCombine performed in
5906     // DAGCombiner::visitBITCAST. It performs the equivalent of:
5907     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5908     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5909     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
5910         !Op0.getNode()->hasOneUse())
5911       break;
5912     SDValue NewSplitF64 =
5913         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
5914                     Op0.getOperand(0));
5915     SDValue Lo = NewSplitF64.getValue(0);
5916     SDValue Hi = NewSplitF64.getValue(1);
5917     APInt SignBit = APInt::getSignMask(32);
5918     if (Op0.getOpcode() == ISD::FNEG) {
5919       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
5920                                   DAG.getConstant(SignBit, DL, MVT::i32));
5921       return DCI.CombineTo(N, Lo, NewHi);
5922     }
5923     assert(Op0.getOpcode() == ISD::FABS);
5924     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
5925                                 DAG.getConstant(~SignBit, DL, MVT::i32));
5926     return DCI.CombineTo(N, Lo, NewHi);
5927   }
5928   case RISCVISD::SLLW:
5929   case RISCVISD::SRAW:
5930   case RISCVISD::SRLW:
5931   case RISCVISD::ROLW:
5932   case RISCVISD::RORW: {
5933     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
5934     SDValue LHS = N->getOperand(0);
5935     SDValue RHS = N->getOperand(1);
5936     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
5937     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 5);
5938     if (SimplifyDemandedBits(N->getOperand(0), LHSMask, DCI) ||
5939         SimplifyDemandedBits(N->getOperand(1), RHSMask, DCI)) {
5940       if (N->getOpcode() != ISD::DELETED_NODE)
5941         DCI.AddToWorklist(N);
5942       return SDValue(N, 0);
5943     }
5944     break;
5945   }
5946   case RISCVISD::CLZW:
5947   case RISCVISD::CTZW: {
5948     // Only the lower 32 bits of the first operand are read
5949     SDValue Op0 = N->getOperand(0);
5950     APInt Mask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32);
5951     if (SimplifyDemandedBits(Op0, Mask, DCI)) {
5952       if (N->getOpcode() != ISD::DELETED_NODE)
5953         DCI.AddToWorklist(N);
5954       return SDValue(N, 0);
5955     }
5956     break;
5957   }
5958   case RISCVISD::FSL:
5959   case RISCVISD::FSR: {
5960     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
5961     SDValue ShAmt = N->getOperand(2);
5962     unsigned BitWidth = ShAmt.getValueSizeInBits();
5963     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
5964     APInt ShAmtMask(BitWidth, (BitWidth * 2) - 1);
5965     if (SimplifyDemandedBits(ShAmt, ShAmtMask, DCI)) {
5966       if (N->getOpcode() != ISD::DELETED_NODE)
5967         DCI.AddToWorklist(N);
5968       return SDValue(N, 0);
5969     }
5970     break;
5971   }
5972   case RISCVISD::FSLW:
5973   case RISCVISD::FSRW: {
5974     // Only the lower 32 bits of Values and lower 6 bits of shift amount are
5975     // read.
5976     SDValue Op0 = N->getOperand(0);
5977     SDValue Op1 = N->getOperand(1);
5978     SDValue ShAmt = N->getOperand(2);
5979     APInt OpMask = APInt::getLowBitsSet(Op0.getValueSizeInBits(), 32);
5980     APInt ShAmtMask = APInt::getLowBitsSet(ShAmt.getValueSizeInBits(), 6);
5981     if (SimplifyDemandedBits(Op0, OpMask, DCI) ||
5982         SimplifyDemandedBits(Op1, OpMask, DCI) ||
5983         SimplifyDemandedBits(ShAmt, ShAmtMask, DCI)) {
5984       if (N->getOpcode() != ISD::DELETED_NODE)
5985         DCI.AddToWorklist(N);
5986       return SDValue(N, 0);
5987     }
5988     break;
5989   }
5990   case RISCVISD::GREV:
5991   case RISCVISD::GORC: {
5992     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
5993     SDValue ShAmt = N->getOperand(1);
5994     unsigned BitWidth = ShAmt.getValueSizeInBits();
5995     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
5996     APInt ShAmtMask(BitWidth, BitWidth - 1);
5997     if (SimplifyDemandedBits(ShAmt, ShAmtMask, DCI)) {
5998       if (N->getOpcode() != ISD::DELETED_NODE)
5999         DCI.AddToWorklist(N);
6000       return SDValue(N, 0);
6001     }
6002 
6003     return combineGREVI_GORCI(N, DCI.DAG);
6004   }
6005   case RISCVISD::GREVW:
6006   case RISCVISD::GORCW: {
6007     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6008     SDValue LHS = N->getOperand(0);
6009     SDValue RHS = N->getOperand(1);
6010     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
6011     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 5);
6012     if (SimplifyDemandedBits(LHS, LHSMask, DCI) ||
6013         SimplifyDemandedBits(RHS, RHSMask, DCI)) {
6014       if (N->getOpcode() != ISD::DELETED_NODE)
6015         DCI.AddToWorklist(N);
6016       return SDValue(N, 0);
6017     }
6018 
6019     return combineGREVI_GORCI(N, DCI.DAG);
6020   }
6021   case RISCVISD::SHFL:
6022   case RISCVISD::UNSHFL: {
6023     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
6024     SDValue ShAmt = N->getOperand(1);
6025     unsigned BitWidth = ShAmt.getValueSizeInBits();
6026     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
6027     APInt ShAmtMask(BitWidth, (BitWidth / 2) - 1);
6028     if (SimplifyDemandedBits(ShAmt, ShAmtMask, DCI)) {
6029       if (N->getOpcode() != ISD::DELETED_NODE)
6030         DCI.AddToWorklist(N);
6031       return SDValue(N, 0);
6032     }
6033 
6034     break;
6035   }
6036   case RISCVISD::SHFLW:
6037   case RISCVISD::UNSHFLW: {
6038     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
6039     SDValue LHS = N->getOperand(0);
6040     SDValue RHS = N->getOperand(1);
6041     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
6042     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
6043     if (SimplifyDemandedBits(LHS, LHSMask, DCI) ||
6044         SimplifyDemandedBits(RHS, RHSMask, DCI)) {
6045       if (N->getOpcode() != ISD::DELETED_NODE)
6046         DCI.AddToWorklist(N);
6047       return SDValue(N, 0);
6048     }
6049 
6050     break;
6051   }
6052   case RISCVISD::BCOMPRESSW:
6053   case RISCVISD::BDECOMPRESSW: {
6054     // Only the lower 32 bits of LHS and RHS are read.
6055     SDValue LHS = N->getOperand(0);
6056     SDValue RHS = N->getOperand(1);
6057     APInt Mask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
6058     if (SimplifyDemandedBits(LHS, Mask, DCI) ||
6059         SimplifyDemandedBits(RHS, Mask, DCI)) {
6060       if (N->getOpcode() != ISD::DELETED_NODE)
6061         DCI.AddToWorklist(N);
6062       return SDValue(N, 0);
6063     }
6064 
6065     break;
6066   }
6067   case RISCVISD::FMV_X_ANYEXTW_RV64: {
6068     SDLoc DL(N);
6069     SDValue Op0 = N->getOperand(0);
6070     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
6071     // conversion is unnecessary and can be replaced with an ANY_EXTEND
6072     // of the FMV_W_X_RV64 operand.
6073     if (Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) {
6074       assert(Op0.getOperand(0).getValueType() == MVT::i64 &&
6075              "Unexpected value type!");
6076       return Op0.getOperand(0);
6077     }
6078 
6079     // This is a target-specific version of a DAGCombine performed in
6080     // DAGCombiner::visitBITCAST. It performs the equivalent of:
6081     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6082     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6083     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
6084         !Op0.getNode()->hasOneUse())
6085       break;
6086     SDValue NewFMV = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64,
6087                                  Op0.getOperand(0));
6088     APInt SignBit = APInt::getSignMask(32).sext(64);
6089     if (Op0.getOpcode() == ISD::FNEG)
6090       return DAG.getNode(ISD::XOR, DL, MVT::i64, NewFMV,
6091                          DAG.getConstant(SignBit, DL, MVT::i64));
6092 
6093     assert(Op0.getOpcode() == ISD::FABS);
6094     return DAG.getNode(ISD::AND, DL, MVT::i64, NewFMV,
6095                        DAG.getConstant(~SignBit, DL, MVT::i64));
6096   }
6097   case ISD::AND:
6098     return performANDCombine(N, DCI, Subtarget);
6099   case ISD::OR:
6100     return performORCombine(N, DCI, Subtarget);
6101   case ISD::XOR:
6102     return performXORCombine(N, DCI, Subtarget);
6103   case ISD::ANY_EXTEND:
6104     return performANY_EXTENDCombine(N, DCI, Subtarget);
6105   case ISD::ZERO_EXTEND:
6106     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
6107     // type legalization. This is safe because fp_to_uint produces poison if
6108     // it overflows.
6109     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit() &&
6110         N->getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
6111         isTypeLegal(N->getOperand(0).getOperand(0).getValueType()))
6112       return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
6113                          N->getOperand(0).getOperand(0));
6114     return SDValue();
6115   case RISCVISD::SELECT_CC: {
6116     // Transform
6117     SDValue LHS = N->getOperand(0);
6118     SDValue RHS = N->getOperand(1);
6119     auto CCVal = static_cast<ISD::CondCode>(N->getConstantOperandVal(2));
6120     if (!ISD::isIntEqualitySetCC(CCVal))
6121       break;
6122 
6123     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
6124     //      (select_cc X, Y, lt, trueV, falseV)
6125     // Sometimes the setcc is introduced after select_cc has been formed.
6126     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6127         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6128       // If we're looking for eq 0 instead of ne 0, we need to invert the
6129       // condition.
6130       bool Invert = CCVal == ISD::SETEQ;
6131       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6132       if (Invert)
6133         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6134 
6135       SDLoc DL(N);
6136       RHS = LHS.getOperand(1);
6137       LHS = LHS.getOperand(0);
6138       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
6139 
6140       SDValue TargetCC =
6141           DAG.getTargetConstant(CCVal, DL, Subtarget.getXLenVT());
6142       return DAG.getNode(
6143           RISCVISD::SELECT_CC, DL, N->getValueType(0),
6144           {LHS, RHS, TargetCC, N->getOperand(3), N->getOperand(4)});
6145     }
6146 
6147     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
6148     //      (select_cc X, Y, eq/ne, trueV, falseV)
6149     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
6150       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
6151                          {LHS.getOperand(0), LHS.getOperand(1),
6152                           N->getOperand(2), N->getOperand(3),
6153                           N->getOperand(4)});
6154     // (select_cc X, 1, setne, trueV, falseV) ->
6155     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
6156     // This can occur when legalizing some floating point comparisons.
6157     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
6158     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
6159       SDLoc DL(N);
6160       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6161       SDValue TargetCC =
6162           DAG.getTargetConstant(CCVal, DL, Subtarget.getXLenVT());
6163       RHS = DAG.getConstant(0, DL, LHS.getValueType());
6164       return DAG.getNode(
6165           RISCVISD::SELECT_CC, DL, N->getValueType(0),
6166           {LHS, RHS, TargetCC, N->getOperand(3), N->getOperand(4)});
6167     }
6168 
6169     break;
6170   }
6171   case RISCVISD::BR_CC: {
6172     SDValue LHS = N->getOperand(1);
6173     SDValue RHS = N->getOperand(2);
6174     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
6175     if (!ISD::isIntEqualitySetCC(CCVal))
6176       break;
6177 
6178     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
6179     //      (br_cc X, Y, lt, dest)
6180     // Sometimes the setcc is introduced after br_cc has been formed.
6181     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
6182         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
6183       // If we're looking for eq 0 instead of ne 0, we need to invert the
6184       // condition.
6185       bool Invert = CCVal == ISD::SETEQ;
6186       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6187       if (Invert)
6188         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6189 
6190       SDLoc DL(N);
6191       RHS = LHS.getOperand(1);
6192       LHS = LHS.getOperand(0);
6193       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
6194 
6195       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
6196                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
6197                          N->getOperand(4));
6198     }
6199 
6200     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
6201     //      (br_cc X, Y, eq/ne, trueV, falseV)
6202     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
6203       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
6204                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
6205                          N->getOperand(3), N->getOperand(4));
6206 
6207     // (br_cc X, 1, setne, br_cc) ->
6208     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
6209     // This can occur when legalizing some floating point comparisons.
6210     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
6211     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
6212       SDLoc DL(N);
6213       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
6214       SDValue TargetCC = DAG.getCondCode(CCVal);
6215       RHS = DAG.getConstant(0, DL, LHS.getValueType());
6216       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
6217                          N->getOperand(0), LHS, RHS, TargetCC,
6218                          N->getOperand(4));
6219     }
6220     break;
6221   }
6222   case ISD::FCOPYSIGN: {
6223     EVT VT = N->getValueType(0);
6224     if (!VT.isVector())
6225       break;
6226     // There is a form of VFSGNJ which injects the negated sign of its second
6227     // operand. Try and bubble any FNEG up after the extend/round to produce
6228     // this optimized pattern. Avoid modifying cases where FP_ROUND and
6229     // TRUNC=1.
6230     SDValue In2 = N->getOperand(1);
6231     // Avoid cases where the extend/round has multiple uses, as duplicating
6232     // those is typically more expensive than removing a fneg.
6233     if (!In2.hasOneUse())
6234       break;
6235     if (In2.getOpcode() != ISD::FP_EXTEND &&
6236         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
6237       break;
6238     In2 = In2.getOperand(0);
6239     if (In2.getOpcode() != ISD::FNEG)
6240       break;
6241     SDLoc DL(N);
6242     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
6243     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
6244                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
6245   }
6246   case ISD::MGATHER:
6247   case ISD::MSCATTER: {
6248     if (!DCI.isBeforeLegalize())
6249       break;
6250     MaskedGatherScatterSDNode *MGSN = cast<MaskedGatherScatterSDNode>(N);
6251     SDValue Index = MGSN->getIndex();
6252     EVT IndexVT = Index.getValueType();
6253     MVT XLenVT = Subtarget.getXLenVT();
6254     // RISCV indexed loads only support the "unsigned unscaled" addressing
6255     // mode, so anything else must be manually legalized.
6256     bool NeedsIdxLegalization = MGSN->isIndexScaled() ||
6257                                 (MGSN->isIndexSigned() &&
6258                                  IndexVT.getVectorElementType().bitsLT(XLenVT));
6259     if (!NeedsIdxLegalization)
6260       break;
6261 
6262     SDLoc DL(N);
6263 
6264     // Any index legalization should first promote to XLenVT, so we don't lose
6265     // bits when scaling. This may create an illegal index type so we let
6266     // LLVM's legalization take care of the splitting.
6267     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
6268       IndexVT = IndexVT.changeVectorElementType(XLenVT);
6269       Index = DAG.getNode(MGSN->isIndexSigned() ? ISD::SIGN_EXTEND
6270                                                 : ISD::ZERO_EXTEND,
6271                           DL, IndexVT, Index);
6272     }
6273 
6274     unsigned Scale = N->getConstantOperandVal(5);
6275     if (MGSN->isIndexScaled() && Scale != 1) {
6276       // Manually scale the indices by the element size.
6277       // TODO: Sanitize the scale operand here?
6278       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
6279       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
6280       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
6281     }
6282 
6283     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
6284     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) {
6285       return DAG.getMaskedGather(
6286           N->getVTList(), MGSN->getMemoryVT(), DL,
6287           {MGSN->getChain(), MGN->getPassThru(), MGSN->getMask(),
6288            MGSN->getBasePtr(), Index, MGN->getScale()},
6289           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
6290     }
6291     const auto *MSN = cast<MaskedScatterSDNode>(N);
6292     return DAG.getMaskedScatter(
6293         N->getVTList(), MGSN->getMemoryVT(), DL,
6294         {MGSN->getChain(), MSN->getValue(), MGSN->getMask(), MGSN->getBasePtr(),
6295          Index, MGSN->getScale()},
6296         MGSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
6297   }
6298   case RISCVISD::SRA_VL:
6299   case RISCVISD::SRL_VL:
6300   case RISCVISD::SHL_VL: {
6301     SDValue ShAmt = N->getOperand(1);
6302     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
6303       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
6304       SDLoc DL(N);
6305       SDValue VL = N->getOperand(3);
6306       EVT VT = N->getValueType(0);
6307       ShAmt =
6308           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
6309       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
6310                          N->getOperand(2), N->getOperand(3));
6311     }
6312     break;
6313   }
6314   case ISD::SRA:
6315   case ISD::SRL:
6316   case ISD::SHL: {
6317     SDValue ShAmt = N->getOperand(1);
6318     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
6319       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
6320       SDLoc DL(N);
6321       EVT VT = N->getValueType(0);
6322       ShAmt =
6323           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
6324       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
6325     }
6326     break;
6327   }
6328   case RISCVISD::MUL_VL: {
6329     // Try to form VWMUL or VWMULU.
6330     // FIXME: Look for splat of extended scalar as well.
6331     // FIXME: Support VWMULSU.
6332     SDValue Op0 = N->getOperand(0);
6333     SDValue Op1 = N->getOperand(1);
6334     bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
6335     bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
6336     if ((!IsSignExt && !IsZeroExt) || Op0.getOpcode() != Op1.getOpcode())
6337       return SDValue();
6338 
6339     // Make sure the extends have a single use.
6340     if (!Op0.hasOneUse() || !Op1.hasOneUse())
6341       return SDValue();
6342 
6343     SDValue Mask = N->getOperand(2);
6344     SDValue VL = N->getOperand(3);
6345     if (Op0.getOperand(1) != Mask || Op1.getOperand(1) != Mask ||
6346         Op0.getOperand(2) != VL || Op1.getOperand(2) != VL)
6347       return SDValue();
6348 
6349     Op0 = Op0.getOperand(0);
6350     Op1 = Op1.getOperand(0);
6351 
6352     MVT VT = N->getSimpleValueType(0);
6353     MVT NarrowVT =
6354         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() / 2),
6355                          VT.getVectorElementCount());
6356 
6357     SDLoc DL(N);
6358 
6359     // Re-introduce narrower extends if needed.
6360     unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
6361     if (Op0.getValueType() != NarrowVT)
6362       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
6363     if (Op1.getValueType() != NarrowVT)
6364       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
6365 
6366     unsigned WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
6367     return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
6368   }
6369   }
6370 
6371   return SDValue();
6372 }
6373 
6374 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
6375     const SDNode *N, CombineLevel Level) const {
6376   // The following folds are only desirable if `(OP _, c1 << c2)` can be
6377   // materialised in fewer instructions than `(OP _, c1)`:
6378   //
6379   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
6380   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
6381   SDValue N0 = N->getOperand(0);
6382   EVT Ty = N0.getValueType();
6383   if (Ty.isScalarInteger() &&
6384       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
6385     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
6386     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
6387     if (C1 && C2) {
6388       const APInt &C1Int = C1->getAPIntValue();
6389       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
6390 
6391       // We can materialise `c1 << c2` into an add immediate, so it's "free",
6392       // and the combine should happen, to potentially allow further combines
6393       // later.
6394       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
6395           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
6396         return true;
6397 
6398       // We can materialise `c1` in an add immediate, so it's "free", and the
6399       // combine should be prevented.
6400       if (C1Int.getMinSignedBits() <= 64 &&
6401           isLegalAddImmediate(C1Int.getSExtValue()))
6402         return false;
6403 
6404       // Neither constant will fit into an immediate, so find materialisation
6405       // costs.
6406       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
6407                                               Subtarget.getFeatureBits(),
6408                                               /*CompressionCost*/true);
6409       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
6410           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
6411           /*CompressionCost*/true);
6412 
6413       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
6414       // combine should be prevented.
6415       if (C1Cost < ShiftedC1Cost)
6416         return false;
6417     }
6418   }
6419   return true;
6420 }
6421 
6422 bool RISCVTargetLowering::targetShrinkDemandedConstant(
6423     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
6424     TargetLoweringOpt &TLO) const {
6425   // Delay this optimization as late as possible.
6426   if (!TLO.LegalOps)
6427     return false;
6428 
6429   EVT VT = Op.getValueType();
6430   if (VT.isVector())
6431     return false;
6432 
6433   // Only handle AND for now.
6434   if (Op.getOpcode() != ISD::AND)
6435     return false;
6436 
6437   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6438   if (!C)
6439     return false;
6440 
6441   const APInt &Mask = C->getAPIntValue();
6442 
6443   // Clear all non-demanded bits initially.
6444   APInt ShrunkMask = Mask & DemandedBits;
6445 
6446   // Try to make a smaller immediate by setting undemanded bits.
6447 
6448   APInt ExpandedMask = Mask | ~DemandedBits;
6449 
6450   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
6451     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
6452   };
6453   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
6454     if (NewMask == Mask)
6455       return true;
6456     SDLoc DL(Op);
6457     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
6458     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
6459     return TLO.CombineTo(Op, NewOp);
6460   };
6461 
6462   // If the shrunk mask fits in sign extended 12 bits, let the target
6463   // independent code apply it.
6464   if (ShrunkMask.isSignedIntN(12))
6465     return false;
6466 
6467   // Preserve (and X, 0xffff) when zext.h is supported.
6468   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
6469     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
6470     if (IsLegalMask(NewMask))
6471       return UseMask(NewMask);
6472   }
6473 
6474   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
6475   if (VT == MVT::i64) {
6476     APInt NewMask = APInt(64, 0xffffffff);
6477     if (IsLegalMask(NewMask))
6478       return UseMask(NewMask);
6479   }
6480 
6481   // For the remaining optimizations, we need to be able to make a negative
6482   // number through a combination of mask and undemanded bits.
6483   if (!ExpandedMask.isNegative())
6484     return false;
6485 
6486   // What is the fewest number of bits we need to represent the negative number.
6487   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
6488 
6489   // Try to make a 12 bit negative immediate. If that fails try to make a 32
6490   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
6491   APInt NewMask = ShrunkMask;
6492   if (MinSignedBits <= 12)
6493     NewMask.setBitsFrom(11);
6494   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
6495     NewMask.setBitsFrom(31);
6496   else
6497     return false;
6498 
6499   // Sanity check that our new mask is a subset of the demanded mask.
6500   assert(IsLegalMask(NewMask));
6501   return UseMask(NewMask);
6502 }
6503 
6504 static void computeGREV(APInt &Src, unsigned ShAmt) {
6505   ShAmt &= Src.getBitWidth() - 1;
6506   uint64_t x = Src.getZExtValue();
6507   if (ShAmt & 1)
6508     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
6509   if (ShAmt & 2)
6510     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
6511   if (ShAmt & 4)
6512     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
6513   if (ShAmt & 8)
6514     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
6515   if (ShAmt & 16)
6516     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
6517   if (ShAmt & 32)
6518     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
6519   Src = x;
6520 }
6521 
6522 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
6523                                                         KnownBits &Known,
6524                                                         const APInt &DemandedElts,
6525                                                         const SelectionDAG &DAG,
6526                                                         unsigned Depth) const {
6527   unsigned BitWidth = Known.getBitWidth();
6528   unsigned Opc = Op.getOpcode();
6529   assert((Opc >= ISD::BUILTIN_OP_END ||
6530           Opc == ISD::INTRINSIC_WO_CHAIN ||
6531           Opc == ISD::INTRINSIC_W_CHAIN ||
6532           Opc == ISD::INTRINSIC_VOID) &&
6533          "Should use MaskedValueIsZero if you don't know whether Op"
6534          " is a target node!");
6535 
6536   Known.resetAll();
6537   switch (Opc) {
6538   default: break;
6539   case RISCVISD::SELECT_CC: {
6540     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
6541     // If we don't know any bits, early out.
6542     if (Known.isUnknown())
6543       break;
6544     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
6545 
6546     // Only known if known in both the LHS and RHS.
6547     Known = KnownBits::commonBits(Known, Known2);
6548     break;
6549   }
6550   case RISCVISD::REMUW: {
6551     KnownBits Known2;
6552     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6553     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6554     // We only care about the lower 32 bits.
6555     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
6556     // Restore the original width by sign extending.
6557     Known = Known.sext(BitWidth);
6558     break;
6559   }
6560   case RISCVISD::DIVUW: {
6561     KnownBits Known2;
6562     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
6563     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
6564     // We only care about the lower 32 bits.
6565     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
6566     // Restore the original width by sign extending.
6567     Known = Known.sext(BitWidth);
6568     break;
6569   }
6570   case RISCVISD::CTZW: {
6571     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
6572     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
6573     unsigned LowBits = Log2_32(PossibleTZ) + 1;
6574     Known.Zero.setBitsFrom(LowBits);
6575     break;
6576   }
6577   case RISCVISD::CLZW: {
6578     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
6579     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
6580     unsigned LowBits = Log2_32(PossibleLZ) + 1;
6581     Known.Zero.setBitsFrom(LowBits);
6582     break;
6583   }
6584   case RISCVISD::GREV:
6585   case RISCVISD::GREVW: {
6586     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
6587       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
6588       if (Opc == RISCVISD::GREVW)
6589         Known = Known.trunc(32);
6590       unsigned ShAmt = C->getZExtValue();
6591       computeGREV(Known.Zero, ShAmt);
6592       computeGREV(Known.One, ShAmt);
6593       if (Opc == RISCVISD::GREVW)
6594         Known = Known.sext(BitWidth);
6595     }
6596     break;
6597   }
6598   case RISCVISD::READ_VLENB:
6599     // We assume VLENB is at least 16 bytes.
6600     Known.Zero.setLowBits(4);
6601     // We assume VLENB is no more than 65536 / 8 bytes.
6602     Known.Zero.setBitsFrom(14);
6603     break;
6604   case ISD::INTRINSIC_W_CHAIN: {
6605     unsigned IntNo = Op.getConstantOperandVal(1);
6606     switch (IntNo) {
6607     default:
6608       // We can't do anything for most intrinsics.
6609       break;
6610     case Intrinsic::riscv_vsetvli:
6611     case Intrinsic::riscv_vsetvlimax:
6612       // Assume that VL output is positive and would fit in an int32_t.
6613       // TODO: VLEN might be capped at 16 bits in a future V spec update.
6614       if (BitWidth >= 32)
6615         Known.Zero.setBitsFrom(31);
6616       break;
6617     }
6618     break;
6619   }
6620   }
6621 }
6622 
6623 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
6624     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
6625     unsigned Depth) const {
6626   switch (Op.getOpcode()) {
6627   default:
6628     break;
6629   case RISCVISD::SLLW:
6630   case RISCVISD::SRAW:
6631   case RISCVISD::SRLW:
6632   case RISCVISD::DIVW:
6633   case RISCVISD::DIVUW:
6634   case RISCVISD::REMUW:
6635   case RISCVISD::ROLW:
6636   case RISCVISD::RORW:
6637   case RISCVISD::GREVW:
6638   case RISCVISD::GORCW:
6639   case RISCVISD::FSLW:
6640   case RISCVISD::FSRW:
6641   case RISCVISD::SHFLW:
6642   case RISCVISD::UNSHFLW:
6643   case RISCVISD::BCOMPRESSW:
6644   case RISCVISD::BDECOMPRESSW:
6645   case RISCVISD::FCVT_W_RV64:
6646   case RISCVISD::FCVT_WU_RV64:
6647     // TODO: As the result is sign-extended, this is conservatively correct. A
6648     // more precise answer could be calculated for SRAW depending on known
6649     // bits in the shift amount.
6650     return 33;
6651   case RISCVISD::SHFL:
6652   case RISCVISD::UNSHFL: {
6653     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
6654     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
6655     // will stay within the upper 32 bits. If there were more than 32 sign bits
6656     // before there will be at least 33 sign bits after.
6657     if (Op.getValueType() == MVT::i64 &&
6658         isa<ConstantSDNode>(Op.getOperand(1)) &&
6659         (Op.getConstantOperandVal(1) & 0x10) == 0) {
6660       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
6661       if (Tmp > 32)
6662         return 33;
6663     }
6664     break;
6665   }
6666   case RISCVISD::VMV_X_S:
6667     // The number of sign bits of the scalar result is computed by obtaining the
6668     // element type of the input vector operand, subtracting its width from the
6669     // XLEN, and then adding one (sign bit within the element type). If the
6670     // element type is wider than XLen, the least-significant XLEN bits are
6671     // taken.
6672     if (Op.getOperand(0).getScalarValueSizeInBits() > Subtarget.getXLen())
6673       return 1;
6674     return Subtarget.getXLen() - Op.getOperand(0).getScalarValueSizeInBits() + 1;
6675   }
6676 
6677   return 1;
6678 }
6679 
6680 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
6681                                                   MachineBasicBlock *BB) {
6682   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
6683 
6684   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
6685   // Should the count have wrapped while it was being read, we need to try
6686   // again.
6687   // ...
6688   // read:
6689   // rdcycleh x3 # load high word of cycle
6690   // rdcycle  x2 # load low word of cycle
6691   // rdcycleh x4 # load high word of cycle
6692   // bne x3, x4, read # check if high word reads match, otherwise try again
6693   // ...
6694 
6695   MachineFunction &MF = *BB->getParent();
6696   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6697   MachineFunction::iterator It = ++BB->getIterator();
6698 
6699   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
6700   MF.insert(It, LoopMBB);
6701 
6702   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
6703   MF.insert(It, DoneMBB);
6704 
6705   // Transfer the remainder of BB and its successor edges to DoneMBB.
6706   DoneMBB->splice(DoneMBB->begin(), BB,
6707                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6708   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
6709 
6710   BB->addSuccessor(LoopMBB);
6711 
6712   MachineRegisterInfo &RegInfo = MF.getRegInfo();
6713   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
6714   Register LoReg = MI.getOperand(0).getReg();
6715   Register HiReg = MI.getOperand(1).getReg();
6716   DebugLoc DL = MI.getDebugLoc();
6717 
6718   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
6719   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
6720       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
6721       .addReg(RISCV::X0);
6722   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
6723       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
6724       .addReg(RISCV::X0);
6725   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
6726       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
6727       .addReg(RISCV::X0);
6728 
6729   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
6730       .addReg(HiReg)
6731       .addReg(ReadAgainReg)
6732       .addMBB(LoopMBB);
6733 
6734   LoopMBB->addSuccessor(LoopMBB);
6735   LoopMBB->addSuccessor(DoneMBB);
6736 
6737   MI.eraseFromParent();
6738 
6739   return DoneMBB;
6740 }
6741 
6742 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
6743                                              MachineBasicBlock *BB) {
6744   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
6745 
6746   MachineFunction &MF = *BB->getParent();
6747   DebugLoc DL = MI.getDebugLoc();
6748   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
6749   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
6750   Register LoReg = MI.getOperand(0).getReg();
6751   Register HiReg = MI.getOperand(1).getReg();
6752   Register SrcReg = MI.getOperand(2).getReg();
6753   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
6754   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
6755 
6756   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
6757                           RI);
6758   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
6759   MachineMemOperand *MMOLo =
6760       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
6761   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
6762       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
6763   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
6764       .addFrameIndex(FI)
6765       .addImm(0)
6766       .addMemOperand(MMOLo);
6767   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
6768       .addFrameIndex(FI)
6769       .addImm(4)
6770       .addMemOperand(MMOHi);
6771   MI.eraseFromParent(); // The pseudo instruction is gone now.
6772   return BB;
6773 }
6774 
6775 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
6776                                                  MachineBasicBlock *BB) {
6777   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
6778          "Unexpected instruction");
6779 
6780   MachineFunction &MF = *BB->getParent();
6781   DebugLoc DL = MI.getDebugLoc();
6782   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
6783   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
6784   Register DstReg = MI.getOperand(0).getReg();
6785   Register LoReg = MI.getOperand(1).getReg();
6786   Register HiReg = MI.getOperand(2).getReg();
6787   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
6788   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
6789 
6790   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
6791   MachineMemOperand *MMOLo =
6792       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
6793   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
6794       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
6795   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
6796       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
6797       .addFrameIndex(FI)
6798       .addImm(0)
6799       .addMemOperand(MMOLo);
6800   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
6801       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
6802       .addFrameIndex(FI)
6803       .addImm(4)
6804       .addMemOperand(MMOHi);
6805   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
6806   MI.eraseFromParent(); // The pseudo instruction is gone now.
6807   return BB;
6808 }
6809 
6810 static bool isSelectPseudo(MachineInstr &MI) {
6811   switch (MI.getOpcode()) {
6812   default:
6813     return false;
6814   case RISCV::Select_GPR_Using_CC_GPR:
6815   case RISCV::Select_FPR16_Using_CC_GPR:
6816   case RISCV::Select_FPR32_Using_CC_GPR:
6817   case RISCV::Select_FPR64_Using_CC_GPR:
6818     return true;
6819   }
6820 }
6821 
6822 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
6823                                            MachineBasicBlock *BB) {
6824   // To "insert" Select_* instructions, we actually have to insert the triangle
6825   // control-flow pattern.  The incoming instructions know the destination vreg
6826   // to set, the condition code register to branch on, the true/false values to
6827   // select between, and the condcode to use to select the appropriate branch.
6828   //
6829   // We produce the following control flow:
6830   //     HeadMBB
6831   //     |  \
6832   //     |  IfFalseMBB
6833   //     | /
6834   //    TailMBB
6835   //
6836   // When we find a sequence of selects we attempt to optimize their emission
6837   // by sharing the control flow. Currently we only handle cases where we have
6838   // multiple selects with the exact same condition (same LHS, RHS and CC).
6839   // The selects may be interleaved with other instructions if the other
6840   // instructions meet some requirements we deem safe:
6841   // - They are debug instructions. Otherwise,
6842   // - They do not have side-effects, do not access memory and their inputs do
6843   //   not depend on the results of the select pseudo-instructions.
6844   // The TrueV/FalseV operands of the selects cannot depend on the result of
6845   // previous selects in the sequence.
6846   // These conditions could be further relaxed. See the X86 target for a
6847   // related approach and more information.
6848   Register LHS = MI.getOperand(1).getReg();
6849   Register RHS = MI.getOperand(2).getReg();
6850   auto CC = static_cast<ISD::CondCode>(MI.getOperand(3).getImm());
6851 
6852   SmallVector<MachineInstr *, 4> SelectDebugValues;
6853   SmallSet<Register, 4> SelectDests;
6854   SelectDests.insert(MI.getOperand(0).getReg());
6855 
6856   MachineInstr *LastSelectPseudo = &MI;
6857 
6858   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
6859        SequenceMBBI != E; ++SequenceMBBI) {
6860     if (SequenceMBBI->isDebugInstr())
6861       continue;
6862     else if (isSelectPseudo(*SequenceMBBI)) {
6863       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
6864           SequenceMBBI->getOperand(2).getReg() != RHS ||
6865           SequenceMBBI->getOperand(3).getImm() != CC ||
6866           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
6867           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
6868         break;
6869       LastSelectPseudo = &*SequenceMBBI;
6870       SequenceMBBI->collectDebugValues(SelectDebugValues);
6871       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
6872     } else {
6873       if (SequenceMBBI->hasUnmodeledSideEffects() ||
6874           SequenceMBBI->mayLoadOrStore())
6875         break;
6876       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
6877             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
6878           }))
6879         break;
6880     }
6881   }
6882 
6883   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
6884   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6885   DebugLoc DL = MI.getDebugLoc();
6886   MachineFunction::iterator I = ++BB->getIterator();
6887 
6888   MachineBasicBlock *HeadMBB = BB;
6889   MachineFunction *F = BB->getParent();
6890   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
6891   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
6892 
6893   F->insert(I, IfFalseMBB);
6894   F->insert(I, TailMBB);
6895 
6896   // Transfer debug instructions associated with the selects to TailMBB.
6897   for (MachineInstr *DebugInstr : SelectDebugValues) {
6898     TailMBB->push_back(DebugInstr->removeFromParent());
6899   }
6900 
6901   // Move all instructions after the sequence to TailMBB.
6902   TailMBB->splice(TailMBB->end(), HeadMBB,
6903                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
6904   // Update machine-CFG edges by transferring all successors of the current
6905   // block to the new block which will contain the Phi nodes for the selects.
6906   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
6907   // Set the successors for HeadMBB.
6908   HeadMBB->addSuccessor(IfFalseMBB);
6909   HeadMBB->addSuccessor(TailMBB);
6910 
6911   // Insert appropriate branch.
6912   unsigned Opcode = getBranchOpcodeForIntCondCode(CC);
6913 
6914   BuildMI(HeadMBB, DL, TII.get(Opcode))
6915     .addReg(LHS)
6916     .addReg(RHS)
6917     .addMBB(TailMBB);
6918 
6919   // IfFalseMBB just falls through to TailMBB.
6920   IfFalseMBB->addSuccessor(TailMBB);
6921 
6922   // Create PHIs for all of the select pseudo-instructions.
6923   auto SelectMBBI = MI.getIterator();
6924   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
6925   auto InsertionPoint = TailMBB->begin();
6926   while (SelectMBBI != SelectEnd) {
6927     auto Next = std::next(SelectMBBI);
6928     if (isSelectPseudo(*SelectMBBI)) {
6929       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
6930       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
6931               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
6932           .addReg(SelectMBBI->getOperand(4).getReg())
6933           .addMBB(HeadMBB)
6934           .addReg(SelectMBBI->getOperand(5).getReg())
6935           .addMBB(IfFalseMBB);
6936       SelectMBBI->eraseFromParent();
6937     }
6938     SelectMBBI = Next;
6939   }
6940 
6941   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
6942   return TailMBB;
6943 }
6944 
6945 MachineBasicBlock *
6946 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
6947                                                  MachineBasicBlock *BB) const {
6948   switch (MI.getOpcode()) {
6949   default:
6950     llvm_unreachable("Unexpected instr type to insert");
6951   case RISCV::ReadCycleWide:
6952     assert(!Subtarget.is64Bit() &&
6953            "ReadCycleWrite is only to be used on riscv32");
6954     return emitReadCycleWidePseudo(MI, BB);
6955   case RISCV::Select_GPR_Using_CC_GPR:
6956   case RISCV::Select_FPR16_Using_CC_GPR:
6957   case RISCV::Select_FPR32_Using_CC_GPR:
6958   case RISCV::Select_FPR64_Using_CC_GPR:
6959     return emitSelectPseudo(MI, BB);
6960   case RISCV::BuildPairF64Pseudo:
6961     return emitBuildPairF64Pseudo(MI, BB);
6962   case RISCV::SplitF64Pseudo:
6963     return emitSplitF64Pseudo(MI, BB);
6964   }
6965 }
6966 
6967 // Calling Convention Implementation.
6968 // The expectations for frontend ABI lowering vary from target to target.
6969 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
6970 // details, but this is a longer term goal. For now, we simply try to keep the
6971 // role of the frontend as simple and well-defined as possible. The rules can
6972 // be summarised as:
6973 // * Never split up large scalar arguments. We handle them here.
6974 // * If a hardfloat calling convention is being used, and the struct may be
6975 // passed in a pair of registers (fp+fp, int+fp), and both registers are
6976 // available, then pass as two separate arguments. If either the GPRs or FPRs
6977 // are exhausted, then pass according to the rule below.
6978 // * If a struct could never be passed in registers or directly in a stack
6979 // slot (as it is larger than 2*XLEN and the floating point rules don't
6980 // apply), then pass it using a pointer with the byval attribute.
6981 // * If a struct is less than 2*XLEN, then coerce to either a two-element
6982 // word-sized array or a 2*XLEN scalar (depending on alignment).
6983 // * The frontend can determine whether a struct is returned by reference or
6984 // not based on its size and fields. If it will be returned by reference, the
6985 // frontend must modify the prototype so a pointer with the sret annotation is
6986 // passed as the first argument. This is not necessary for large scalar
6987 // returns.
6988 // * Struct return values and varargs should be coerced to structs containing
6989 // register-size fields in the same situations they would be for fixed
6990 // arguments.
6991 
6992 static const MCPhysReg ArgGPRs[] = {
6993   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
6994   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
6995 };
6996 static const MCPhysReg ArgFPR16s[] = {
6997   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
6998   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
6999 };
7000 static const MCPhysReg ArgFPR32s[] = {
7001   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
7002   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
7003 };
7004 static const MCPhysReg ArgFPR64s[] = {
7005   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
7006   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
7007 };
7008 // This is an interim calling convention and it may be changed in the future.
7009 static const MCPhysReg ArgVRs[] = {
7010     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
7011     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
7012     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
7013 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
7014                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
7015                                      RISCV::V20M2, RISCV::V22M2};
7016 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
7017                                      RISCV::V20M4};
7018 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
7019 
7020 // Pass a 2*XLEN argument that has been split into two XLEN values through
7021 // registers or the stack as necessary.
7022 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
7023                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
7024                                 MVT ValVT2, MVT LocVT2,
7025                                 ISD::ArgFlagsTy ArgFlags2) {
7026   unsigned XLenInBytes = XLen / 8;
7027   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7028     // At least one half can be passed via register.
7029     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
7030                                      VA1.getLocVT(), CCValAssign::Full));
7031   } else {
7032     // Both halves must be passed on the stack, with proper alignment.
7033     Align StackAlign =
7034         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
7035     State.addLoc(
7036         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
7037                             State.AllocateStack(XLenInBytes, StackAlign),
7038                             VA1.getLocVT(), CCValAssign::Full));
7039     State.addLoc(CCValAssign::getMem(
7040         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7041         LocVT2, CCValAssign::Full));
7042     return false;
7043   }
7044 
7045   if (Register Reg = State.AllocateReg(ArgGPRs)) {
7046     // The second half can also be passed via register.
7047     State.addLoc(
7048         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
7049   } else {
7050     // The second half is passed via the stack, without additional alignment.
7051     State.addLoc(CCValAssign::getMem(
7052         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
7053         LocVT2, CCValAssign::Full));
7054   }
7055 
7056   return false;
7057 }
7058 
7059 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
7060                                Optional<unsigned> FirstMaskArgument,
7061                                CCState &State, const RISCVTargetLowering &TLI) {
7062   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
7063   if (RC == &RISCV::VRRegClass) {
7064     // Assign the first mask argument to V0.
7065     // This is an interim calling convention and it may be changed in the
7066     // future.
7067     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
7068       return State.AllocateReg(RISCV::V0);
7069     return State.AllocateReg(ArgVRs);
7070   }
7071   if (RC == &RISCV::VRM2RegClass)
7072     return State.AllocateReg(ArgVRM2s);
7073   if (RC == &RISCV::VRM4RegClass)
7074     return State.AllocateReg(ArgVRM4s);
7075   if (RC == &RISCV::VRM8RegClass)
7076     return State.AllocateReg(ArgVRM8s);
7077   llvm_unreachable("Unhandled register class for ValueType");
7078 }
7079 
7080 // Implements the RISC-V calling convention. Returns true upon failure.
7081 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
7082                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
7083                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
7084                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
7085                      Optional<unsigned> FirstMaskArgument) {
7086   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
7087   assert(XLen == 32 || XLen == 64);
7088   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
7089 
7090   // Any return value split in to more than two values can't be returned
7091   // directly. Vectors are returned via the available vector registers.
7092   if (!LocVT.isVector() && IsRet && ValNo > 1)
7093     return true;
7094 
7095   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
7096   // variadic argument, or if no F16/F32 argument registers are available.
7097   bool UseGPRForF16_F32 = true;
7098   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
7099   // variadic argument, or if no F64 argument registers are available.
7100   bool UseGPRForF64 = true;
7101 
7102   switch (ABI) {
7103   default:
7104     llvm_unreachable("Unexpected ABI");
7105   case RISCVABI::ABI_ILP32:
7106   case RISCVABI::ABI_LP64:
7107     break;
7108   case RISCVABI::ABI_ILP32F:
7109   case RISCVABI::ABI_LP64F:
7110     UseGPRForF16_F32 = !IsFixed;
7111     break;
7112   case RISCVABI::ABI_ILP32D:
7113   case RISCVABI::ABI_LP64D:
7114     UseGPRForF16_F32 = !IsFixed;
7115     UseGPRForF64 = !IsFixed;
7116     break;
7117   }
7118 
7119   // FPR16, FPR32, and FPR64 alias each other.
7120   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
7121     UseGPRForF16_F32 = true;
7122     UseGPRForF64 = true;
7123   }
7124 
7125   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
7126   // similar local variables rather than directly checking against the target
7127   // ABI.
7128 
7129   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
7130     LocVT = XLenVT;
7131     LocInfo = CCValAssign::BCvt;
7132   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
7133     LocVT = MVT::i64;
7134     LocInfo = CCValAssign::BCvt;
7135   }
7136 
7137   // If this is a variadic argument, the RISC-V calling convention requires
7138   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
7139   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
7140   // be used regardless of whether the original argument was split during
7141   // legalisation or not. The argument will not be passed by registers if the
7142   // original type is larger than 2*XLEN, so the register alignment rule does
7143   // not apply.
7144   unsigned TwoXLenInBytes = (2 * XLen) / 8;
7145   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
7146       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
7147     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
7148     // Skip 'odd' register if necessary.
7149     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
7150       State.AllocateReg(ArgGPRs);
7151   }
7152 
7153   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
7154   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
7155       State.getPendingArgFlags();
7156 
7157   assert(PendingLocs.size() == PendingArgFlags.size() &&
7158          "PendingLocs and PendingArgFlags out of sync");
7159 
7160   // Handle passing f64 on RV32D with a soft float ABI or when floating point
7161   // registers are exhausted.
7162   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
7163     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
7164            "Can't lower f64 if it is split");
7165     // Depending on available argument GPRS, f64 may be passed in a pair of
7166     // GPRs, split between a GPR and the stack, or passed completely on the
7167     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
7168     // cases.
7169     Register Reg = State.AllocateReg(ArgGPRs);
7170     LocVT = MVT::i32;
7171     if (!Reg) {
7172       unsigned StackOffset = State.AllocateStack(8, Align(8));
7173       State.addLoc(
7174           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
7175       return false;
7176     }
7177     if (!State.AllocateReg(ArgGPRs))
7178       State.AllocateStack(4, Align(4));
7179     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7180     return false;
7181   }
7182 
7183   // Fixed-length vectors are located in the corresponding scalable-vector
7184   // container types.
7185   if (ValVT.isFixedLengthVector())
7186     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
7187 
7188   // Split arguments might be passed indirectly, so keep track of the pending
7189   // values. Split vectors are passed via a mix of registers and indirectly, so
7190   // treat them as we would any other argument.
7191   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
7192     LocVT = XLenVT;
7193     LocInfo = CCValAssign::Indirect;
7194     PendingLocs.push_back(
7195         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
7196     PendingArgFlags.push_back(ArgFlags);
7197     if (!ArgFlags.isSplitEnd()) {
7198       return false;
7199     }
7200   }
7201 
7202   // If the split argument only had two elements, it should be passed directly
7203   // in registers or on the stack.
7204   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
7205       PendingLocs.size() <= 2) {
7206     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
7207     // Apply the normal calling convention rules to the first half of the
7208     // split argument.
7209     CCValAssign VA = PendingLocs[0];
7210     ISD::ArgFlagsTy AF = PendingArgFlags[0];
7211     PendingLocs.clear();
7212     PendingArgFlags.clear();
7213     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
7214                                ArgFlags);
7215   }
7216 
7217   // Allocate to a register if possible, or else a stack slot.
7218   Register Reg;
7219   unsigned StoreSizeBytes = XLen / 8;
7220   Align StackAlign = Align(XLen / 8);
7221 
7222   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
7223     Reg = State.AllocateReg(ArgFPR16s);
7224   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
7225     Reg = State.AllocateReg(ArgFPR32s);
7226   else if (ValVT == MVT::f64 && !UseGPRForF64)
7227     Reg = State.AllocateReg(ArgFPR64s);
7228   else if (ValVT.isVector()) {
7229     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
7230     if (!Reg) {
7231       // For return values, the vector must be passed fully via registers or
7232       // via the stack.
7233       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
7234       // but we're using all of them.
7235       if (IsRet)
7236         return true;
7237       // Try using a GPR to pass the address
7238       if ((Reg = State.AllocateReg(ArgGPRs))) {
7239         LocVT = XLenVT;
7240         LocInfo = CCValAssign::Indirect;
7241       } else if (ValVT.isScalableVector()) {
7242         report_fatal_error("Unable to pass scalable vector types on the stack");
7243       } else {
7244         // Pass fixed-length vectors on the stack.
7245         LocVT = ValVT;
7246         StoreSizeBytes = ValVT.getStoreSize();
7247         // Align vectors to their element sizes, being careful for vXi1
7248         // vectors.
7249         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
7250       }
7251     }
7252   } else {
7253     Reg = State.AllocateReg(ArgGPRs);
7254   }
7255 
7256   unsigned StackOffset =
7257       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
7258 
7259   // If we reach this point and PendingLocs is non-empty, we must be at the
7260   // end of a split argument that must be passed indirectly.
7261   if (!PendingLocs.empty()) {
7262     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
7263     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
7264 
7265     for (auto &It : PendingLocs) {
7266       if (Reg)
7267         It.convertToReg(Reg);
7268       else
7269         It.convertToMem(StackOffset);
7270       State.addLoc(It);
7271     }
7272     PendingLocs.clear();
7273     PendingArgFlags.clear();
7274     return false;
7275   }
7276 
7277   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
7278           (TLI.getSubtarget().hasStdExtV() && ValVT.isVector())) &&
7279          "Expected an XLenVT or vector types at this stage");
7280 
7281   if (Reg) {
7282     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7283     return false;
7284   }
7285 
7286   // When a floating-point value is passed on the stack, no bit-conversion is
7287   // needed.
7288   if (ValVT.isFloatingPoint()) {
7289     LocVT = ValVT;
7290     LocInfo = CCValAssign::Full;
7291   }
7292   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
7293   return false;
7294 }
7295 
7296 template <typename ArgTy>
7297 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
7298   for (const auto &ArgIdx : enumerate(Args)) {
7299     MVT ArgVT = ArgIdx.value().VT;
7300     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
7301       return ArgIdx.index();
7302   }
7303   return None;
7304 }
7305 
7306 void RISCVTargetLowering::analyzeInputArgs(
7307     MachineFunction &MF, CCState &CCInfo,
7308     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
7309     RISCVCCAssignFn Fn) const {
7310   unsigned NumArgs = Ins.size();
7311   FunctionType *FType = MF.getFunction().getFunctionType();
7312 
7313   Optional<unsigned> FirstMaskArgument;
7314   if (Subtarget.hasStdExtV())
7315     FirstMaskArgument = preAssignMask(Ins);
7316 
7317   for (unsigned i = 0; i != NumArgs; ++i) {
7318     MVT ArgVT = Ins[i].VT;
7319     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
7320 
7321     Type *ArgTy = nullptr;
7322     if (IsRet)
7323       ArgTy = FType->getReturnType();
7324     else if (Ins[i].isOrigArg())
7325       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
7326 
7327     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
7328     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
7329            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
7330            FirstMaskArgument)) {
7331       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
7332                         << EVT(ArgVT).getEVTString() << '\n');
7333       llvm_unreachable(nullptr);
7334     }
7335   }
7336 }
7337 
7338 void RISCVTargetLowering::analyzeOutputArgs(
7339     MachineFunction &MF, CCState &CCInfo,
7340     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
7341     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
7342   unsigned NumArgs = Outs.size();
7343 
7344   Optional<unsigned> FirstMaskArgument;
7345   if (Subtarget.hasStdExtV())
7346     FirstMaskArgument = preAssignMask(Outs);
7347 
7348   for (unsigned i = 0; i != NumArgs; i++) {
7349     MVT ArgVT = Outs[i].VT;
7350     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
7351     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
7352 
7353     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
7354     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
7355            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
7356            FirstMaskArgument)) {
7357       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
7358                         << EVT(ArgVT).getEVTString() << "\n");
7359       llvm_unreachable(nullptr);
7360     }
7361   }
7362 }
7363 
7364 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
7365 // values.
7366 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
7367                                    const CCValAssign &VA, const SDLoc &DL,
7368                                    const RISCVSubtarget &Subtarget) {
7369   switch (VA.getLocInfo()) {
7370   default:
7371     llvm_unreachable("Unexpected CCValAssign::LocInfo");
7372   case CCValAssign::Full:
7373     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
7374       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
7375     break;
7376   case CCValAssign::BCvt:
7377     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
7378       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
7379     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
7380       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
7381     else
7382       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
7383     break;
7384   }
7385   return Val;
7386 }
7387 
7388 // The caller is responsible for loading the full value if the argument is
7389 // passed with CCValAssign::Indirect.
7390 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
7391                                 const CCValAssign &VA, const SDLoc &DL,
7392                                 const RISCVTargetLowering &TLI) {
7393   MachineFunction &MF = DAG.getMachineFunction();
7394   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7395   EVT LocVT = VA.getLocVT();
7396   SDValue Val;
7397   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
7398   Register VReg = RegInfo.createVirtualRegister(RC);
7399   RegInfo.addLiveIn(VA.getLocReg(), VReg);
7400   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
7401 
7402   if (VA.getLocInfo() == CCValAssign::Indirect)
7403     return Val;
7404 
7405   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
7406 }
7407 
7408 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
7409                                    const CCValAssign &VA, const SDLoc &DL,
7410                                    const RISCVSubtarget &Subtarget) {
7411   EVT LocVT = VA.getLocVT();
7412 
7413   switch (VA.getLocInfo()) {
7414   default:
7415     llvm_unreachable("Unexpected CCValAssign::LocInfo");
7416   case CCValAssign::Full:
7417     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
7418       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
7419     break;
7420   case CCValAssign::BCvt:
7421     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
7422       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
7423     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
7424       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
7425     else
7426       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
7427     break;
7428   }
7429   return Val;
7430 }
7431 
7432 // The caller is responsible for loading the full value if the argument is
7433 // passed with CCValAssign::Indirect.
7434 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
7435                                 const CCValAssign &VA, const SDLoc &DL) {
7436   MachineFunction &MF = DAG.getMachineFunction();
7437   MachineFrameInfo &MFI = MF.getFrameInfo();
7438   EVT LocVT = VA.getLocVT();
7439   EVT ValVT = VA.getValVT();
7440   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
7441   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
7442                                  /*Immutable=*/true);
7443   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7444   SDValue Val;
7445 
7446   ISD::LoadExtType ExtType;
7447   switch (VA.getLocInfo()) {
7448   default:
7449     llvm_unreachable("Unexpected CCValAssign::LocInfo");
7450   case CCValAssign::Full:
7451   case CCValAssign::Indirect:
7452   case CCValAssign::BCvt:
7453     ExtType = ISD::NON_EXTLOAD;
7454     break;
7455   }
7456   Val = DAG.getExtLoad(
7457       ExtType, DL, LocVT, Chain, FIN,
7458       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
7459   return Val;
7460 }
7461 
7462 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
7463                                        const CCValAssign &VA, const SDLoc &DL) {
7464   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
7465          "Unexpected VA");
7466   MachineFunction &MF = DAG.getMachineFunction();
7467   MachineFrameInfo &MFI = MF.getFrameInfo();
7468   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7469 
7470   if (VA.isMemLoc()) {
7471     // f64 is passed on the stack.
7472     int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*Immutable=*/true);
7473     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
7474     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
7475                        MachinePointerInfo::getFixedStack(MF, FI));
7476   }
7477 
7478   assert(VA.isRegLoc() && "Expected register VA assignment");
7479 
7480   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7481   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
7482   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
7483   SDValue Hi;
7484   if (VA.getLocReg() == RISCV::X17) {
7485     // Second half of f64 is passed on the stack.
7486     int FI = MFI.CreateFixedObject(4, 0, /*Immutable=*/true);
7487     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
7488     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
7489                      MachinePointerInfo::getFixedStack(MF, FI));
7490   } else {
7491     // Second half of f64 is passed in another GPR.
7492     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
7493     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
7494     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
7495   }
7496   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
7497 }
7498 
7499 // FastCC has less than 1% performance improvement for some particular
7500 // benchmark. But theoretically, it may has benenfit for some cases.
7501 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
7502                             unsigned ValNo, MVT ValVT, MVT LocVT,
7503                             CCValAssign::LocInfo LocInfo,
7504                             ISD::ArgFlagsTy ArgFlags, CCState &State,
7505                             bool IsFixed, bool IsRet, Type *OrigTy,
7506                             const RISCVTargetLowering &TLI,
7507                             Optional<unsigned> FirstMaskArgument) {
7508 
7509   // X5 and X6 might be used for save-restore libcall.
7510   static const MCPhysReg GPRList[] = {
7511       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
7512       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
7513       RISCV::X29, RISCV::X30, RISCV::X31};
7514 
7515   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
7516     if (unsigned Reg = State.AllocateReg(GPRList)) {
7517       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7518       return false;
7519     }
7520   }
7521 
7522   if (LocVT == MVT::f16) {
7523     static const MCPhysReg FPR16List[] = {
7524         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
7525         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
7526         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
7527         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
7528     if (unsigned Reg = State.AllocateReg(FPR16List)) {
7529       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7530       return false;
7531     }
7532   }
7533 
7534   if (LocVT == MVT::f32) {
7535     static const MCPhysReg FPR32List[] = {
7536         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
7537         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
7538         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
7539         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
7540     if (unsigned Reg = State.AllocateReg(FPR32List)) {
7541       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7542       return false;
7543     }
7544   }
7545 
7546   if (LocVT == MVT::f64) {
7547     static const MCPhysReg FPR64List[] = {
7548         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
7549         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
7550         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
7551         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
7552     if (unsigned Reg = State.AllocateReg(FPR64List)) {
7553       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7554       return false;
7555     }
7556   }
7557 
7558   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
7559     unsigned Offset4 = State.AllocateStack(4, Align(4));
7560     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
7561     return false;
7562   }
7563 
7564   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
7565     unsigned Offset5 = State.AllocateStack(8, Align(8));
7566     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
7567     return false;
7568   }
7569 
7570   if (LocVT.isVector()) {
7571     if (unsigned Reg =
7572             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
7573       // Fixed-length vectors are located in the corresponding scalable-vector
7574       // container types.
7575       if (ValVT.isFixedLengthVector())
7576         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
7577       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7578     } else {
7579       // Try and pass the address via a "fast" GPR.
7580       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
7581         LocInfo = CCValAssign::Indirect;
7582         LocVT = TLI.getSubtarget().getXLenVT();
7583         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
7584       } else if (ValVT.isFixedLengthVector()) {
7585         auto StackAlign =
7586             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
7587         unsigned StackOffset =
7588             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
7589         State.addLoc(
7590             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
7591       } else {
7592         // Can't pass scalable vectors on the stack.
7593         return true;
7594       }
7595     }
7596 
7597     return false;
7598   }
7599 
7600   return true; // CC didn't match.
7601 }
7602 
7603 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
7604                          CCValAssign::LocInfo LocInfo,
7605                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
7606 
7607   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
7608     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
7609     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
7610     static const MCPhysReg GPRList[] = {
7611         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
7612         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
7613     if (unsigned Reg = State.AllocateReg(GPRList)) {
7614       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7615       return false;
7616     }
7617   }
7618 
7619   if (LocVT == MVT::f32) {
7620     // Pass in STG registers: F1, ..., F6
7621     //                        fs0 ... fs5
7622     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
7623                                           RISCV::F18_F, RISCV::F19_F,
7624                                           RISCV::F20_F, RISCV::F21_F};
7625     if (unsigned Reg = State.AllocateReg(FPR32List)) {
7626       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7627       return false;
7628     }
7629   }
7630 
7631   if (LocVT == MVT::f64) {
7632     // Pass in STG registers: D1, ..., D6
7633     //                        fs6 ... fs11
7634     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
7635                                           RISCV::F24_D, RISCV::F25_D,
7636                                           RISCV::F26_D, RISCV::F27_D};
7637     if (unsigned Reg = State.AllocateReg(FPR64List)) {
7638       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
7639       return false;
7640     }
7641   }
7642 
7643   report_fatal_error("No registers left in GHC calling convention");
7644   return true;
7645 }
7646 
7647 // Transform physical registers into virtual registers.
7648 SDValue RISCVTargetLowering::LowerFormalArguments(
7649     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
7650     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
7651     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7652 
7653   MachineFunction &MF = DAG.getMachineFunction();
7654 
7655   switch (CallConv) {
7656   default:
7657     report_fatal_error("Unsupported calling convention");
7658   case CallingConv::C:
7659   case CallingConv::Fast:
7660     break;
7661   case CallingConv::GHC:
7662     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
7663         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
7664       report_fatal_error(
7665         "GHC calling convention requires the F and D instruction set extensions");
7666   }
7667 
7668   const Function &Func = MF.getFunction();
7669   if (Func.hasFnAttribute("interrupt")) {
7670     if (!Func.arg_empty())
7671       report_fatal_error(
7672         "Functions with the interrupt attribute cannot have arguments!");
7673 
7674     StringRef Kind =
7675       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
7676 
7677     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
7678       report_fatal_error(
7679         "Function interrupt attribute argument not supported!");
7680   }
7681 
7682   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7683   MVT XLenVT = Subtarget.getXLenVT();
7684   unsigned XLenInBytes = Subtarget.getXLen() / 8;
7685   // Used with vargs to acumulate store chains.
7686   std::vector<SDValue> OutChains;
7687 
7688   // Assign locations to all of the incoming arguments.
7689   SmallVector<CCValAssign, 16> ArgLocs;
7690   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
7691 
7692   if (CallConv == CallingConv::GHC)
7693     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
7694   else
7695     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
7696                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
7697                                                    : CC_RISCV);
7698 
7699   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
7700     CCValAssign &VA = ArgLocs[i];
7701     SDValue ArgValue;
7702     // Passing f64 on RV32D with a soft float ABI must be handled as a special
7703     // case.
7704     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
7705       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
7706     else if (VA.isRegLoc())
7707       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
7708     else
7709       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
7710 
7711     if (VA.getLocInfo() == CCValAssign::Indirect) {
7712       // If the original argument was split and passed by reference (e.g. i128
7713       // on RV32), we need to load all parts of it here (using the same
7714       // address). Vectors may be partly split to registers and partly to the
7715       // stack, in which case the base address is partly offset and subsequent
7716       // stores are relative to that.
7717       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
7718                                    MachinePointerInfo()));
7719       unsigned ArgIndex = Ins[i].OrigArgIndex;
7720       unsigned ArgPartOffset = Ins[i].PartOffset;
7721       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
7722       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
7723         CCValAssign &PartVA = ArgLocs[i + 1];
7724         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
7725         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
7726         if (PartVA.getValVT().isScalableVector())
7727           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
7728         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
7729         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
7730                                      MachinePointerInfo()));
7731         ++i;
7732       }
7733       continue;
7734     }
7735     InVals.push_back(ArgValue);
7736   }
7737 
7738   if (IsVarArg) {
7739     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
7740     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
7741     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
7742     MachineFrameInfo &MFI = MF.getFrameInfo();
7743     MachineRegisterInfo &RegInfo = MF.getRegInfo();
7744     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
7745 
7746     // Offset of the first variable argument from stack pointer, and size of
7747     // the vararg save area. For now, the varargs save area is either zero or
7748     // large enough to hold a0-a7.
7749     int VaArgOffset, VarArgsSaveSize;
7750 
7751     // If all registers are allocated, then all varargs must be passed on the
7752     // stack and we don't need to save any argregs.
7753     if (ArgRegs.size() == Idx) {
7754       VaArgOffset = CCInfo.getNextStackOffset();
7755       VarArgsSaveSize = 0;
7756     } else {
7757       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
7758       VaArgOffset = -VarArgsSaveSize;
7759     }
7760 
7761     // Record the frame index of the first variable argument
7762     // which is a value necessary to VASTART.
7763     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
7764     RVFI->setVarArgsFrameIndex(FI);
7765 
7766     // If saving an odd number of registers then create an extra stack slot to
7767     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
7768     // offsets to even-numbered registered remain 2*XLEN-aligned.
7769     if (Idx % 2) {
7770       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
7771       VarArgsSaveSize += XLenInBytes;
7772     }
7773 
7774     // Copy the integer registers that may have been used for passing varargs
7775     // to the vararg save area.
7776     for (unsigned I = Idx; I < ArgRegs.size();
7777          ++I, VaArgOffset += XLenInBytes) {
7778       const Register Reg = RegInfo.createVirtualRegister(RC);
7779       RegInfo.addLiveIn(ArgRegs[I], Reg);
7780       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
7781       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
7782       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
7783       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
7784                                    MachinePointerInfo::getFixedStack(MF, FI));
7785       cast<StoreSDNode>(Store.getNode())
7786           ->getMemOperand()
7787           ->setValue((Value *)nullptr);
7788       OutChains.push_back(Store);
7789     }
7790     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
7791   }
7792 
7793   // All stores are grouped in one node to allow the matching between
7794   // the size of Ins and InVals. This only happens for vararg functions.
7795   if (!OutChains.empty()) {
7796     OutChains.push_back(Chain);
7797     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
7798   }
7799 
7800   return Chain;
7801 }
7802 
7803 /// isEligibleForTailCallOptimization - Check whether the call is eligible
7804 /// for tail call optimization.
7805 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
7806 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
7807     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
7808     const SmallVector<CCValAssign, 16> &ArgLocs) const {
7809 
7810   auto &Callee = CLI.Callee;
7811   auto CalleeCC = CLI.CallConv;
7812   auto &Outs = CLI.Outs;
7813   auto &Caller = MF.getFunction();
7814   auto CallerCC = Caller.getCallingConv();
7815 
7816   // Exception-handling functions need a special set of instructions to
7817   // indicate a return to the hardware. Tail-calling another function would
7818   // probably break this.
7819   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
7820   // should be expanded as new function attributes are introduced.
7821   if (Caller.hasFnAttribute("interrupt"))
7822     return false;
7823 
7824   // Do not tail call opt if the stack is used to pass parameters.
7825   if (CCInfo.getNextStackOffset() != 0)
7826     return false;
7827 
7828   // Do not tail call opt if any parameters need to be passed indirectly.
7829   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
7830   // passed indirectly. So the address of the value will be passed in a
7831   // register, or if not available, then the address is put on the stack. In
7832   // order to pass indirectly, space on the stack often needs to be allocated
7833   // in order to store the value. In this case the CCInfo.getNextStackOffset()
7834   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
7835   // are passed CCValAssign::Indirect.
7836   for (auto &VA : ArgLocs)
7837     if (VA.getLocInfo() == CCValAssign::Indirect)
7838       return false;
7839 
7840   // Do not tail call opt if either caller or callee uses struct return
7841   // semantics.
7842   auto IsCallerStructRet = Caller.hasStructRetAttr();
7843   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
7844   if (IsCallerStructRet || IsCalleeStructRet)
7845     return false;
7846 
7847   // Externally-defined functions with weak linkage should not be
7848   // tail-called. The behaviour of branch instructions in this situation (as
7849   // used for tail calls) is implementation-defined, so we cannot rely on the
7850   // linker replacing the tail call with a return.
7851   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
7852     const GlobalValue *GV = G->getGlobal();
7853     if (GV->hasExternalWeakLinkage())
7854       return false;
7855   }
7856 
7857   // The callee has to preserve all registers the caller needs to preserve.
7858   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
7859   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
7860   if (CalleeCC != CallerCC) {
7861     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
7862     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
7863       return false;
7864   }
7865 
7866   // Byval parameters hand the function a pointer directly into the stack area
7867   // we want to reuse during a tail call. Working around this *is* possible
7868   // but less efficient and uglier in LowerCall.
7869   for (auto &Arg : Outs)
7870     if (Arg.Flags.isByVal())
7871       return false;
7872 
7873   return true;
7874 }
7875 
7876 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
7877   return DAG.getDataLayout().getPrefTypeAlign(
7878       VT.getTypeForEVT(*DAG.getContext()));
7879 }
7880 
7881 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
7882 // and output parameter nodes.
7883 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
7884                                        SmallVectorImpl<SDValue> &InVals) const {
7885   SelectionDAG &DAG = CLI.DAG;
7886   SDLoc &DL = CLI.DL;
7887   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
7888   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
7889   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
7890   SDValue Chain = CLI.Chain;
7891   SDValue Callee = CLI.Callee;
7892   bool &IsTailCall = CLI.IsTailCall;
7893   CallingConv::ID CallConv = CLI.CallConv;
7894   bool IsVarArg = CLI.IsVarArg;
7895   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7896   MVT XLenVT = Subtarget.getXLenVT();
7897 
7898   MachineFunction &MF = DAG.getMachineFunction();
7899 
7900   // Analyze the operands of the call, assigning locations to each operand.
7901   SmallVector<CCValAssign, 16> ArgLocs;
7902   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
7903 
7904   if (CallConv == CallingConv::GHC)
7905     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
7906   else
7907     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
7908                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
7909                                                     : CC_RISCV);
7910 
7911   // Check if it's really possible to do a tail call.
7912   if (IsTailCall)
7913     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
7914 
7915   if (IsTailCall)
7916     ++NumTailCalls;
7917   else if (CLI.CB && CLI.CB->isMustTailCall())
7918     report_fatal_error("failed to perform tail call elimination on a call "
7919                        "site marked musttail");
7920 
7921   // Get a count of how many bytes are to be pushed on the stack.
7922   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
7923 
7924   // Create local copies for byval args
7925   SmallVector<SDValue, 8> ByValArgs;
7926   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
7927     ISD::ArgFlagsTy Flags = Outs[i].Flags;
7928     if (!Flags.isByVal())
7929       continue;
7930 
7931     SDValue Arg = OutVals[i];
7932     unsigned Size = Flags.getByValSize();
7933     Align Alignment = Flags.getNonZeroByValAlign();
7934 
7935     int FI =
7936         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
7937     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
7938     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
7939 
7940     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
7941                           /*IsVolatile=*/false,
7942                           /*AlwaysInline=*/false, IsTailCall,
7943                           MachinePointerInfo(), MachinePointerInfo());
7944     ByValArgs.push_back(FIPtr);
7945   }
7946 
7947   if (!IsTailCall)
7948     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
7949 
7950   // Copy argument values to their designated locations.
7951   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
7952   SmallVector<SDValue, 8> MemOpChains;
7953   SDValue StackPtr;
7954   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
7955     CCValAssign &VA = ArgLocs[i];
7956     SDValue ArgValue = OutVals[i];
7957     ISD::ArgFlagsTy Flags = Outs[i].Flags;
7958 
7959     // Handle passing f64 on RV32D with a soft float ABI as a special case.
7960     bool IsF64OnRV32DSoftABI =
7961         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
7962     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
7963       SDValue SplitF64 = DAG.getNode(
7964           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
7965       SDValue Lo = SplitF64.getValue(0);
7966       SDValue Hi = SplitF64.getValue(1);
7967 
7968       Register RegLo = VA.getLocReg();
7969       RegsToPass.push_back(std::make_pair(RegLo, Lo));
7970 
7971       if (RegLo == RISCV::X17) {
7972         // Second half of f64 is passed on the stack.
7973         // Work out the address of the stack slot.
7974         if (!StackPtr.getNode())
7975           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
7976         // Emit the store.
7977         MemOpChains.push_back(
7978             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
7979       } else {
7980         // Second half of f64 is passed in another GPR.
7981         assert(RegLo < RISCV::X31 && "Invalid register pair");
7982         Register RegHigh = RegLo + 1;
7983         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
7984       }
7985       continue;
7986     }
7987 
7988     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
7989     // as any other MemLoc.
7990 
7991     // Promote the value if needed.
7992     // For now, only handle fully promoted and indirect arguments.
7993     if (VA.getLocInfo() == CCValAssign::Indirect) {
7994       // Store the argument in a stack slot and pass its address.
7995       Align StackAlign =
7996           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
7997                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
7998       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
7999       // If the original argument was split (e.g. i128), we need
8000       // to store the required parts of it here (and pass just one address).
8001       // Vectors may be partly split to registers and partly to the stack, in
8002       // which case the base address is partly offset and subsequent stores are
8003       // relative to that.
8004       unsigned ArgIndex = Outs[i].OrigArgIndex;
8005       unsigned ArgPartOffset = Outs[i].PartOffset;
8006       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
8007       // Calculate the total size to store. We don't have access to what we're
8008       // actually storing other than performing the loop and collecting the
8009       // info.
8010       SmallVector<std::pair<SDValue, SDValue>> Parts;
8011       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
8012         SDValue PartValue = OutVals[i + 1];
8013         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
8014         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
8015         EVT PartVT = PartValue.getValueType();
8016         if (PartVT.isScalableVector())
8017           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
8018         StoredSize += PartVT.getStoreSize();
8019         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
8020         Parts.push_back(std::make_pair(PartValue, Offset));
8021         ++i;
8022       }
8023       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
8024       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
8025       MemOpChains.push_back(
8026           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
8027                        MachinePointerInfo::getFixedStack(MF, FI)));
8028       for (const auto &Part : Parts) {
8029         SDValue PartValue = Part.first;
8030         SDValue PartOffset = Part.second;
8031         SDValue Address =
8032             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
8033         MemOpChains.push_back(
8034             DAG.getStore(Chain, DL, PartValue, Address,
8035                          MachinePointerInfo::getFixedStack(MF, FI)));
8036       }
8037       ArgValue = SpillSlot;
8038     } else {
8039       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
8040     }
8041 
8042     // Use local copy if it is a byval arg.
8043     if (Flags.isByVal())
8044       ArgValue = ByValArgs[j++];
8045 
8046     if (VA.isRegLoc()) {
8047       // Queue up the argument copies and emit them at the end.
8048       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
8049     } else {
8050       assert(VA.isMemLoc() && "Argument not register or memory");
8051       assert(!IsTailCall && "Tail call not allowed if stack is used "
8052                             "for passing parameters");
8053 
8054       // Work out the address of the stack slot.
8055       if (!StackPtr.getNode())
8056         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
8057       SDValue Address =
8058           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
8059                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
8060 
8061       // Emit the store.
8062       MemOpChains.push_back(
8063           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
8064     }
8065   }
8066 
8067   // Join the stores, which are independent of one another.
8068   if (!MemOpChains.empty())
8069     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
8070 
8071   SDValue Glue;
8072 
8073   // Build a sequence of copy-to-reg nodes, chained and glued together.
8074   for (auto &Reg : RegsToPass) {
8075     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
8076     Glue = Chain.getValue(1);
8077   }
8078 
8079   // Validate that none of the argument registers have been marked as
8080   // reserved, if so report an error. Do the same for the return address if this
8081   // is not a tailcall.
8082   validateCCReservedRegs(RegsToPass, MF);
8083   if (!IsTailCall &&
8084       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
8085     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8086         MF.getFunction(),
8087         "Return address register required, but has been reserved."});
8088 
8089   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
8090   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
8091   // split it and then direct call can be matched by PseudoCALL.
8092   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
8093     const GlobalValue *GV = S->getGlobal();
8094 
8095     unsigned OpFlags = RISCVII::MO_CALL;
8096     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
8097       OpFlags = RISCVII::MO_PLT;
8098 
8099     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
8100   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
8101     unsigned OpFlags = RISCVII::MO_CALL;
8102 
8103     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
8104                                                  nullptr))
8105       OpFlags = RISCVII::MO_PLT;
8106 
8107     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
8108   }
8109 
8110   // The first call operand is the chain and the second is the target address.
8111   SmallVector<SDValue, 8> Ops;
8112   Ops.push_back(Chain);
8113   Ops.push_back(Callee);
8114 
8115   // Add argument registers to the end of the list so that they are
8116   // known live into the call.
8117   for (auto &Reg : RegsToPass)
8118     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
8119 
8120   if (!IsTailCall) {
8121     // Add a register mask operand representing the call-preserved registers.
8122     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
8123     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
8124     assert(Mask && "Missing call preserved mask for calling convention");
8125     Ops.push_back(DAG.getRegisterMask(Mask));
8126   }
8127 
8128   // Glue the call to the argument copies, if any.
8129   if (Glue.getNode())
8130     Ops.push_back(Glue);
8131 
8132   // Emit the call.
8133   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8134 
8135   if (IsTailCall) {
8136     MF.getFrameInfo().setHasTailCall();
8137     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
8138   }
8139 
8140   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
8141   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
8142   Glue = Chain.getValue(1);
8143 
8144   // Mark the end of the call, which is glued to the call itself.
8145   Chain = DAG.getCALLSEQ_END(Chain,
8146                              DAG.getConstant(NumBytes, DL, PtrVT, true),
8147                              DAG.getConstant(0, DL, PtrVT, true),
8148                              Glue, DL);
8149   Glue = Chain.getValue(1);
8150 
8151   // Assign locations to each value returned by this call.
8152   SmallVector<CCValAssign, 16> RVLocs;
8153   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
8154   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
8155 
8156   // Copy all of the result registers out of their specified physreg.
8157   for (auto &VA : RVLocs) {
8158     // Copy the value out
8159     SDValue RetValue =
8160         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
8161     // Glue the RetValue to the end of the call sequence
8162     Chain = RetValue.getValue(1);
8163     Glue = RetValue.getValue(2);
8164 
8165     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
8166       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
8167       SDValue RetValue2 =
8168           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
8169       Chain = RetValue2.getValue(1);
8170       Glue = RetValue2.getValue(2);
8171       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
8172                              RetValue2);
8173     }
8174 
8175     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
8176 
8177     InVals.push_back(RetValue);
8178   }
8179 
8180   return Chain;
8181 }
8182 
8183 bool RISCVTargetLowering::CanLowerReturn(
8184     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
8185     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
8186   SmallVector<CCValAssign, 16> RVLocs;
8187   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
8188 
8189   Optional<unsigned> FirstMaskArgument;
8190   if (Subtarget.hasStdExtV())
8191     FirstMaskArgument = preAssignMask(Outs);
8192 
8193   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
8194     MVT VT = Outs[i].VT;
8195     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
8196     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
8197     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
8198                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
8199                  *this, FirstMaskArgument))
8200       return false;
8201   }
8202   return true;
8203 }
8204 
8205 SDValue
8206 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
8207                                  bool IsVarArg,
8208                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
8209                                  const SmallVectorImpl<SDValue> &OutVals,
8210                                  const SDLoc &DL, SelectionDAG &DAG) const {
8211   const MachineFunction &MF = DAG.getMachineFunction();
8212   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
8213 
8214   // Stores the assignment of the return value to a location.
8215   SmallVector<CCValAssign, 16> RVLocs;
8216 
8217   // Info about the registers and stack slot.
8218   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
8219                  *DAG.getContext());
8220 
8221   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
8222                     nullptr, CC_RISCV);
8223 
8224   if (CallConv == CallingConv::GHC && !RVLocs.empty())
8225     report_fatal_error("GHC functions return void only");
8226 
8227   SDValue Glue;
8228   SmallVector<SDValue, 4> RetOps(1, Chain);
8229 
8230   // Copy the result values into the output registers.
8231   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
8232     SDValue Val = OutVals[i];
8233     CCValAssign &VA = RVLocs[i];
8234     assert(VA.isRegLoc() && "Can only return in registers!");
8235 
8236     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
8237       // Handle returning f64 on RV32D with a soft float ABI.
8238       assert(VA.isRegLoc() && "Expected return via registers");
8239       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
8240                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
8241       SDValue Lo = SplitF64.getValue(0);
8242       SDValue Hi = SplitF64.getValue(1);
8243       Register RegLo = VA.getLocReg();
8244       assert(RegLo < RISCV::X31 && "Invalid register pair");
8245       Register RegHi = RegLo + 1;
8246 
8247       if (STI.isRegisterReservedByUser(RegLo) ||
8248           STI.isRegisterReservedByUser(RegHi))
8249         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8250             MF.getFunction(),
8251             "Return value register required, but has been reserved."});
8252 
8253       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
8254       Glue = Chain.getValue(1);
8255       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
8256       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
8257       Glue = Chain.getValue(1);
8258       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
8259     } else {
8260       // Handle a 'normal' return.
8261       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
8262       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
8263 
8264       if (STI.isRegisterReservedByUser(VA.getLocReg()))
8265         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
8266             MF.getFunction(),
8267             "Return value register required, but has been reserved."});
8268 
8269       // Guarantee that all emitted copies are stuck together.
8270       Glue = Chain.getValue(1);
8271       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
8272     }
8273   }
8274 
8275   RetOps[0] = Chain; // Update chain.
8276 
8277   // Add the glue node if we have it.
8278   if (Glue.getNode()) {
8279     RetOps.push_back(Glue);
8280   }
8281 
8282   unsigned RetOpc = RISCVISD::RET_FLAG;
8283   // Interrupt service routines use different return instructions.
8284   const Function &Func = DAG.getMachineFunction().getFunction();
8285   if (Func.hasFnAttribute("interrupt")) {
8286     if (!Func.getReturnType()->isVoidTy())
8287       report_fatal_error(
8288           "Functions with the interrupt attribute must have void return type!");
8289 
8290     MachineFunction &MF = DAG.getMachineFunction();
8291     StringRef Kind =
8292       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
8293 
8294     if (Kind == "user")
8295       RetOpc = RISCVISD::URET_FLAG;
8296     else if (Kind == "supervisor")
8297       RetOpc = RISCVISD::SRET_FLAG;
8298     else
8299       RetOpc = RISCVISD::MRET_FLAG;
8300   }
8301 
8302   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
8303 }
8304 
8305 void RISCVTargetLowering::validateCCReservedRegs(
8306     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
8307     MachineFunction &MF) const {
8308   const Function &F = MF.getFunction();
8309   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
8310 
8311   if (llvm::any_of(Regs, [&STI](auto Reg) {
8312         return STI.isRegisterReservedByUser(Reg.first);
8313       }))
8314     F.getContext().diagnose(DiagnosticInfoUnsupported{
8315         F, "Argument register required, but has been reserved."});
8316 }
8317 
8318 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
8319   return CI->isTailCall();
8320 }
8321 
8322 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
8323 #define NODE_NAME_CASE(NODE)                                                   \
8324   case RISCVISD::NODE:                                                         \
8325     return "RISCVISD::" #NODE;
8326   // clang-format off
8327   switch ((RISCVISD::NodeType)Opcode) {
8328   case RISCVISD::FIRST_NUMBER:
8329     break;
8330   NODE_NAME_CASE(RET_FLAG)
8331   NODE_NAME_CASE(URET_FLAG)
8332   NODE_NAME_CASE(SRET_FLAG)
8333   NODE_NAME_CASE(MRET_FLAG)
8334   NODE_NAME_CASE(CALL)
8335   NODE_NAME_CASE(SELECT_CC)
8336   NODE_NAME_CASE(BR_CC)
8337   NODE_NAME_CASE(BuildPairF64)
8338   NODE_NAME_CASE(SplitF64)
8339   NODE_NAME_CASE(TAIL)
8340   NODE_NAME_CASE(MULHSU)
8341   NODE_NAME_CASE(SLLW)
8342   NODE_NAME_CASE(SRAW)
8343   NODE_NAME_CASE(SRLW)
8344   NODE_NAME_CASE(DIVW)
8345   NODE_NAME_CASE(DIVUW)
8346   NODE_NAME_CASE(REMUW)
8347   NODE_NAME_CASE(ROLW)
8348   NODE_NAME_CASE(RORW)
8349   NODE_NAME_CASE(CLZW)
8350   NODE_NAME_CASE(CTZW)
8351   NODE_NAME_CASE(FSLW)
8352   NODE_NAME_CASE(FSRW)
8353   NODE_NAME_CASE(FSL)
8354   NODE_NAME_CASE(FSR)
8355   NODE_NAME_CASE(FMV_H_X)
8356   NODE_NAME_CASE(FMV_X_ANYEXTH)
8357   NODE_NAME_CASE(FMV_W_X_RV64)
8358   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
8359   NODE_NAME_CASE(FCVT_W_RV64)
8360   NODE_NAME_CASE(FCVT_WU_RV64)
8361   NODE_NAME_CASE(READ_CYCLE_WIDE)
8362   NODE_NAME_CASE(GREV)
8363   NODE_NAME_CASE(GREVW)
8364   NODE_NAME_CASE(GORC)
8365   NODE_NAME_CASE(GORCW)
8366   NODE_NAME_CASE(SHFL)
8367   NODE_NAME_CASE(SHFLW)
8368   NODE_NAME_CASE(UNSHFL)
8369   NODE_NAME_CASE(UNSHFLW)
8370   NODE_NAME_CASE(BCOMPRESS)
8371   NODE_NAME_CASE(BCOMPRESSW)
8372   NODE_NAME_CASE(BDECOMPRESS)
8373   NODE_NAME_CASE(BDECOMPRESSW)
8374   NODE_NAME_CASE(VMV_V_X_VL)
8375   NODE_NAME_CASE(VFMV_V_F_VL)
8376   NODE_NAME_CASE(VMV_X_S)
8377   NODE_NAME_CASE(VMV_S_X_VL)
8378   NODE_NAME_CASE(VFMV_S_F_VL)
8379   NODE_NAME_CASE(SPLAT_VECTOR_I64)
8380   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
8381   NODE_NAME_CASE(READ_VLENB)
8382   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
8383   NODE_NAME_CASE(VSLIDEUP_VL)
8384   NODE_NAME_CASE(VSLIDE1UP_VL)
8385   NODE_NAME_CASE(VSLIDEDOWN_VL)
8386   NODE_NAME_CASE(VSLIDE1DOWN_VL)
8387   NODE_NAME_CASE(VID_VL)
8388   NODE_NAME_CASE(VFNCVT_ROD_VL)
8389   NODE_NAME_CASE(VECREDUCE_ADD_VL)
8390   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
8391   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
8392   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
8393   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
8394   NODE_NAME_CASE(VECREDUCE_AND_VL)
8395   NODE_NAME_CASE(VECREDUCE_OR_VL)
8396   NODE_NAME_CASE(VECREDUCE_XOR_VL)
8397   NODE_NAME_CASE(VECREDUCE_FADD_VL)
8398   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
8399   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
8400   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
8401   NODE_NAME_CASE(ADD_VL)
8402   NODE_NAME_CASE(AND_VL)
8403   NODE_NAME_CASE(MUL_VL)
8404   NODE_NAME_CASE(OR_VL)
8405   NODE_NAME_CASE(SDIV_VL)
8406   NODE_NAME_CASE(SHL_VL)
8407   NODE_NAME_CASE(SREM_VL)
8408   NODE_NAME_CASE(SRA_VL)
8409   NODE_NAME_CASE(SRL_VL)
8410   NODE_NAME_CASE(SUB_VL)
8411   NODE_NAME_CASE(UDIV_VL)
8412   NODE_NAME_CASE(UREM_VL)
8413   NODE_NAME_CASE(XOR_VL)
8414   NODE_NAME_CASE(SADDSAT_VL)
8415   NODE_NAME_CASE(UADDSAT_VL)
8416   NODE_NAME_CASE(SSUBSAT_VL)
8417   NODE_NAME_CASE(USUBSAT_VL)
8418   NODE_NAME_CASE(FADD_VL)
8419   NODE_NAME_CASE(FSUB_VL)
8420   NODE_NAME_CASE(FMUL_VL)
8421   NODE_NAME_CASE(FDIV_VL)
8422   NODE_NAME_CASE(FNEG_VL)
8423   NODE_NAME_CASE(FABS_VL)
8424   NODE_NAME_CASE(FSQRT_VL)
8425   NODE_NAME_CASE(FMA_VL)
8426   NODE_NAME_CASE(FCOPYSIGN_VL)
8427   NODE_NAME_CASE(SMIN_VL)
8428   NODE_NAME_CASE(SMAX_VL)
8429   NODE_NAME_CASE(UMIN_VL)
8430   NODE_NAME_CASE(UMAX_VL)
8431   NODE_NAME_CASE(FMINNUM_VL)
8432   NODE_NAME_CASE(FMAXNUM_VL)
8433   NODE_NAME_CASE(MULHS_VL)
8434   NODE_NAME_CASE(MULHU_VL)
8435   NODE_NAME_CASE(FP_TO_SINT_VL)
8436   NODE_NAME_CASE(FP_TO_UINT_VL)
8437   NODE_NAME_CASE(SINT_TO_FP_VL)
8438   NODE_NAME_CASE(UINT_TO_FP_VL)
8439   NODE_NAME_CASE(FP_EXTEND_VL)
8440   NODE_NAME_CASE(FP_ROUND_VL)
8441   NODE_NAME_CASE(VWMUL_VL)
8442   NODE_NAME_CASE(VWMULU_VL)
8443   NODE_NAME_CASE(SETCC_VL)
8444   NODE_NAME_CASE(VSELECT_VL)
8445   NODE_NAME_CASE(VMAND_VL)
8446   NODE_NAME_CASE(VMOR_VL)
8447   NODE_NAME_CASE(VMXOR_VL)
8448   NODE_NAME_CASE(VMCLR_VL)
8449   NODE_NAME_CASE(VMSET_VL)
8450   NODE_NAME_CASE(VRGATHER_VX_VL)
8451   NODE_NAME_CASE(VRGATHER_VV_VL)
8452   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
8453   NODE_NAME_CASE(VSEXT_VL)
8454   NODE_NAME_CASE(VZEXT_VL)
8455   NODE_NAME_CASE(VPOPC_VL)
8456   NODE_NAME_CASE(VLE_VL)
8457   NODE_NAME_CASE(VSE_VL)
8458   NODE_NAME_CASE(READ_CSR)
8459   NODE_NAME_CASE(WRITE_CSR)
8460   NODE_NAME_CASE(SWAP_CSR)
8461   }
8462   // clang-format on
8463   return nullptr;
8464 #undef NODE_NAME_CASE
8465 }
8466 
8467 /// getConstraintType - Given a constraint letter, return the type of
8468 /// constraint it is for this target.
8469 RISCVTargetLowering::ConstraintType
8470 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
8471   if (Constraint.size() == 1) {
8472     switch (Constraint[0]) {
8473     default:
8474       break;
8475     case 'f':
8476     case 'v':
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   }
8488   return TargetLowering::getConstraintType(Constraint);
8489 }
8490 
8491 std::pair<unsigned, const TargetRegisterClass *>
8492 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
8493                                                   StringRef Constraint,
8494                                                   MVT VT) const {
8495   // First, see if this is a constraint that directly corresponds to a
8496   // RISCV register class.
8497   if (Constraint.size() == 1) {
8498     switch (Constraint[0]) {
8499     case 'r':
8500       return std::make_pair(0U, &RISCV::GPRRegClass);
8501     case 'f':
8502       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
8503         return std::make_pair(0U, &RISCV::FPR16RegClass);
8504       if (Subtarget.hasStdExtF() && VT == MVT::f32)
8505         return std::make_pair(0U, &RISCV::FPR32RegClass);
8506       if (Subtarget.hasStdExtD() && VT == MVT::f64)
8507         return std::make_pair(0U, &RISCV::FPR64RegClass);
8508       break;
8509     case 'v':
8510       for (const auto *RC :
8511            {&RISCV::VMRegClass, &RISCV::VRRegClass, &RISCV::VRM2RegClass,
8512             &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
8513         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
8514           return std::make_pair(0U, RC);
8515       }
8516       break;
8517     default:
8518       break;
8519     }
8520   }
8521 
8522   // Clang will correctly decode the usage of register name aliases into their
8523   // official names. However, other frontends like `rustc` do not. This allows
8524   // users of these frontends to use the ABI names for registers in LLVM-style
8525   // register constraints.
8526   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
8527                                .Case("{zero}", RISCV::X0)
8528                                .Case("{ra}", RISCV::X1)
8529                                .Case("{sp}", RISCV::X2)
8530                                .Case("{gp}", RISCV::X3)
8531                                .Case("{tp}", RISCV::X4)
8532                                .Case("{t0}", RISCV::X5)
8533                                .Case("{t1}", RISCV::X6)
8534                                .Case("{t2}", RISCV::X7)
8535                                .Cases("{s0}", "{fp}", RISCV::X8)
8536                                .Case("{s1}", RISCV::X9)
8537                                .Case("{a0}", RISCV::X10)
8538                                .Case("{a1}", RISCV::X11)
8539                                .Case("{a2}", RISCV::X12)
8540                                .Case("{a3}", RISCV::X13)
8541                                .Case("{a4}", RISCV::X14)
8542                                .Case("{a5}", RISCV::X15)
8543                                .Case("{a6}", RISCV::X16)
8544                                .Case("{a7}", RISCV::X17)
8545                                .Case("{s2}", RISCV::X18)
8546                                .Case("{s3}", RISCV::X19)
8547                                .Case("{s4}", RISCV::X20)
8548                                .Case("{s5}", RISCV::X21)
8549                                .Case("{s6}", RISCV::X22)
8550                                .Case("{s7}", RISCV::X23)
8551                                .Case("{s8}", RISCV::X24)
8552                                .Case("{s9}", RISCV::X25)
8553                                .Case("{s10}", RISCV::X26)
8554                                .Case("{s11}", RISCV::X27)
8555                                .Case("{t3}", RISCV::X28)
8556                                .Case("{t4}", RISCV::X29)
8557                                .Case("{t5}", RISCV::X30)
8558                                .Case("{t6}", RISCV::X31)
8559                                .Default(RISCV::NoRegister);
8560   if (XRegFromAlias != RISCV::NoRegister)
8561     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
8562 
8563   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
8564   // TableGen record rather than the AsmName to choose registers for InlineAsm
8565   // constraints, plus we want to match those names to the widest floating point
8566   // register type available, manually select floating point registers here.
8567   //
8568   // The second case is the ABI name of the register, so that frontends can also
8569   // use the ABI names in register constraint lists.
8570   if (Subtarget.hasStdExtF()) {
8571     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
8572                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
8573                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
8574                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
8575                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
8576                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
8577                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
8578                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
8579                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
8580                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
8581                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
8582                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
8583                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
8584                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
8585                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
8586                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
8587                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
8588                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
8589                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
8590                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
8591                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
8592                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
8593                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
8594                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
8595                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
8596                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
8597                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
8598                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
8599                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
8600                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
8601                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
8602                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
8603                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
8604                         .Default(RISCV::NoRegister);
8605     if (FReg != RISCV::NoRegister) {
8606       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
8607       if (Subtarget.hasStdExtD()) {
8608         unsigned RegNo = FReg - RISCV::F0_F;
8609         unsigned DReg = RISCV::F0_D + RegNo;
8610         return std::make_pair(DReg, &RISCV::FPR64RegClass);
8611       }
8612       return std::make_pair(FReg, &RISCV::FPR32RegClass);
8613     }
8614   }
8615 
8616   if (Subtarget.hasStdExtV()) {
8617     Register VReg = StringSwitch<Register>(Constraint.lower())
8618                         .Case("{v0}", RISCV::V0)
8619                         .Case("{v1}", RISCV::V1)
8620                         .Case("{v2}", RISCV::V2)
8621                         .Case("{v3}", RISCV::V3)
8622                         .Case("{v4}", RISCV::V4)
8623                         .Case("{v5}", RISCV::V5)
8624                         .Case("{v6}", RISCV::V6)
8625                         .Case("{v7}", RISCV::V7)
8626                         .Case("{v8}", RISCV::V8)
8627                         .Case("{v9}", RISCV::V9)
8628                         .Case("{v10}", RISCV::V10)
8629                         .Case("{v11}", RISCV::V11)
8630                         .Case("{v12}", RISCV::V12)
8631                         .Case("{v13}", RISCV::V13)
8632                         .Case("{v14}", RISCV::V14)
8633                         .Case("{v15}", RISCV::V15)
8634                         .Case("{v16}", RISCV::V16)
8635                         .Case("{v17}", RISCV::V17)
8636                         .Case("{v18}", RISCV::V18)
8637                         .Case("{v19}", RISCV::V19)
8638                         .Case("{v20}", RISCV::V20)
8639                         .Case("{v21}", RISCV::V21)
8640                         .Case("{v22}", RISCV::V22)
8641                         .Case("{v23}", RISCV::V23)
8642                         .Case("{v24}", RISCV::V24)
8643                         .Case("{v25}", RISCV::V25)
8644                         .Case("{v26}", RISCV::V26)
8645                         .Case("{v27}", RISCV::V27)
8646                         .Case("{v28}", RISCV::V28)
8647                         .Case("{v29}", RISCV::V29)
8648                         .Case("{v30}", RISCV::V30)
8649                         .Case("{v31}", RISCV::V31)
8650                         .Default(RISCV::NoRegister);
8651     if (VReg != RISCV::NoRegister) {
8652       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
8653         return std::make_pair(VReg, &RISCV::VMRegClass);
8654       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
8655         return std::make_pair(VReg, &RISCV::VRRegClass);
8656       for (const auto *RC :
8657            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
8658         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
8659           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
8660           return std::make_pair(VReg, RC);
8661         }
8662       }
8663     }
8664   }
8665 
8666   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
8667 }
8668 
8669 unsigned
8670 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
8671   // Currently only support length 1 constraints.
8672   if (ConstraintCode.size() == 1) {
8673     switch (ConstraintCode[0]) {
8674     case 'A':
8675       return InlineAsm::Constraint_A;
8676     default:
8677       break;
8678     }
8679   }
8680 
8681   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
8682 }
8683 
8684 void RISCVTargetLowering::LowerAsmOperandForConstraint(
8685     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
8686     SelectionDAG &DAG) const {
8687   // Currently only support length 1 constraints.
8688   if (Constraint.length() == 1) {
8689     switch (Constraint[0]) {
8690     case 'I':
8691       // Validate & create a 12-bit signed immediate operand.
8692       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
8693         uint64_t CVal = C->getSExtValue();
8694         if (isInt<12>(CVal))
8695           Ops.push_back(
8696               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
8697       }
8698       return;
8699     case 'J':
8700       // Validate & create an integer zero operand.
8701       if (auto *C = dyn_cast<ConstantSDNode>(Op))
8702         if (C->getZExtValue() == 0)
8703           Ops.push_back(
8704               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
8705       return;
8706     case 'K':
8707       // Validate & create a 5-bit unsigned immediate operand.
8708       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
8709         uint64_t CVal = C->getZExtValue();
8710         if (isUInt<5>(CVal))
8711           Ops.push_back(
8712               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
8713       }
8714       return;
8715     case 'S':
8716       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
8717         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
8718                                                  GA->getValueType(0)));
8719       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
8720         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
8721                                                 BA->getValueType(0)));
8722       }
8723       return;
8724     default:
8725       break;
8726     }
8727   }
8728   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8729 }
8730 
8731 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
8732                                                    Instruction *Inst,
8733                                                    AtomicOrdering Ord) const {
8734   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
8735     return Builder.CreateFence(Ord);
8736   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
8737     return Builder.CreateFence(AtomicOrdering::Release);
8738   return nullptr;
8739 }
8740 
8741 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
8742                                                     Instruction *Inst,
8743                                                     AtomicOrdering Ord) const {
8744   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
8745     return Builder.CreateFence(AtomicOrdering::Acquire);
8746   return nullptr;
8747 }
8748 
8749 TargetLowering::AtomicExpansionKind
8750 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
8751   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
8752   // point operations can't be used in an lr/sc sequence without breaking the
8753   // forward-progress guarantee.
8754   if (AI->isFloatingPointOperation())
8755     return AtomicExpansionKind::CmpXChg;
8756 
8757   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
8758   if (Size == 8 || Size == 16)
8759     return AtomicExpansionKind::MaskedIntrinsic;
8760   return AtomicExpansionKind::None;
8761 }
8762 
8763 static Intrinsic::ID
8764 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
8765   if (XLen == 32) {
8766     switch (BinOp) {
8767     default:
8768       llvm_unreachable("Unexpected AtomicRMW BinOp");
8769     case AtomicRMWInst::Xchg:
8770       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
8771     case AtomicRMWInst::Add:
8772       return Intrinsic::riscv_masked_atomicrmw_add_i32;
8773     case AtomicRMWInst::Sub:
8774       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
8775     case AtomicRMWInst::Nand:
8776       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
8777     case AtomicRMWInst::Max:
8778       return Intrinsic::riscv_masked_atomicrmw_max_i32;
8779     case AtomicRMWInst::Min:
8780       return Intrinsic::riscv_masked_atomicrmw_min_i32;
8781     case AtomicRMWInst::UMax:
8782       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
8783     case AtomicRMWInst::UMin:
8784       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
8785     }
8786   }
8787 
8788   if (XLen == 64) {
8789     switch (BinOp) {
8790     default:
8791       llvm_unreachable("Unexpected AtomicRMW BinOp");
8792     case AtomicRMWInst::Xchg:
8793       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
8794     case AtomicRMWInst::Add:
8795       return Intrinsic::riscv_masked_atomicrmw_add_i64;
8796     case AtomicRMWInst::Sub:
8797       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
8798     case AtomicRMWInst::Nand:
8799       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
8800     case AtomicRMWInst::Max:
8801       return Intrinsic::riscv_masked_atomicrmw_max_i64;
8802     case AtomicRMWInst::Min:
8803       return Intrinsic::riscv_masked_atomicrmw_min_i64;
8804     case AtomicRMWInst::UMax:
8805       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
8806     case AtomicRMWInst::UMin:
8807       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
8808     }
8809   }
8810 
8811   llvm_unreachable("Unexpected XLen\n");
8812 }
8813 
8814 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
8815     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
8816     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
8817   unsigned XLen = Subtarget.getXLen();
8818   Value *Ordering =
8819       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
8820   Type *Tys[] = {AlignedAddr->getType()};
8821   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
8822       AI->getModule(),
8823       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
8824 
8825   if (XLen == 64) {
8826     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
8827     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
8828     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
8829   }
8830 
8831   Value *Result;
8832 
8833   // Must pass the shift amount needed to sign extend the loaded value prior
8834   // to performing a signed comparison for min/max. ShiftAmt is the number of
8835   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
8836   // is the number of bits to left+right shift the value in order to
8837   // sign-extend.
8838   if (AI->getOperation() == AtomicRMWInst::Min ||
8839       AI->getOperation() == AtomicRMWInst::Max) {
8840     const DataLayout &DL = AI->getModule()->getDataLayout();
8841     unsigned ValWidth =
8842         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
8843     Value *SextShamt =
8844         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
8845     Result = Builder.CreateCall(LrwOpScwLoop,
8846                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
8847   } else {
8848     Result =
8849         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
8850   }
8851 
8852   if (XLen == 64)
8853     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
8854   return Result;
8855 }
8856 
8857 TargetLowering::AtomicExpansionKind
8858 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
8859     AtomicCmpXchgInst *CI) const {
8860   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
8861   if (Size == 8 || Size == 16)
8862     return AtomicExpansionKind::MaskedIntrinsic;
8863   return AtomicExpansionKind::None;
8864 }
8865 
8866 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
8867     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
8868     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
8869   unsigned XLen = Subtarget.getXLen();
8870   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
8871   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
8872   if (XLen == 64) {
8873     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
8874     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
8875     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
8876     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
8877   }
8878   Type *Tys[] = {AlignedAddr->getType()};
8879   Function *MaskedCmpXchg =
8880       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
8881   Value *Result = Builder.CreateCall(
8882       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
8883   if (XLen == 64)
8884     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
8885   return Result;
8886 }
8887 
8888 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
8889   return false;
8890 }
8891 
8892 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
8893                                                      EVT VT) const {
8894   VT = VT.getScalarType();
8895 
8896   if (!VT.isSimple())
8897     return false;
8898 
8899   switch (VT.getSimpleVT().SimpleTy) {
8900   case MVT::f16:
8901     return Subtarget.hasStdExtZfh();
8902   case MVT::f32:
8903     return Subtarget.hasStdExtF();
8904   case MVT::f64:
8905     return Subtarget.hasStdExtD();
8906   default:
8907     break;
8908   }
8909 
8910   return false;
8911 }
8912 
8913 Register RISCVTargetLowering::getExceptionPointerRegister(
8914     const Constant *PersonalityFn) const {
8915   return RISCV::X10;
8916 }
8917 
8918 Register RISCVTargetLowering::getExceptionSelectorRegister(
8919     const Constant *PersonalityFn) const {
8920   return RISCV::X11;
8921 }
8922 
8923 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
8924   // Return false to suppress the unnecessary extensions if the LibCall
8925   // arguments or return value is f32 type for LP64 ABI.
8926   RISCVABI::ABI ABI = Subtarget.getTargetABI();
8927   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
8928     return false;
8929 
8930   return true;
8931 }
8932 
8933 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
8934   if (Subtarget.is64Bit() && Type == MVT::i32)
8935     return true;
8936 
8937   return IsSigned;
8938 }
8939 
8940 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
8941                                                  SDValue C) const {
8942   // Check integral scalar types.
8943   if (VT.isScalarInteger()) {
8944     // Omit the optimization if the sub target has the M extension and the data
8945     // size exceeds XLen.
8946     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
8947       return false;
8948     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
8949       // Break the MUL to a SLLI and an ADD/SUB.
8950       const APInt &Imm = ConstNode->getAPIntValue();
8951       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
8952           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
8953         return true;
8954       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
8955       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
8956           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
8957            (Imm - 8).isPowerOf2()))
8958         return true;
8959       // Omit the following optimization if the sub target has the M extension
8960       // and the data size >= XLen.
8961       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
8962         return false;
8963       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
8964       // a pair of LUI/ADDI.
8965       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
8966         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
8967         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
8968             (1 - ImmS).isPowerOf2())
8969         return true;
8970       }
8971     }
8972   }
8973 
8974   return false;
8975 }
8976 
8977 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
8978     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
8979     bool *Fast) const {
8980   if (!VT.isVector())
8981     return false;
8982 
8983   EVT ElemVT = VT.getVectorElementType();
8984   if (Alignment >= ElemVT.getStoreSize()) {
8985     if (Fast)
8986       *Fast = true;
8987     return true;
8988   }
8989 
8990   return false;
8991 }
8992 
8993 bool RISCVTargetLowering::splitValueIntoRegisterParts(
8994     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
8995     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
8996   bool IsABIRegCopy = CC.hasValue();
8997   EVT ValueVT = Val.getValueType();
8998   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
8999     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
9000     // and cast to f32.
9001     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
9002     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
9003     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
9004                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
9005     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
9006     Parts[0] = Val;
9007     return true;
9008   }
9009 
9010   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9011     LLVMContext &Context = *DAG.getContext();
9012     EVT ValueEltVT = ValueVT.getVectorElementType();
9013     EVT PartEltVT = PartVT.getVectorElementType();
9014     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9015     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9016     if (PartVTBitSize % ValueVTBitSize == 0) {
9017       // If the element types are different, bitcast to the same element type of
9018       // PartVT first.
9019       if (ValueEltVT != PartEltVT) {
9020         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9021         assert(Count != 0 && "The number of element should not be zero.");
9022         EVT SameEltTypeVT =
9023             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9024         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
9025       }
9026       Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
9027                         Val, DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9028       Parts[0] = Val;
9029       return true;
9030     }
9031   }
9032   return false;
9033 }
9034 
9035 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
9036     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
9037     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
9038   bool IsABIRegCopy = CC.hasValue();
9039   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
9040     SDValue Val = Parts[0];
9041 
9042     // Cast the f32 to i32, truncate to i16, and cast back to f16.
9043     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
9044     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
9045     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
9046     return Val;
9047   }
9048 
9049   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
9050     LLVMContext &Context = *DAG.getContext();
9051     SDValue Val = Parts[0];
9052     EVT ValueEltVT = ValueVT.getVectorElementType();
9053     EVT PartEltVT = PartVT.getVectorElementType();
9054     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
9055     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
9056     if (PartVTBitSize % ValueVTBitSize == 0) {
9057       EVT SameEltTypeVT = ValueVT;
9058       // If the element types are different, convert it to the same element type
9059       // of PartVT.
9060       if (ValueEltVT != PartEltVT) {
9061         unsigned Count = ValueVTBitSize / PartEltVT.getSizeInBits();
9062         assert(Count != 0 && "The number of element should not be zero.");
9063         SameEltTypeVT =
9064             EVT::getVectorVT(Context, PartEltVT, Count, /*IsScalable=*/true);
9065       }
9066       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SameEltTypeVT, Val,
9067                         DAG.getConstant(0, DL, Subtarget.getXLenVT()));
9068       if (ValueEltVT != PartEltVT)
9069         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
9070       return Val;
9071     }
9072   }
9073   return SDValue();
9074 }
9075 
9076 #define GET_REGISTER_MATCHER
9077 #include "RISCVGenAsmMatcher.inc"
9078 
9079 Register
9080 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
9081                                        const MachineFunction &MF) const {
9082   Register Reg = MatchRegisterAltName(RegName);
9083   if (Reg == RISCV::NoRegister)
9084     Reg = MatchRegisterName(RegName);
9085   if (Reg == RISCV::NoRegister)
9086     report_fatal_error(
9087         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
9088   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
9089   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
9090     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
9091                              StringRef(RegName) + "\"."));
9092   return Reg;
9093 }
9094 
9095 namespace llvm {
9096 namespace RISCVVIntrinsicsTable {
9097 
9098 #define GET_RISCVVIntrinsicsTable_IMPL
9099 #include "RISCVGenSearchableTables.inc"
9100 
9101 } // namespace RISCVVIntrinsicsTable
9102 
9103 } // namespace llvm
9104