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