xref: /freebsd/contrib/llvm-project/llvm/lib/Target/RISCV/RISCVISelLowering.cpp (revision 53683b95ef66a12337999587cd98302b1b425920)
1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation  --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that RISCV uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RISCVISelLowering.h"
15 #include "MCTargetDesc/RISCVMatInt.h"
16 #include "RISCV.h"
17 #include "RISCVMachineFunctionInfo.h"
18 #include "RISCVRegisterInfo.h"
19 #include "RISCVSubtarget.h"
20 #include "RISCVTargetMachine.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/MemoryLocation.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/DiagnosticInfo.h"
32 #include "llvm/IR/DiagnosticPrinter.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/IntrinsicsRISCV.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/KnownBits.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "riscv-lower"
45 
46 STATISTIC(NumTailCalls, "Number of tail calls");
47 
48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
49                                          const RISCVSubtarget &STI)
50     : TargetLowering(TM), Subtarget(STI) {
51 
52   if (Subtarget.isRV32E())
53     report_fatal_error("Codegen not yet implemented for RV32E");
54 
55   RISCVABI::ABI ABI = Subtarget.getTargetABI();
56   assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
57 
58   if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
59       !Subtarget.hasStdExtF()) {
60     errs() << "Hard-float 'f' ABI can't be used for a target that "
61                 "doesn't support the F instruction set extension (ignoring "
62                           "target-abi)\n";
63     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
64   } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
65              !Subtarget.hasStdExtD()) {
66     errs() << "Hard-float 'd' ABI can't be used for a target that "
67               "doesn't support the D instruction set extension (ignoring "
68               "target-abi)\n";
69     ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
70   }
71 
72   switch (ABI) {
73   default:
74     report_fatal_error("Don't know how to lower this ABI");
75   case RISCVABI::ABI_ILP32:
76   case RISCVABI::ABI_ILP32F:
77   case RISCVABI::ABI_ILP32D:
78   case RISCVABI::ABI_LP64:
79   case RISCVABI::ABI_LP64F:
80   case RISCVABI::ABI_LP64D:
81     break;
82   }
83 
84   MVT XLenVT = Subtarget.getXLenVT();
85 
86   // Set up the register classes.
87   addRegisterClass(XLenVT, &RISCV::GPRRegClass);
88 
89   if (Subtarget.hasStdExtZfh())
90     addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
91   if (Subtarget.hasStdExtF())
92     addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
93   if (Subtarget.hasStdExtD())
94     addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
95 
96   static const MVT::SimpleValueType BoolVecVTs[] = {
97       MVT::nxv1i1,  MVT::nxv2i1,  MVT::nxv4i1, MVT::nxv8i1,
98       MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
99   static const MVT::SimpleValueType IntVecVTs[] = {
100       MVT::nxv1i8,  MVT::nxv2i8,   MVT::nxv4i8,   MVT::nxv8i8,  MVT::nxv16i8,
101       MVT::nxv32i8, MVT::nxv64i8,  MVT::nxv1i16,  MVT::nxv2i16, MVT::nxv4i16,
102       MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
103       MVT::nxv4i32, MVT::nxv8i32,  MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
104       MVT::nxv4i64, MVT::nxv8i64};
105   static const MVT::SimpleValueType F16VecVTs[] = {
106       MVT::nxv1f16, MVT::nxv2f16,  MVT::nxv4f16,
107       MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
108   static const MVT::SimpleValueType F32VecVTs[] = {
109       MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
110   static const MVT::SimpleValueType F64VecVTs[] = {
111       MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
112 
113   if (Subtarget.hasVInstructions()) {
114     auto addRegClassForRVV = [this](MVT VT) {
115       unsigned Size = VT.getSizeInBits().getKnownMinValue();
116       assert(Size <= 512 && isPowerOf2_32(Size));
117       const TargetRegisterClass *RC;
118       if (Size <= 64)
119         RC = &RISCV::VRRegClass;
120       else if (Size == 128)
121         RC = &RISCV::VRM2RegClass;
122       else if (Size == 256)
123         RC = &RISCV::VRM4RegClass;
124       else
125         RC = &RISCV::VRM8RegClass;
126 
127       addRegisterClass(VT, RC);
128     };
129 
130     for (MVT VT : BoolVecVTs)
131       addRegClassForRVV(VT);
132     for (MVT VT : IntVecVTs) {
133       if (VT.getVectorElementType() == MVT::i64 &&
134           !Subtarget.hasVInstructionsI64())
135         continue;
136       addRegClassForRVV(VT);
137     }
138 
139     if (Subtarget.hasVInstructionsF16())
140       for (MVT VT : F16VecVTs)
141         addRegClassForRVV(VT);
142 
143     if (Subtarget.hasVInstructionsF32())
144       for (MVT VT : F32VecVTs)
145         addRegClassForRVV(VT);
146 
147     if (Subtarget.hasVInstructionsF64())
148       for (MVT VT : F64VecVTs)
149         addRegClassForRVV(VT);
150 
151     if (Subtarget.useRVVForFixedLengthVectors()) {
152       auto addRegClassForFixedVectors = [this](MVT VT) {
153         MVT ContainerVT = getContainerForFixedLengthVector(VT);
154         unsigned RCID = getRegClassIDForVecVT(ContainerVT);
155         const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
156         addRegisterClass(VT, TRI.getRegClass(RCID));
157       };
158       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
159         if (useRVVForFixedLengthVectorVT(VT))
160           addRegClassForFixedVectors(VT);
161 
162       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
163         if (useRVVForFixedLengthVectorVT(VT))
164           addRegClassForFixedVectors(VT);
165     }
166   }
167 
168   // Compute derived properties from the register classes.
169   computeRegisterProperties(STI.getRegisterInfo());
170 
171   setStackPointerRegisterToSaveRestore(RISCV::X2);
172 
173   for (auto N : {ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD})
174     setLoadExtAction(N, XLenVT, MVT::i1, Promote);
175 
176   // TODO: add all necessary setOperationAction calls.
177   setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
178 
179   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
180   setOperationAction(ISD::BR_CC, XLenVT, Expand);
181   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
182   setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
183 
184   setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
185   setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
186 
187   setOperationAction(ISD::VASTART, MVT::Other, Custom);
188   setOperationAction(ISD::VAARG, MVT::Other, Expand);
189   setOperationAction(ISD::VACOPY, MVT::Other, Expand);
190   setOperationAction(ISD::VAEND, MVT::Other, Expand);
191 
192   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
193   if (!Subtarget.hasStdExtZbb()) {
194     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
195     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
196   }
197 
198   if (Subtarget.is64Bit()) {
199     setOperationAction(ISD::ADD, MVT::i32, Custom);
200     setOperationAction(ISD::SUB, MVT::i32, Custom);
201     setOperationAction(ISD::SHL, MVT::i32, Custom);
202     setOperationAction(ISD::SRA, MVT::i32, Custom);
203     setOperationAction(ISD::SRL, MVT::i32, Custom);
204 
205     setOperationAction(ISD::UADDO, MVT::i32, Custom);
206     setOperationAction(ISD::USUBO, MVT::i32, Custom);
207     setOperationAction(ISD::UADDSAT, MVT::i32, Custom);
208     setOperationAction(ISD::USUBSAT, MVT::i32, Custom);
209   } else {
210     setLibcallName(RTLIB::SHL_I128, nullptr);
211     setLibcallName(RTLIB::SRL_I128, nullptr);
212     setLibcallName(RTLIB::SRA_I128, nullptr);
213     setLibcallName(RTLIB::MUL_I128, nullptr);
214     setLibcallName(RTLIB::MULO_I64, nullptr);
215   }
216 
217   if (!Subtarget.hasStdExtM()) {
218     setOperationAction(ISD::MUL, XLenVT, Expand);
219     setOperationAction(ISD::MULHS, XLenVT, Expand);
220     setOperationAction(ISD::MULHU, XLenVT, Expand);
221     setOperationAction(ISD::SDIV, XLenVT, Expand);
222     setOperationAction(ISD::UDIV, XLenVT, Expand);
223     setOperationAction(ISD::SREM, XLenVT, Expand);
224     setOperationAction(ISD::UREM, XLenVT, Expand);
225   } else {
226     if (Subtarget.is64Bit()) {
227       setOperationAction(ISD::MUL, MVT::i32, Custom);
228       setOperationAction(ISD::MUL, MVT::i128, Custom);
229 
230       setOperationAction(ISD::SDIV, MVT::i8, Custom);
231       setOperationAction(ISD::UDIV, MVT::i8, Custom);
232       setOperationAction(ISD::UREM, MVT::i8, Custom);
233       setOperationAction(ISD::SDIV, MVT::i16, Custom);
234       setOperationAction(ISD::UDIV, MVT::i16, Custom);
235       setOperationAction(ISD::UREM, MVT::i16, Custom);
236       setOperationAction(ISD::SDIV, MVT::i32, Custom);
237       setOperationAction(ISD::UDIV, MVT::i32, Custom);
238       setOperationAction(ISD::UREM, MVT::i32, Custom);
239     } else {
240       setOperationAction(ISD::MUL, MVT::i64, Custom);
241     }
242   }
243 
244   setOperationAction(ISD::SDIVREM, XLenVT, Expand);
245   setOperationAction(ISD::UDIVREM, XLenVT, Expand);
246   setOperationAction(ISD::SMUL_LOHI, XLenVT, Expand);
247   setOperationAction(ISD::UMUL_LOHI, XLenVT, Expand);
248 
249   setOperationAction(ISD::SHL_PARTS, XLenVT, Custom);
250   setOperationAction(ISD::SRL_PARTS, XLenVT, Custom);
251   setOperationAction(ISD::SRA_PARTS, XLenVT, Custom);
252 
253   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
254       Subtarget.hasStdExtZbkb()) {
255     if (Subtarget.is64Bit()) {
256       setOperationAction(ISD::ROTL, MVT::i32, Custom);
257       setOperationAction(ISD::ROTR, MVT::i32, Custom);
258     }
259   } else {
260     setOperationAction(ISD::ROTL, XLenVT, Expand);
261     setOperationAction(ISD::ROTR, XLenVT, Expand);
262   }
263 
264   if (Subtarget.hasStdExtZbp()) {
265     // Custom lower bswap/bitreverse so we can convert them to GREVI to enable
266     // more combining.
267     setOperationAction(ISD::BITREVERSE, XLenVT,   Custom);
268     setOperationAction(ISD::BSWAP,      XLenVT,   Custom);
269     setOperationAction(ISD::BITREVERSE, MVT::i8,  Custom);
270     // BSWAP i8 doesn't exist.
271     setOperationAction(ISD::BITREVERSE, MVT::i16, Custom);
272     setOperationAction(ISD::BSWAP,      MVT::i16, Custom);
273 
274     if (Subtarget.is64Bit()) {
275       setOperationAction(ISD::BITREVERSE, MVT::i32, Custom);
276       setOperationAction(ISD::BSWAP,      MVT::i32, Custom);
277     }
278   } else {
279     // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
280     // pattern match it directly in isel.
281     setOperationAction(ISD::BSWAP, XLenVT,
282                        (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
283                            ? Legal
284                            : Expand);
285     // Zbkb can use rev8+brev8 to implement bitreverse.
286     setOperationAction(ISD::BITREVERSE, XLenVT,
287                        Subtarget.hasStdExtZbkb() ? Custom : Expand);
288   }
289 
290   if (Subtarget.hasStdExtZbb()) {
291     setOperationAction(ISD::SMIN, XLenVT, Legal);
292     setOperationAction(ISD::SMAX, XLenVT, Legal);
293     setOperationAction(ISD::UMIN, XLenVT, Legal);
294     setOperationAction(ISD::UMAX, XLenVT, Legal);
295 
296     if (Subtarget.is64Bit()) {
297       setOperationAction(ISD::CTTZ, MVT::i32, Custom);
298       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
299       setOperationAction(ISD::CTLZ, MVT::i32, Custom);
300       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
301     }
302   } else {
303     setOperationAction(ISD::CTTZ, XLenVT, Expand);
304     setOperationAction(ISD::CTLZ, XLenVT, Expand);
305     setOperationAction(ISD::CTPOP, XLenVT, Expand);
306   }
307 
308   if (Subtarget.hasStdExtZbt()) {
309     setOperationAction(ISD::FSHL, XLenVT, Custom);
310     setOperationAction(ISD::FSHR, XLenVT, Custom);
311     setOperationAction(ISD::SELECT, XLenVT, Legal);
312 
313     if (Subtarget.is64Bit()) {
314       setOperationAction(ISD::FSHL, MVT::i32, Custom);
315       setOperationAction(ISD::FSHR, MVT::i32, Custom);
316     }
317   } else {
318     setOperationAction(ISD::SELECT, XLenVT, Custom);
319   }
320 
321   static const ISD::CondCode FPCCToExpand[] = {
322       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
323       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
324       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
325 
326   static const ISD::NodeType FPOpToExpand[] = {
327       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
328       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
329 
330   if (Subtarget.hasStdExtZfh())
331     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
332 
333   if (Subtarget.hasStdExtZfh()) {
334     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
335     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
336     setOperationAction(ISD::LRINT, MVT::f16, Legal);
337     setOperationAction(ISD::LLRINT, MVT::f16, Legal);
338     setOperationAction(ISD::LROUND, MVT::f16, Legal);
339     setOperationAction(ISD::LLROUND, MVT::f16, Legal);
340     setOperationAction(ISD::STRICT_LRINT, MVT::f16, Legal);
341     setOperationAction(ISD::STRICT_LLRINT, MVT::f16, Legal);
342     setOperationAction(ISD::STRICT_LROUND, MVT::f16, Legal);
343     setOperationAction(ISD::STRICT_LLROUND, MVT::f16, Legal);
344     setOperationAction(ISD::STRICT_FADD, MVT::f16, Legal);
345     setOperationAction(ISD::STRICT_FMA, MVT::f16, Legal);
346     setOperationAction(ISD::STRICT_FSUB, MVT::f16, Legal);
347     setOperationAction(ISD::STRICT_FMUL, MVT::f16, Legal);
348     setOperationAction(ISD::STRICT_FDIV, MVT::f16, Legal);
349     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
350     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
351     setOperationAction(ISD::STRICT_FSQRT, MVT::f16, Legal);
352     setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Legal);
353     setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Legal);
354     for (auto CC : FPCCToExpand)
355       setCondCodeAction(CC, MVT::f16, Expand);
356     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
357     setOperationAction(ISD::SELECT, MVT::f16, Custom);
358     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
359 
360     setOperationAction(ISD::FREM,       MVT::f16, Promote);
361     setOperationAction(ISD::FCEIL,      MVT::f16, Promote);
362     setOperationAction(ISD::FFLOOR,     MVT::f16, Promote);
363     setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
364     setOperationAction(ISD::FRINT,      MVT::f16, Promote);
365     setOperationAction(ISD::FROUND,     MVT::f16, Promote);
366     setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote);
367     setOperationAction(ISD::FTRUNC,     MVT::f16, Promote);
368     setOperationAction(ISD::FPOW,       MVT::f16, Promote);
369     setOperationAction(ISD::FPOWI,      MVT::f16, Promote);
370     setOperationAction(ISD::FCOS,       MVT::f16, Promote);
371     setOperationAction(ISD::FSIN,       MVT::f16, Promote);
372     setOperationAction(ISD::FSINCOS,    MVT::f16, Promote);
373     setOperationAction(ISD::FEXP,       MVT::f16, Promote);
374     setOperationAction(ISD::FEXP2,      MVT::f16, Promote);
375     setOperationAction(ISD::FLOG,       MVT::f16, Promote);
376     setOperationAction(ISD::FLOG2,      MVT::f16, Promote);
377     setOperationAction(ISD::FLOG10,     MVT::f16, Promote);
378 
379     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
380     // complete support for all operations in LegalizeDAG.
381 
382     // We need to custom promote this.
383     if (Subtarget.is64Bit())
384       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
385   }
386 
387   if (Subtarget.hasStdExtF()) {
388     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
389     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
390     setOperationAction(ISD::LRINT, MVT::f32, Legal);
391     setOperationAction(ISD::LLRINT, MVT::f32, Legal);
392     setOperationAction(ISD::LROUND, MVT::f32, Legal);
393     setOperationAction(ISD::LLROUND, MVT::f32, Legal);
394     setOperationAction(ISD::STRICT_LRINT, MVT::f32, Legal);
395     setOperationAction(ISD::STRICT_LLRINT, MVT::f32, Legal);
396     setOperationAction(ISD::STRICT_LROUND, MVT::f32, Legal);
397     setOperationAction(ISD::STRICT_LLROUND, MVT::f32, Legal);
398     setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
399     setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
400     setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
401     setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
402     setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
403     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
404     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
405     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
406     for (auto CC : FPCCToExpand)
407       setCondCodeAction(CC, MVT::f32, Expand);
408     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
409     setOperationAction(ISD::SELECT, MVT::f32, Custom);
410     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
411     for (auto Op : FPOpToExpand)
412       setOperationAction(Op, MVT::f32, Expand);
413     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
414     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
415   }
416 
417   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
418     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
419 
420   if (Subtarget.hasStdExtD()) {
421     setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
422     setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
423     setOperationAction(ISD::LRINT, MVT::f64, Legal);
424     setOperationAction(ISD::LLRINT, MVT::f64, Legal);
425     setOperationAction(ISD::LROUND, MVT::f64, Legal);
426     setOperationAction(ISD::LLROUND, MVT::f64, Legal);
427     setOperationAction(ISD::STRICT_LRINT, MVT::f64, Legal);
428     setOperationAction(ISD::STRICT_LLRINT, MVT::f64, Legal);
429     setOperationAction(ISD::STRICT_LROUND, MVT::f64, Legal);
430     setOperationAction(ISD::STRICT_LLROUND, MVT::f64, Legal);
431     setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
432     setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
433     setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
434     setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
435     setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
436     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
437     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
438     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
439     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
440     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
441     for (auto CC : FPCCToExpand)
442       setCondCodeAction(CC, MVT::f64, Expand);
443     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
444     setOperationAction(ISD::SELECT, MVT::f64, Custom);
445     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
446     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
447     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
448     for (auto Op : FPOpToExpand)
449       setOperationAction(Op, MVT::f64, Expand);
450     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
451     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
452   }
453 
454   if (Subtarget.is64Bit()) {
455     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
456     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
457     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
458     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
459   }
460 
461   if (Subtarget.hasStdExtF()) {
462     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
463     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
464 
465     setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal);
466     setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal);
467     setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal);
468     setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal);
469 
470     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
471     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
472   }
473 
474   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
475   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
476   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
477   setOperationAction(ISD::JumpTable, XLenVT, Custom);
478 
479   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
480 
481   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
482   // Unfortunately this can't be determined just from the ISA naming string.
483   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
484                      Subtarget.is64Bit() ? Legal : Custom);
485 
486   setOperationAction(ISD::TRAP, MVT::Other, Legal);
487   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
488   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
489   if (Subtarget.is64Bit())
490     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
491 
492   if (Subtarget.hasStdExtA()) {
493     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
494     setMinCmpXchgSizeInBits(32);
495   } else {
496     setMaxAtomicSizeInBitsSupported(0);
497   }
498 
499   setBooleanContents(ZeroOrOneBooleanContent);
500 
501   if (Subtarget.hasVInstructions()) {
502     setBooleanVectorContents(ZeroOrOneBooleanContent);
503 
504     setOperationAction(ISD::VSCALE, XLenVT, Custom);
505 
506     // RVV intrinsics may have illegal operands.
507     // We also need to custom legalize vmv.x.s.
508     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
509     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
510     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
511     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
512     if (Subtarget.is64Bit()) {
513       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
514     } else {
515       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
516       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
517     }
518 
519     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
520     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
521 
522     static const unsigned IntegerVPOps[] = {
523         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
524         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
525         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
526         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
527         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
528         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
529         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
530         ISD::VP_MERGE,       ISD::VP_SELECT};
531 
532     static const unsigned FloatingPointVPOps[] = {
533         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
534         ISD::VP_FDIV,        ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
535         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_MERGE,
536         ISD::VP_SELECT};
537 
538     if (!Subtarget.is64Bit()) {
539       // We must custom-lower certain vXi64 operations on RV32 due to the vector
540       // element type being illegal.
541       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
542       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
543 
544       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
545       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
546       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
547       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
548       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
549       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
550       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
551       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
552 
553       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
554       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
555       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
556       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
557       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
558       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
559       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
560       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
561     }
562 
563     for (MVT VT : BoolVecVTs) {
564       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
565 
566       // Mask VTs are custom-expanded into a series of standard nodes
567       setOperationAction(ISD::TRUNCATE, VT, Custom);
568       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
569       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
570       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
571 
572       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
573       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
574 
575       setOperationAction(ISD::SELECT, VT, Custom);
576       setOperationAction(ISD::SELECT_CC, VT, Expand);
577       setOperationAction(ISD::VSELECT, VT, Expand);
578       setOperationAction(ISD::VP_MERGE, VT, Expand);
579       setOperationAction(ISD::VP_SELECT, VT, Expand);
580 
581       setOperationAction(ISD::VP_AND, VT, Custom);
582       setOperationAction(ISD::VP_OR, VT, Custom);
583       setOperationAction(ISD::VP_XOR, VT, Custom);
584 
585       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
586       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
587       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
588 
589       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
590       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
591       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
592 
593       // RVV has native int->float & float->int conversions where the
594       // element type sizes are within one power-of-two of each other. Any
595       // wider distances between type sizes have to be lowered as sequences
596       // which progressively narrow the gap in stages.
597       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
598       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
599       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
600       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
601 
602       // Expand all extending loads to types larger than this, and truncating
603       // stores from types larger than this.
604       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
605         setTruncStoreAction(OtherVT, VT, Expand);
606         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
607         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
608         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
609       }
610     }
611 
612     for (MVT VT : IntVecVTs) {
613       if (VT.getVectorElementType() == MVT::i64 &&
614           !Subtarget.hasVInstructionsI64())
615         continue;
616 
617       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
618       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
619 
620       // Vectors implement MULHS/MULHU.
621       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
622       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
623 
624       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
625       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) {
626         setOperationAction(ISD::MULHU, VT, Expand);
627         setOperationAction(ISD::MULHS, VT, Expand);
628       }
629 
630       setOperationAction(ISD::SMIN, VT, Legal);
631       setOperationAction(ISD::SMAX, VT, Legal);
632       setOperationAction(ISD::UMIN, VT, Legal);
633       setOperationAction(ISD::UMAX, VT, Legal);
634 
635       setOperationAction(ISD::ROTL, VT, Expand);
636       setOperationAction(ISD::ROTR, VT, Expand);
637 
638       setOperationAction(ISD::CTTZ, VT, Expand);
639       setOperationAction(ISD::CTLZ, VT, Expand);
640       setOperationAction(ISD::CTPOP, VT, Expand);
641 
642       setOperationAction(ISD::BSWAP, VT, Expand);
643 
644       // Custom-lower extensions and truncations from/to mask types.
645       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
646       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
647       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
648 
649       // RVV has native int->float & float->int conversions where the
650       // element type sizes are within one power-of-two of each other. Any
651       // wider distances between type sizes have to be lowered as sequences
652       // which progressively narrow the gap in stages.
653       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
654       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
655       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
656       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
657 
658       setOperationAction(ISD::SADDSAT, VT, Legal);
659       setOperationAction(ISD::UADDSAT, VT, Legal);
660       setOperationAction(ISD::SSUBSAT, VT, Legal);
661       setOperationAction(ISD::USUBSAT, VT, Legal);
662 
663       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
664       // nodes which truncate by one power of two at a time.
665       setOperationAction(ISD::TRUNCATE, VT, Custom);
666 
667       // Custom-lower insert/extract operations to simplify patterns.
668       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
669       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
670 
671       // Custom-lower reduction operations to set up the corresponding custom
672       // nodes' operands.
673       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
674       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
675       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
676       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
677       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
678       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
679       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
680       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
681 
682       for (unsigned VPOpc : IntegerVPOps)
683         setOperationAction(VPOpc, VT, Custom);
684 
685       setOperationAction(ISD::LOAD, VT, Custom);
686       setOperationAction(ISD::STORE, VT, Custom);
687 
688       setOperationAction(ISD::MLOAD, VT, Custom);
689       setOperationAction(ISD::MSTORE, VT, Custom);
690       setOperationAction(ISD::MGATHER, VT, Custom);
691       setOperationAction(ISD::MSCATTER, VT, Custom);
692 
693       setOperationAction(ISD::VP_LOAD, VT, Custom);
694       setOperationAction(ISD::VP_STORE, VT, Custom);
695       setOperationAction(ISD::VP_GATHER, VT, Custom);
696       setOperationAction(ISD::VP_SCATTER, VT, Custom);
697 
698       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
699       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
700       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
701 
702       setOperationAction(ISD::SELECT, VT, Custom);
703       setOperationAction(ISD::SELECT_CC, VT, Expand);
704 
705       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
706       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
707 
708       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
709         setTruncStoreAction(VT, OtherVT, Expand);
710         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
711         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
712         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
713       }
714 
715       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
716       // type that can represent the value exactly.
717       if (VT.getVectorElementType() != MVT::i64) {
718         MVT FloatEltVT =
719             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
720         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
721         if (isTypeLegal(FloatVT)) {
722           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
723           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
724         }
725       }
726     }
727 
728     // Expand various CCs to best match the RVV ISA, which natively supports UNE
729     // but no other unordered comparisons, and supports all ordered comparisons
730     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
731     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
732     // and we pattern-match those back to the "original", swapping operands once
733     // more. This way we catch both operations and both "vf" and "fv" forms with
734     // fewer patterns.
735     static const ISD::CondCode VFPCCToExpand[] = {
736         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
737         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
738         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
739     };
740 
741     // Sets common operation actions on RVV floating-point vector types.
742     const auto SetCommonVFPActions = [&](MVT VT) {
743       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
744       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
745       // sizes are within one power-of-two of each other. Therefore conversions
746       // between vXf16 and vXf64 must be lowered as sequences which convert via
747       // vXf32.
748       setOperationAction(ISD::FP_ROUND, VT, Custom);
749       setOperationAction(ISD::FP_EXTEND, VT, Custom);
750       // Custom-lower insert/extract operations to simplify patterns.
751       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
752       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
753       // Expand various condition codes (explained above).
754       for (auto CC : VFPCCToExpand)
755         setCondCodeAction(CC, VT, Expand);
756 
757       setOperationAction(ISD::FMINNUM, VT, Legal);
758       setOperationAction(ISD::FMAXNUM, VT, Legal);
759 
760       setOperationAction(ISD::FTRUNC, VT, Custom);
761       setOperationAction(ISD::FCEIL, VT, Custom);
762       setOperationAction(ISD::FFLOOR, VT, Custom);
763 
764       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
765       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
766       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
767       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
768 
769       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
770 
771       setOperationAction(ISD::LOAD, VT, Custom);
772       setOperationAction(ISD::STORE, VT, Custom);
773 
774       setOperationAction(ISD::MLOAD, VT, Custom);
775       setOperationAction(ISD::MSTORE, VT, Custom);
776       setOperationAction(ISD::MGATHER, VT, Custom);
777       setOperationAction(ISD::MSCATTER, VT, Custom);
778 
779       setOperationAction(ISD::VP_LOAD, VT, Custom);
780       setOperationAction(ISD::VP_STORE, VT, Custom);
781       setOperationAction(ISD::VP_GATHER, VT, Custom);
782       setOperationAction(ISD::VP_SCATTER, VT, Custom);
783 
784       setOperationAction(ISD::SELECT, VT, Custom);
785       setOperationAction(ISD::SELECT_CC, VT, Expand);
786 
787       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
788       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
789       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
790 
791       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
792 
793       for (unsigned VPOpc : FloatingPointVPOps)
794         setOperationAction(VPOpc, VT, Custom);
795     };
796 
797     // Sets common extload/truncstore actions on RVV floating-point vector
798     // types.
799     const auto SetCommonVFPExtLoadTruncStoreActions =
800         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
801           for (auto SmallVT : SmallerVTs) {
802             setTruncStoreAction(VT, SmallVT, Expand);
803             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
804           }
805         };
806 
807     if (Subtarget.hasVInstructionsF16())
808       for (MVT VT : F16VecVTs)
809         SetCommonVFPActions(VT);
810 
811     for (MVT VT : F32VecVTs) {
812       if (Subtarget.hasVInstructionsF32())
813         SetCommonVFPActions(VT);
814       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
815     }
816 
817     for (MVT VT : F64VecVTs) {
818       if (Subtarget.hasVInstructionsF64())
819         SetCommonVFPActions(VT);
820       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
821       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
822     }
823 
824     if (Subtarget.useRVVForFixedLengthVectors()) {
825       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
826         if (!useRVVForFixedLengthVectorVT(VT))
827           continue;
828 
829         // By default everything must be expanded.
830         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
831           setOperationAction(Op, VT, Expand);
832         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
833           setTruncStoreAction(VT, OtherVT, Expand);
834           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
835           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
836           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
837         }
838 
839         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
840         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
841         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
842 
843         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
844         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
845 
846         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
847         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
848 
849         setOperationAction(ISD::LOAD, VT, Custom);
850         setOperationAction(ISD::STORE, VT, Custom);
851 
852         setOperationAction(ISD::SETCC, VT, Custom);
853 
854         setOperationAction(ISD::SELECT, VT, Custom);
855 
856         setOperationAction(ISD::TRUNCATE, VT, Custom);
857 
858         setOperationAction(ISD::BITCAST, VT, Custom);
859 
860         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
861         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
862         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
863 
864         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
865         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
866         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
867 
868         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
869         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
870         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
871         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
872 
873         // Operations below are different for between masks and other vectors.
874         if (VT.getVectorElementType() == MVT::i1) {
875           setOperationAction(ISD::VP_AND, VT, Custom);
876           setOperationAction(ISD::VP_OR, VT, Custom);
877           setOperationAction(ISD::VP_XOR, VT, Custom);
878           setOperationAction(ISD::AND, VT, Custom);
879           setOperationAction(ISD::OR, VT, Custom);
880           setOperationAction(ISD::XOR, VT, Custom);
881           continue;
882         }
883 
884         // Use SPLAT_VECTOR to prevent type legalization from destroying the
885         // splats when type legalizing i64 scalar on RV32.
886         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
887         // improvements first.
888         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
889           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
890           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
891         }
892 
893         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
894         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
895 
896         setOperationAction(ISD::MLOAD, VT, Custom);
897         setOperationAction(ISD::MSTORE, VT, Custom);
898         setOperationAction(ISD::MGATHER, VT, Custom);
899         setOperationAction(ISD::MSCATTER, VT, Custom);
900 
901         setOperationAction(ISD::VP_LOAD, VT, Custom);
902         setOperationAction(ISD::VP_STORE, VT, Custom);
903         setOperationAction(ISD::VP_GATHER, VT, Custom);
904         setOperationAction(ISD::VP_SCATTER, VT, Custom);
905 
906         setOperationAction(ISD::ADD, VT, Custom);
907         setOperationAction(ISD::MUL, VT, Custom);
908         setOperationAction(ISD::SUB, VT, Custom);
909         setOperationAction(ISD::AND, VT, Custom);
910         setOperationAction(ISD::OR, VT, Custom);
911         setOperationAction(ISD::XOR, VT, Custom);
912         setOperationAction(ISD::SDIV, VT, Custom);
913         setOperationAction(ISD::SREM, VT, Custom);
914         setOperationAction(ISD::UDIV, VT, Custom);
915         setOperationAction(ISD::UREM, VT, Custom);
916         setOperationAction(ISD::SHL, VT, Custom);
917         setOperationAction(ISD::SRA, VT, Custom);
918         setOperationAction(ISD::SRL, VT, Custom);
919 
920         setOperationAction(ISD::SMIN, VT, Custom);
921         setOperationAction(ISD::SMAX, VT, Custom);
922         setOperationAction(ISD::UMIN, VT, Custom);
923         setOperationAction(ISD::UMAX, VT, Custom);
924         setOperationAction(ISD::ABS,  VT, Custom);
925 
926         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
927         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) {
928           setOperationAction(ISD::MULHS, VT, Custom);
929           setOperationAction(ISD::MULHU, VT, Custom);
930         }
931 
932         setOperationAction(ISD::SADDSAT, VT, Custom);
933         setOperationAction(ISD::UADDSAT, VT, Custom);
934         setOperationAction(ISD::SSUBSAT, VT, Custom);
935         setOperationAction(ISD::USUBSAT, VT, Custom);
936 
937         setOperationAction(ISD::VSELECT, VT, Custom);
938         setOperationAction(ISD::SELECT_CC, VT, Expand);
939 
940         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
941         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
942         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
943 
944         // Custom-lower reduction operations to set up the corresponding custom
945         // nodes' operands.
946         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
947         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
948         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
949         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
950         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
951 
952         for (unsigned VPOpc : IntegerVPOps)
953           setOperationAction(VPOpc, VT, Custom);
954 
955         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
956         // type that can represent the value exactly.
957         if (VT.getVectorElementType() != MVT::i64) {
958           MVT FloatEltVT =
959               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
960           EVT FloatVT =
961               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
962           if (isTypeLegal(FloatVT)) {
963             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
964             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
965           }
966         }
967       }
968 
969       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
970         if (!useRVVForFixedLengthVectorVT(VT))
971           continue;
972 
973         // By default everything must be expanded.
974         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
975           setOperationAction(Op, VT, Expand);
976         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
977           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
978           setTruncStoreAction(VT, OtherVT, Expand);
979         }
980 
981         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
982         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
983         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
984 
985         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
986         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
987         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
988         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
989         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
990 
991         setOperationAction(ISD::LOAD, VT, Custom);
992         setOperationAction(ISD::STORE, VT, Custom);
993         setOperationAction(ISD::MLOAD, VT, Custom);
994         setOperationAction(ISD::MSTORE, VT, Custom);
995         setOperationAction(ISD::MGATHER, VT, Custom);
996         setOperationAction(ISD::MSCATTER, VT, Custom);
997 
998         setOperationAction(ISD::VP_LOAD, VT, Custom);
999         setOperationAction(ISD::VP_STORE, VT, Custom);
1000         setOperationAction(ISD::VP_GATHER, VT, Custom);
1001         setOperationAction(ISD::VP_SCATTER, VT, Custom);
1002 
1003         setOperationAction(ISD::FADD, VT, Custom);
1004         setOperationAction(ISD::FSUB, VT, Custom);
1005         setOperationAction(ISD::FMUL, VT, Custom);
1006         setOperationAction(ISD::FDIV, VT, Custom);
1007         setOperationAction(ISD::FNEG, VT, Custom);
1008         setOperationAction(ISD::FABS, VT, Custom);
1009         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
1010         setOperationAction(ISD::FSQRT, VT, Custom);
1011         setOperationAction(ISD::FMA, VT, Custom);
1012         setOperationAction(ISD::FMINNUM, VT, Custom);
1013         setOperationAction(ISD::FMAXNUM, VT, Custom);
1014 
1015         setOperationAction(ISD::FP_ROUND, VT, Custom);
1016         setOperationAction(ISD::FP_EXTEND, VT, Custom);
1017 
1018         setOperationAction(ISD::FTRUNC, VT, Custom);
1019         setOperationAction(ISD::FCEIL, VT, Custom);
1020         setOperationAction(ISD::FFLOOR, VT, Custom);
1021 
1022         for (auto CC : VFPCCToExpand)
1023           setCondCodeAction(CC, VT, Expand);
1024 
1025         setOperationAction(ISD::VSELECT, VT, Custom);
1026         setOperationAction(ISD::SELECT, VT, Custom);
1027         setOperationAction(ISD::SELECT_CC, VT, Expand);
1028 
1029         setOperationAction(ISD::BITCAST, VT, Custom);
1030 
1031         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1032         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1033         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1034         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1035 
1036         for (unsigned VPOpc : FloatingPointVPOps)
1037           setOperationAction(VPOpc, VT, Custom);
1038       }
1039 
1040       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1041       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1042       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1043       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
1044       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1045       if (Subtarget.hasStdExtZfh())
1046         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
1047       if (Subtarget.hasStdExtF())
1048         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
1049       if (Subtarget.hasStdExtD())
1050         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
1051     }
1052   }
1053 
1054   // Function alignments.
1055   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
1056   setMinFunctionAlignment(FunctionAlignment);
1057   setPrefFunctionAlignment(FunctionAlignment);
1058 
1059   setMinimumJumpTableEntries(5);
1060 
1061   // Jumps are expensive, compared to logic
1062   setJumpIsExpensive();
1063 
1064   setTargetDAGCombine(ISD::ADD);
1065   setTargetDAGCombine(ISD::SUB);
1066   setTargetDAGCombine(ISD::AND);
1067   setTargetDAGCombine(ISD::OR);
1068   setTargetDAGCombine(ISD::XOR);
1069   setTargetDAGCombine(ISD::ANY_EXTEND);
1070   if (Subtarget.hasStdExtF()) {
1071     setTargetDAGCombine(ISD::ZERO_EXTEND);
1072     setTargetDAGCombine(ISD::FP_TO_SINT);
1073     setTargetDAGCombine(ISD::FP_TO_UINT);
1074     setTargetDAGCombine(ISD::FP_TO_SINT_SAT);
1075     setTargetDAGCombine(ISD::FP_TO_UINT_SAT);
1076   }
1077   if (Subtarget.hasVInstructions()) {
1078     setTargetDAGCombine(ISD::FCOPYSIGN);
1079     setTargetDAGCombine(ISD::MGATHER);
1080     setTargetDAGCombine(ISD::MSCATTER);
1081     setTargetDAGCombine(ISD::VP_GATHER);
1082     setTargetDAGCombine(ISD::VP_SCATTER);
1083     setTargetDAGCombine(ISD::SRA);
1084     setTargetDAGCombine(ISD::SRL);
1085     setTargetDAGCombine(ISD::SHL);
1086     setTargetDAGCombine(ISD::STORE);
1087   }
1088 
1089   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
1090   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
1091 }
1092 
1093 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1094                                             LLVMContext &Context,
1095                                             EVT VT) const {
1096   if (!VT.isVector())
1097     return getPointerTy(DL);
1098   if (Subtarget.hasVInstructions() &&
1099       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1100     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1101   return VT.changeVectorElementTypeToInteger();
1102 }
1103 
1104 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1105   return Subtarget.getXLenVT();
1106 }
1107 
1108 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1109                                              const CallInst &I,
1110                                              MachineFunction &MF,
1111                                              unsigned Intrinsic) const {
1112   auto &DL = I.getModule()->getDataLayout();
1113   switch (Intrinsic) {
1114   default:
1115     return false;
1116   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1117   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1118   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1119   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1120   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1121   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1122   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1123   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1124   case Intrinsic::riscv_masked_cmpxchg_i32:
1125     Info.opc = ISD::INTRINSIC_W_CHAIN;
1126     Info.memVT = MVT::i32;
1127     Info.ptrVal = I.getArgOperand(0);
1128     Info.offset = 0;
1129     Info.align = Align(4);
1130     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1131                  MachineMemOperand::MOVolatile;
1132     return true;
1133   case Intrinsic::riscv_masked_strided_load:
1134     Info.opc = ISD::INTRINSIC_W_CHAIN;
1135     Info.ptrVal = I.getArgOperand(1);
1136     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1137     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1138     Info.size = MemoryLocation::UnknownSize;
1139     Info.flags |= MachineMemOperand::MOLoad;
1140     return true;
1141   case Intrinsic::riscv_masked_strided_store:
1142     Info.opc = ISD::INTRINSIC_VOID;
1143     Info.ptrVal = I.getArgOperand(1);
1144     Info.memVT =
1145         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1146     Info.align = Align(
1147         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1148         8);
1149     Info.size = MemoryLocation::UnknownSize;
1150     Info.flags |= MachineMemOperand::MOStore;
1151     return true;
1152   }
1153 }
1154 
1155 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1156                                                 const AddrMode &AM, Type *Ty,
1157                                                 unsigned AS,
1158                                                 Instruction *I) const {
1159   // No global is ever allowed as a base.
1160   if (AM.BaseGV)
1161     return false;
1162 
1163   // Require a 12-bit signed offset.
1164   if (!isInt<12>(AM.BaseOffs))
1165     return false;
1166 
1167   switch (AM.Scale) {
1168   case 0: // "r+i" or just "i", depending on HasBaseReg.
1169     break;
1170   case 1:
1171     if (!AM.HasBaseReg) // allow "r+i".
1172       break;
1173     return false; // disallow "r+r" or "r+r+i".
1174   default:
1175     return false;
1176   }
1177 
1178   return true;
1179 }
1180 
1181 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1182   return isInt<12>(Imm);
1183 }
1184 
1185 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1186   return isInt<12>(Imm);
1187 }
1188 
1189 // On RV32, 64-bit integers are split into their high and low parts and held
1190 // in two different registers, so the trunc is free since the low register can
1191 // just be used.
1192 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1193   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1194     return false;
1195   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1196   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1197   return (SrcBits == 64 && DestBits == 32);
1198 }
1199 
1200 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1201   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1202       !SrcVT.isInteger() || !DstVT.isInteger())
1203     return false;
1204   unsigned SrcBits = SrcVT.getSizeInBits();
1205   unsigned DestBits = DstVT.getSizeInBits();
1206   return (SrcBits == 64 && DestBits == 32);
1207 }
1208 
1209 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1210   // Zexts are free if they can be combined with a load.
1211   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1212   // poorly with type legalization of compares preferring sext.
1213   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1214     EVT MemVT = LD->getMemoryVT();
1215     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1216         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1217          LD->getExtensionType() == ISD::ZEXTLOAD))
1218       return true;
1219   }
1220 
1221   return TargetLowering::isZExtFree(Val, VT2);
1222 }
1223 
1224 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1225   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1226 }
1227 
1228 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1229   return Subtarget.hasStdExtZbb();
1230 }
1231 
1232 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1233   return Subtarget.hasStdExtZbb();
1234 }
1235 
1236 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1237   EVT VT = Y.getValueType();
1238 
1239   // FIXME: Support vectors once we have tests.
1240   if (VT.isVector())
1241     return false;
1242 
1243   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1244           Subtarget.hasStdExtZbkb()) &&
1245          !isa<ConstantSDNode>(Y);
1246 }
1247 
1248 /// Check if sinking \p I's operands to I's basic block is profitable, because
1249 /// the operands can be folded into a target instruction, e.g.
1250 /// splats of scalars can fold into vector instructions.
1251 bool RISCVTargetLowering::shouldSinkOperands(
1252     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1253   using namespace llvm::PatternMatch;
1254 
1255   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1256     return false;
1257 
1258   auto IsSinker = [&](Instruction *I, int Operand) {
1259     switch (I->getOpcode()) {
1260     case Instruction::Add:
1261     case Instruction::Sub:
1262     case Instruction::Mul:
1263     case Instruction::And:
1264     case Instruction::Or:
1265     case Instruction::Xor:
1266     case Instruction::FAdd:
1267     case Instruction::FSub:
1268     case Instruction::FMul:
1269     case Instruction::FDiv:
1270     case Instruction::ICmp:
1271     case Instruction::FCmp:
1272       return true;
1273     case Instruction::Shl:
1274     case Instruction::LShr:
1275     case Instruction::AShr:
1276     case Instruction::UDiv:
1277     case Instruction::SDiv:
1278     case Instruction::URem:
1279     case Instruction::SRem:
1280       return Operand == 1;
1281     case Instruction::Call:
1282       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1283         switch (II->getIntrinsicID()) {
1284         case Intrinsic::fma:
1285           return Operand == 0 || Operand == 1;
1286         // FIXME: Our patterns can only match vx/vf instructions when the splat
1287         // it on the RHS, because TableGen doesn't recognize our VP operations
1288         // as commutative.
1289         case Intrinsic::vp_add:
1290         case Intrinsic::vp_mul:
1291         case Intrinsic::vp_and:
1292         case Intrinsic::vp_or:
1293         case Intrinsic::vp_xor:
1294         case Intrinsic::vp_fadd:
1295         case Intrinsic::vp_fmul:
1296         case Intrinsic::vp_shl:
1297         case Intrinsic::vp_lshr:
1298         case Intrinsic::vp_ashr:
1299         case Intrinsic::vp_udiv:
1300         case Intrinsic::vp_sdiv:
1301         case Intrinsic::vp_urem:
1302         case Intrinsic::vp_srem:
1303           return Operand == 1;
1304         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1305         // explicit patterns for both LHS and RHS (as 'vr' versions).
1306         case Intrinsic::vp_sub:
1307         case Intrinsic::vp_fsub:
1308         case Intrinsic::vp_fdiv:
1309           return Operand == 0 || Operand == 1;
1310         default:
1311           return false;
1312         }
1313       }
1314       return false;
1315     default:
1316       return false;
1317     }
1318   };
1319 
1320   for (auto OpIdx : enumerate(I->operands())) {
1321     if (!IsSinker(I, OpIdx.index()))
1322       continue;
1323 
1324     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1325     // Make sure we are not already sinking this operand
1326     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1327       continue;
1328 
1329     // We are looking for a splat that can be sunk.
1330     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1331                              m_Undef(), m_ZeroMask())))
1332       continue;
1333 
1334     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1335     // and vector registers
1336     for (Use &U : Op->uses()) {
1337       Instruction *Insn = cast<Instruction>(U.getUser());
1338       if (!IsSinker(Insn, U.getOperandNo()))
1339         return false;
1340     }
1341 
1342     Ops.push_back(&Op->getOperandUse(0));
1343     Ops.push_back(&OpIdx.value());
1344   }
1345   return true;
1346 }
1347 
1348 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1349                                        bool ForCodeSize) const {
1350   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1351   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1352     return false;
1353   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1354     return false;
1355   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1356     return false;
1357   return Imm.isZero();
1358 }
1359 
1360 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1361   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1362          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1363          (VT == MVT::f64 && Subtarget.hasStdExtD());
1364 }
1365 
1366 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1367                                                       CallingConv::ID CC,
1368                                                       EVT VT) const {
1369   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1370   // We might still end up using a GPR but that will be decided based on ABI.
1371   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1372   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1373     return MVT::f32;
1374 
1375   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1376 }
1377 
1378 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1379                                                            CallingConv::ID CC,
1380                                                            EVT VT) const {
1381   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1382   // We might still end up using a GPR but that will be decided based on ABI.
1383   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1384   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1385     return 1;
1386 
1387   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1388 }
1389 
1390 // Changes the condition code and swaps operands if necessary, so the SetCC
1391 // operation matches one of the comparisons supported directly by branches
1392 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1393 // with 1/-1.
1394 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1395                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1396   // Convert X > -1 to X >= 0.
1397   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1398     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1399     CC = ISD::SETGE;
1400     return;
1401   }
1402   // Convert X < 1 to 0 >= X.
1403   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1404     RHS = LHS;
1405     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1406     CC = ISD::SETGE;
1407     return;
1408   }
1409 
1410   switch (CC) {
1411   default:
1412     break;
1413   case ISD::SETGT:
1414   case ISD::SETLE:
1415   case ISD::SETUGT:
1416   case ISD::SETULE:
1417     CC = ISD::getSetCCSwappedOperands(CC);
1418     std::swap(LHS, RHS);
1419     break;
1420   }
1421 }
1422 
1423 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1424   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1425   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1426   if (VT.getVectorElementType() == MVT::i1)
1427     KnownSize *= 8;
1428 
1429   switch (KnownSize) {
1430   default:
1431     llvm_unreachable("Invalid LMUL.");
1432   case 8:
1433     return RISCVII::VLMUL::LMUL_F8;
1434   case 16:
1435     return RISCVII::VLMUL::LMUL_F4;
1436   case 32:
1437     return RISCVII::VLMUL::LMUL_F2;
1438   case 64:
1439     return RISCVII::VLMUL::LMUL_1;
1440   case 128:
1441     return RISCVII::VLMUL::LMUL_2;
1442   case 256:
1443     return RISCVII::VLMUL::LMUL_4;
1444   case 512:
1445     return RISCVII::VLMUL::LMUL_8;
1446   }
1447 }
1448 
1449 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1450   switch (LMul) {
1451   default:
1452     llvm_unreachable("Invalid LMUL.");
1453   case RISCVII::VLMUL::LMUL_F8:
1454   case RISCVII::VLMUL::LMUL_F4:
1455   case RISCVII::VLMUL::LMUL_F2:
1456   case RISCVII::VLMUL::LMUL_1:
1457     return RISCV::VRRegClassID;
1458   case RISCVII::VLMUL::LMUL_2:
1459     return RISCV::VRM2RegClassID;
1460   case RISCVII::VLMUL::LMUL_4:
1461     return RISCV::VRM4RegClassID;
1462   case RISCVII::VLMUL::LMUL_8:
1463     return RISCV::VRM8RegClassID;
1464   }
1465 }
1466 
1467 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1468   RISCVII::VLMUL LMUL = getLMUL(VT);
1469   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1470       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1471       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1472       LMUL == RISCVII::VLMUL::LMUL_1) {
1473     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1474                   "Unexpected subreg numbering");
1475     return RISCV::sub_vrm1_0 + Index;
1476   }
1477   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1478     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1479                   "Unexpected subreg numbering");
1480     return RISCV::sub_vrm2_0 + Index;
1481   }
1482   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1483     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1484                   "Unexpected subreg numbering");
1485     return RISCV::sub_vrm4_0 + Index;
1486   }
1487   llvm_unreachable("Invalid vector type.");
1488 }
1489 
1490 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1491   if (VT.getVectorElementType() == MVT::i1)
1492     return RISCV::VRRegClassID;
1493   return getRegClassIDForLMUL(getLMUL(VT));
1494 }
1495 
1496 // Attempt to decompose a subvector insert/extract between VecVT and
1497 // SubVecVT via subregister indices. Returns the subregister index that
1498 // can perform the subvector insert/extract with the given element index, as
1499 // well as the index corresponding to any leftover subvectors that must be
1500 // further inserted/extracted within the register class for SubVecVT.
1501 std::pair<unsigned, unsigned>
1502 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1503     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1504     const RISCVRegisterInfo *TRI) {
1505   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1506                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1507                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1508                 "Register classes not ordered");
1509   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1510   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1511   // Try to compose a subregister index that takes us from the incoming
1512   // LMUL>1 register class down to the outgoing one. At each step we half
1513   // the LMUL:
1514   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1515   // Note that this is not guaranteed to find a subregister index, such as
1516   // when we are extracting from one VR type to another.
1517   unsigned SubRegIdx = RISCV::NoSubRegister;
1518   for (const unsigned RCID :
1519        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1520     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1521       VecVT = VecVT.getHalfNumVectorElementsVT();
1522       bool IsHi =
1523           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1524       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1525                                             getSubregIndexByMVT(VecVT, IsHi));
1526       if (IsHi)
1527         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1528     }
1529   return {SubRegIdx, InsertExtractIdx};
1530 }
1531 
1532 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1533 // stores for those types.
1534 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1535   return !Subtarget.useRVVForFixedLengthVectors() ||
1536          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1537 }
1538 
1539 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1540   if (ScalarTy->isPointerTy())
1541     return true;
1542 
1543   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1544       ScalarTy->isIntegerTy(32))
1545     return true;
1546 
1547   if (ScalarTy->isIntegerTy(64))
1548     return Subtarget.hasVInstructionsI64();
1549 
1550   if (ScalarTy->isHalfTy())
1551     return Subtarget.hasVInstructionsF16();
1552   if (ScalarTy->isFloatTy())
1553     return Subtarget.hasVInstructionsF32();
1554   if (ScalarTy->isDoubleTy())
1555     return Subtarget.hasVInstructionsF64();
1556 
1557   return false;
1558 }
1559 
1560 static SDValue getVLOperand(SDValue Op) {
1561   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1562           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1563          "Unexpected opcode");
1564   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1565   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1566   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1567       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1568   if (!II)
1569     return SDValue();
1570   return Op.getOperand(II->VLOperand + 1 + HasChain);
1571 }
1572 
1573 static bool useRVVForFixedLengthVectorVT(MVT VT,
1574                                          const RISCVSubtarget &Subtarget) {
1575   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1576   if (!Subtarget.useRVVForFixedLengthVectors())
1577     return false;
1578 
1579   // We only support a set of vector types with a consistent maximum fixed size
1580   // across all supported vector element types to avoid legalization issues.
1581   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1582   // fixed-length vector type we support is 1024 bytes.
1583   if (VT.getFixedSizeInBits() > 1024 * 8)
1584     return false;
1585 
1586   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1587 
1588   MVT EltVT = VT.getVectorElementType();
1589 
1590   // Don't use RVV for vectors we cannot scalarize if required.
1591   switch (EltVT.SimpleTy) {
1592   // i1 is supported but has different rules.
1593   default:
1594     return false;
1595   case MVT::i1:
1596     // Masks can only use a single register.
1597     if (VT.getVectorNumElements() > MinVLen)
1598       return false;
1599     MinVLen /= 8;
1600     break;
1601   case MVT::i8:
1602   case MVT::i16:
1603   case MVT::i32:
1604     break;
1605   case MVT::i64:
1606     if (!Subtarget.hasVInstructionsI64())
1607       return false;
1608     break;
1609   case MVT::f16:
1610     if (!Subtarget.hasVInstructionsF16())
1611       return false;
1612     break;
1613   case MVT::f32:
1614     if (!Subtarget.hasVInstructionsF32())
1615       return false;
1616     break;
1617   case MVT::f64:
1618     if (!Subtarget.hasVInstructionsF64())
1619       return false;
1620     break;
1621   }
1622 
1623   // Reject elements larger than ELEN.
1624   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1625     return false;
1626 
1627   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1628   // Don't use RVV for types that don't fit.
1629   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1630     return false;
1631 
1632   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1633   // the base fixed length RVV support in place.
1634   if (!VT.isPow2VectorType())
1635     return false;
1636 
1637   return true;
1638 }
1639 
1640 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1641   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1642 }
1643 
1644 // Return the largest legal scalable vector type that matches VT's element type.
1645 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1646                                             const RISCVSubtarget &Subtarget) {
1647   // This may be called before legal types are setup.
1648   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1649           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1650          "Expected legal fixed length vector!");
1651 
1652   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1653   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1654 
1655   MVT EltVT = VT.getVectorElementType();
1656   switch (EltVT.SimpleTy) {
1657   default:
1658     llvm_unreachable("unexpected element type for RVV container");
1659   case MVT::i1:
1660   case MVT::i8:
1661   case MVT::i16:
1662   case MVT::i32:
1663   case MVT::i64:
1664   case MVT::f16:
1665   case MVT::f32:
1666   case MVT::f64: {
1667     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1668     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1669     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1670     unsigned NumElts =
1671         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1672     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1673     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1674     return MVT::getScalableVectorVT(EltVT, NumElts);
1675   }
1676   }
1677 }
1678 
1679 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1680                                             const RISCVSubtarget &Subtarget) {
1681   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1682                                           Subtarget);
1683 }
1684 
1685 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1686   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1687 }
1688 
1689 // Grow V to consume an entire RVV register.
1690 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1691                                        const RISCVSubtarget &Subtarget) {
1692   assert(VT.isScalableVector() &&
1693          "Expected to convert into a scalable vector!");
1694   assert(V.getValueType().isFixedLengthVector() &&
1695          "Expected a fixed length vector operand!");
1696   SDLoc DL(V);
1697   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1698   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1699 }
1700 
1701 // Shrink V so it's just big enough to maintain a VT's worth of data.
1702 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1703                                          const RISCVSubtarget &Subtarget) {
1704   assert(VT.isFixedLengthVector() &&
1705          "Expected to convert into a fixed length vector!");
1706   assert(V.getValueType().isScalableVector() &&
1707          "Expected a scalable vector operand!");
1708   SDLoc DL(V);
1709   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1710   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1711 }
1712 
1713 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1714 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1715 // the vector type that it is contained in.
1716 static std::pair<SDValue, SDValue>
1717 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1718                 const RISCVSubtarget &Subtarget) {
1719   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1720   MVT XLenVT = Subtarget.getXLenVT();
1721   SDValue VL = VecVT.isFixedLengthVector()
1722                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1723                    : DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT);
1724   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1725   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1726   return {Mask, VL};
1727 }
1728 
1729 // As above but assuming the given type is a scalable vector type.
1730 static std::pair<SDValue, SDValue>
1731 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1732                         const RISCVSubtarget &Subtarget) {
1733   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1734   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1735 }
1736 
1737 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1738 // of either is (currently) supported. This can get us into an infinite loop
1739 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1740 // as a ..., etc.
1741 // Until either (or both) of these can reliably lower any node, reporting that
1742 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1743 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1744 // which is not desirable.
1745 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1746     EVT VT, unsigned DefinedValues) const {
1747   return false;
1748 }
1749 
1750 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
1751   // Only splats are currently supported.
1752   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
1753     return true;
1754 
1755   return false;
1756 }
1757 
1758 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1759                                   const RISCVSubtarget &Subtarget) {
1760   // RISCV FP-to-int conversions saturate to the destination register size, but
1761   // don't produce 0 for nan. We can use a conversion instruction and fix the
1762   // nan case with a compare and a select.
1763   SDValue Src = Op.getOperand(0);
1764 
1765   EVT DstVT = Op.getValueType();
1766   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1767 
1768   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1769   unsigned Opc;
1770   if (SatVT == DstVT)
1771     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1772   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1773     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1774   else
1775     return SDValue();
1776   // FIXME: Support other SatVTs by clamping before or after the conversion.
1777 
1778   SDLoc DL(Op);
1779   SDValue FpToInt = DAG.getNode(
1780       Opc, DL, DstVT, Src,
1781       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1782 
1783   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1784   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1785 }
1786 
1787 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1788 // and back. Taking care to avoid converting values that are nan or already
1789 // correct.
1790 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1791 // have FRM dependencies modeled yet.
1792 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1793   MVT VT = Op.getSimpleValueType();
1794   assert(VT.isVector() && "Unexpected type");
1795 
1796   SDLoc DL(Op);
1797 
1798   // Freeze the source since we are increasing the number of uses.
1799   SDValue Src = DAG.getNode(ISD::FREEZE, DL, VT, Op.getOperand(0));
1800 
1801   // Truncate to integer and convert back to FP.
1802   MVT IntVT = VT.changeVectorElementTypeToInteger();
1803   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1804   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1805 
1806   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1807 
1808   if (Op.getOpcode() == ISD::FCEIL) {
1809     // If the truncated value is the greater than or equal to the original
1810     // value, we've computed the ceil. Otherwise, we went the wrong way and
1811     // need to increase by 1.
1812     // FIXME: This should use a masked operation. Handle here or in isel?
1813     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1814                                  DAG.getConstantFP(1.0, DL, VT));
1815     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1816     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1817   } else if (Op.getOpcode() == ISD::FFLOOR) {
1818     // If the truncated value is the less than or equal to the original value,
1819     // we've computed the floor. Otherwise, we went the wrong way and need to
1820     // decrease by 1.
1821     // FIXME: This should use a masked operation. Handle here or in isel?
1822     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1823                                  DAG.getConstantFP(1.0, DL, VT));
1824     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1825     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1826   }
1827 
1828   // Restore the original sign so that -0.0 is preserved.
1829   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1830 
1831   // Determine the largest integer that can be represented exactly. This and
1832   // values larger than it don't have any fractional bits so don't need to
1833   // be converted.
1834   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1835   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1836   APFloat MaxVal = APFloat(FltSem);
1837   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1838                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1839   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1840 
1841   // If abs(Src) was larger than MaxVal or nan, keep it.
1842   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1843   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1844   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1845 }
1846 
1847 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1848                                  const RISCVSubtarget &Subtarget) {
1849   MVT VT = Op.getSimpleValueType();
1850   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1851 
1852   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1853 
1854   SDLoc DL(Op);
1855   SDValue Mask, VL;
1856   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1857 
1858   unsigned Opc =
1859       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1860   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, Op.getOperand(0), VL);
1861   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1862 }
1863 
1864 struct VIDSequence {
1865   int64_t StepNumerator;
1866   unsigned StepDenominator;
1867   int64_t Addend;
1868 };
1869 
1870 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1871 // to the (non-zero) step S and start value X. This can be then lowered as the
1872 // RVV sequence (VID * S) + X, for example.
1873 // The step S is represented as an integer numerator divided by a positive
1874 // denominator. Note that the implementation currently only identifies
1875 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1876 // cannot detect 2/3, for example.
1877 // Note that this method will also match potentially unappealing index
1878 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1879 // determine whether this is worth generating code for.
1880 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1881   unsigned NumElts = Op.getNumOperands();
1882   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1883   if (!Op.getValueType().isInteger())
1884     return None;
1885 
1886   Optional<unsigned> SeqStepDenom;
1887   Optional<int64_t> SeqStepNum, SeqAddend;
1888   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1889   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1890   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1891     // Assume undef elements match the sequence; we just have to be careful
1892     // when interpolating across them.
1893     if (Op.getOperand(Idx).isUndef())
1894       continue;
1895     // The BUILD_VECTOR must be all constants.
1896     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1897       return None;
1898 
1899     uint64_t Val = Op.getConstantOperandVal(Idx) &
1900                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1901 
1902     if (PrevElt) {
1903       // Calculate the step since the last non-undef element, and ensure
1904       // it's consistent across the entire sequence.
1905       unsigned IdxDiff = Idx - PrevElt->second;
1906       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1907 
1908       // A zero-value value difference means that we're somewhere in the middle
1909       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1910       // step change before evaluating the sequence.
1911       if (ValDiff != 0) {
1912         int64_t Remainder = ValDiff % IdxDiff;
1913         // Normalize the step if it's greater than 1.
1914         if (Remainder != ValDiff) {
1915           // The difference must cleanly divide the element span.
1916           if (Remainder != 0)
1917             return None;
1918           ValDiff /= IdxDiff;
1919           IdxDiff = 1;
1920         }
1921 
1922         if (!SeqStepNum)
1923           SeqStepNum = ValDiff;
1924         else if (ValDiff != SeqStepNum)
1925           return None;
1926 
1927         if (!SeqStepDenom)
1928           SeqStepDenom = IdxDiff;
1929         else if (IdxDiff != *SeqStepDenom)
1930           return None;
1931       }
1932     }
1933 
1934     // Record and/or check any addend.
1935     if (SeqStepNum && SeqStepDenom) {
1936       uint64_t ExpectedVal =
1937           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1938       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1939       if (!SeqAddend)
1940         SeqAddend = Addend;
1941       else if (SeqAddend != Addend)
1942         return None;
1943     }
1944 
1945     // Record this non-undef element for later.
1946     if (!PrevElt || PrevElt->first != Val)
1947       PrevElt = std::make_pair(Val, Idx);
1948   }
1949   // We need to have logged both a step and an addend for this to count as
1950   // a legal index sequence.
1951   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1952     return None;
1953 
1954   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1955 }
1956 
1957 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
1958                                  const RISCVSubtarget &Subtarget) {
1959   MVT VT = Op.getSimpleValueType();
1960   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1961 
1962   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1963 
1964   SDLoc DL(Op);
1965   SDValue Mask, VL;
1966   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1967 
1968   MVT XLenVT = Subtarget.getXLenVT();
1969   unsigned NumElts = Op.getNumOperands();
1970 
1971   if (VT.getVectorElementType() == MVT::i1) {
1972     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
1973       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
1974       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
1975     }
1976 
1977     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
1978       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
1979       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
1980     }
1981 
1982     // Lower constant mask BUILD_VECTORs via an integer vector type, in
1983     // scalar integer chunks whose bit-width depends on the number of mask
1984     // bits and XLEN.
1985     // First, determine the most appropriate scalar integer type to use. This
1986     // is at most XLenVT, but may be shrunk to a smaller vector element type
1987     // according to the size of the final vector - use i8 chunks rather than
1988     // XLenVT if we're producing a v8i1. This results in more consistent
1989     // codegen across RV32 and RV64.
1990     unsigned NumViaIntegerBits =
1991         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
1992     NumViaIntegerBits = std::min(NumViaIntegerBits,
1993                                  Subtarget.getMaxELENForFixedLengthVectors());
1994     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
1995       // If we have to use more than one INSERT_VECTOR_ELT then this
1996       // optimization is likely to increase code size; avoid peforming it in
1997       // such a case. We can use a load from a constant pool in this case.
1998       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
1999         return SDValue();
2000       // Now we can create our integer vector type. Note that it may be larger
2001       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2002       MVT IntegerViaVecVT =
2003           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2004                            divideCeil(NumElts, NumViaIntegerBits));
2005 
2006       uint64_t Bits = 0;
2007       unsigned BitPos = 0, IntegerEltIdx = 0;
2008       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2009 
2010       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2011         // Once we accumulate enough bits to fill our scalar type, insert into
2012         // our vector and clear our accumulated data.
2013         if (I != 0 && I % NumViaIntegerBits == 0) {
2014           if (NumViaIntegerBits <= 32)
2015             Bits = SignExtend64(Bits, 32);
2016           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2017           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2018                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2019           Bits = 0;
2020           BitPos = 0;
2021           IntegerEltIdx++;
2022         }
2023         SDValue V = Op.getOperand(I);
2024         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2025         Bits |= ((uint64_t)BitValue << BitPos);
2026       }
2027 
2028       // Insert the (remaining) scalar value into position in our integer
2029       // vector type.
2030       if (NumViaIntegerBits <= 32)
2031         Bits = SignExtend64(Bits, 32);
2032       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2033       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2034                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2035 
2036       if (NumElts < NumViaIntegerBits) {
2037         // If we're producing a smaller vector than our minimum legal integer
2038         // type, bitcast to the equivalent (known-legal) mask type, and extract
2039         // our final mask.
2040         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2041         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2042         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2043                           DAG.getConstant(0, DL, XLenVT));
2044       } else {
2045         // Else we must have produced an integer type with the same size as the
2046         // mask type; bitcast for the final result.
2047         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2048         Vec = DAG.getBitcast(VT, Vec);
2049       }
2050 
2051       return Vec;
2052     }
2053 
2054     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2055     // vector type, we have a legal equivalently-sized i8 type, so we can use
2056     // that.
2057     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2058     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2059 
2060     SDValue WideVec;
2061     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2062       // For a splat, perform a scalar truncate before creating the wider
2063       // vector.
2064       assert(Splat.getValueType() == XLenVT &&
2065              "Unexpected type for i1 splat value");
2066       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2067                           DAG.getConstant(1, DL, XLenVT));
2068       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2069     } else {
2070       SmallVector<SDValue, 8> Ops(Op->op_values());
2071       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2072       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2073       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2074     }
2075 
2076     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2077   }
2078 
2079   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2080     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2081                                         : RISCVISD::VMV_V_X_VL;
2082     Splat = DAG.getNode(Opc, DL, ContainerVT, Splat, VL);
2083     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2084   }
2085 
2086   // Try and match index sequences, which we can lower to the vid instruction
2087   // with optional modifications. An all-undef vector is matched by
2088   // getSplatValue, above.
2089   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2090     int64_t StepNumerator = SimpleVID->StepNumerator;
2091     unsigned StepDenominator = SimpleVID->StepDenominator;
2092     int64_t Addend = SimpleVID->Addend;
2093 
2094     assert(StepNumerator != 0 && "Invalid step");
2095     bool Negate = false;
2096     int64_t SplatStepVal = StepNumerator;
2097     unsigned StepOpcode = ISD::MUL;
2098     if (StepNumerator != 1) {
2099       if (isPowerOf2_64(std::abs(StepNumerator))) {
2100         Negate = StepNumerator < 0;
2101         StepOpcode = ISD::SHL;
2102         SplatStepVal = Log2_64(std::abs(StepNumerator));
2103       }
2104     }
2105 
2106     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2107     // threshold since it's the immediate value many RVV instructions accept.
2108     // There is no vmul.vi instruction so ensure multiply constant can fit in
2109     // a single addi instruction.
2110     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2111          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2112         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2113       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2114       // Convert right out of the scalable type so we can use standard ISD
2115       // nodes for the rest of the computation. If we used scalable types with
2116       // these, we'd lose the fixed-length vector info and generate worse
2117       // vsetvli code.
2118       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2119       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2120           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2121         SDValue SplatStep = DAG.getSplatVector(
2122             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2123         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2124       }
2125       if (StepDenominator != 1) {
2126         SDValue SplatStep = DAG.getSplatVector(
2127             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2128         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2129       }
2130       if (Addend != 0 || Negate) {
2131         SDValue SplatAddend =
2132             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2133         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2134       }
2135       return VID;
2136     }
2137   }
2138 
2139   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2140   // when re-interpreted as a vector with a larger element type. For example,
2141   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2142   // could be instead splat as
2143   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2144   // TODO: This optimization could also work on non-constant splats, but it
2145   // would require bit-manipulation instructions to construct the splat value.
2146   SmallVector<SDValue> Sequence;
2147   unsigned EltBitSize = VT.getScalarSizeInBits();
2148   const auto *BV = cast<BuildVectorSDNode>(Op);
2149   if (VT.isInteger() && EltBitSize < 64 &&
2150       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2151       BV->getRepeatedSequence(Sequence) &&
2152       (Sequence.size() * EltBitSize) <= 64) {
2153     unsigned SeqLen = Sequence.size();
2154     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2155     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2156     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2157             ViaIntVT == MVT::i64) &&
2158            "Unexpected sequence type");
2159 
2160     unsigned EltIdx = 0;
2161     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2162     uint64_t SplatValue = 0;
2163     // Construct the amalgamated value which can be splatted as this larger
2164     // vector type.
2165     for (const auto &SeqV : Sequence) {
2166       if (!SeqV.isUndef())
2167         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2168                        << (EltIdx * EltBitSize));
2169       EltIdx++;
2170     }
2171 
2172     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2173     // achieve better constant materializion.
2174     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2175       SplatValue = SignExtend64(SplatValue, 32);
2176 
2177     // Since we can't introduce illegal i64 types at this stage, we can only
2178     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2179     // way we can use RVV instructions to splat.
2180     assert((ViaIntVT.bitsLE(XLenVT) ||
2181             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2182            "Unexpected bitcast sequence");
2183     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2184       SDValue ViaVL =
2185           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2186       MVT ViaContainerVT =
2187           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2188       SDValue Splat =
2189           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2190                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2191       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2192       return DAG.getBitcast(VT, Splat);
2193     }
2194   }
2195 
2196   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2197   // which constitute a large proportion of the elements. In such cases we can
2198   // splat a vector with the dominant element and make up the shortfall with
2199   // INSERT_VECTOR_ELTs.
2200   // Note that this includes vectors of 2 elements by association. The
2201   // upper-most element is the "dominant" one, allowing us to use a splat to
2202   // "insert" the upper element, and an insert of the lower element at position
2203   // 0, which improves codegen.
2204   SDValue DominantValue;
2205   unsigned MostCommonCount = 0;
2206   DenseMap<SDValue, unsigned> ValueCounts;
2207   unsigned NumUndefElts =
2208       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2209 
2210   // Track the number of scalar loads we know we'd be inserting, estimated as
2211   // any non-zero floating-point constant. Other kinds of element are either
2212   // already in registers or are materialized on demand. The threshold at which
2213   // a vector load is more desirable than several scalar materializion and
2214   // vector-insertion instructions is not known.
2215   unsigned NumScalarLoads = 0;
2216 
2217   for (SDValue V : Op->op_values()) {
2218     if (V.isUndef())
2219       continue;
2220 
2221     ValueCounts.insert(std::make_pair(V, 0));
2222     unsigned &Count = ValueCounts[V];
2223 
2224     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2225       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2226 
2227     // Is this value dominant? In case of a tie, prefer the highest element as
2228     // it's cheaper to insert near the beginning of a vector than it is at the
2229     // end.
2230     if (++Count >= MostCommonCount) {
2231       DominantValue = V;
2232       MostCommonCount = Count;
2233     }
2234   }
2235 
2236   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2237   unsigned NumDefElts = NumElts - NumUndefElts;
2238   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2239 
2240   // Don't perform this optimization when optimizing for size, since
2241   // materializing elements and inserting them tends to cause code bloat.
2242   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2243       ((MostCommonCount > DominantValueCountThreshold) ||
2244        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2245     // Start by splatting the most common element.
2246     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2247 
2248     DenseSet<SDValue> Processed{DominantValue};
2249     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2250     for (const auto &OpIdx : enumerate(Op->ops())) {
2251       const SDValue &V = OpIdx.value();
2252       if (V.isUndef() || !Processed.insert(V).second)
2253         continue;
2254       if (ValueCounts[V] == 1) {
2255         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2256                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2257       } else {
2258         // Blend in all instances of this value using a VSELECT, using a
2259         // mask where each bit signals whether that element is the one
2260         // we're after.
2261         SmallVector<SDValue> Ops;
2262         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2263           return DAG.getConstant(V == V1, DL, XLenVT);
2264         });
2265         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2266                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2267                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2268       }
2269     }
2270 
2271     return Vec;
2272   }
2273 
2274   return SDValue();
2275 }
2276 
2277 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Lo,
2278                                    SDValue Hi, SDValue VL, SelectionDAG &DAG) {
2279   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2280     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2281     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2282     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2283     // node in order to try and match RVV vector/scalar instructions.
2284     if ((LoC >> 31) == HiC)
2285       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Lo, VL);
2286 
2287     // If vl is equal to VLMax and Hi constant is equal to Lo, we could use
2288     // vmv.v.x whose EEW = 32 to lower it.
2289     auto *Const = dyn_cast<ConstantSDNode>(VL);
2290     if (LoC == HiC && Const && Const->getSExtValue() == RISCV::VLMaxSentinel) {
2291       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2292       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2293       // access the subtarget here now.
2294       auto InterVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterVT, Lo, VL);
2295       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2296     }
2297   }
2298 
2299   // Fall back to a stack store and stride x0 vector load.
2300   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Lo, Hi, VL);
2301 }
2302 
2303 // Called by type legalization to handle splat of i64 on RV32.
2304 // FIXME: We can optimize this when the type has sign or zero bits in one
2305 // of the halves.
2306 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Scalar,
2307                                    SDValue VL, SelectionDAG &DAG) {
2308   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2309   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2310                            DAG.getConstant(0, DL, MVT::i32));
2311   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2312                            DAG.getConstant(1, DL, MVT::i32));
2313   return splatPartsI64WithVL(DL, VT, Lo, Hi, VL, DAG);
2314 }
2315 
2316 // This function lowers a splat of a scalar operand Splat with the vector
2317 // length VL. It ensures the final sequence is type legal, which is useful when
2318 // lowering a splat after type legalization.
2319 static SDValue lowerScalarSplat(SDValue Scalar, SDValue VL, MVT VT, SDLoc DL,
2320                                 SelectionDAG &DAG,
2321                                 const RISCVSubtarget &Subtarget) {
2322   if (VT.isFloatingPoint()) {
2323     // If VL is 1, we could use vfmv.s.f.
2324     if (isOneConstant(VL))
2325       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, DAG.getUNDEF(VT),
2326                          Scalar, VL);
2327     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Scalar, VL);
2328   }
2329 
2330   MVT XLenVT = Subtarget.getXLenVT();
2331 
2332   // Simplest case is that the operand needs to be promoted to XLenVT.
2333   if (Scalar.getValueType().bitsLE(XLenVT)) {
2334     // If the operand is a constant, sign extend to increase our chances
2335     // of being able to use a .vi instruction. ANY_EXTEND would become a
2336     // a zero extend and the simm5 check in isel would fail.
2337     // FIXME: Should we ignore the upper bits in isel instead?
2338     unsigned ExtOpc =
2339         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2340     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2341     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2342     // If VL is 1 and the scalar value won't benefit from immediate, we could
2343     // use vmv.s.x.
2344     if (isOneConstant(VL) &&
2345         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2346       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT), Scalar,
2347                          VL);
2348     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Scalar, VL);
2349   }
2350 
2351   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2352          "Unexpected scalar for splat lowering!");
2353 
2354   if (isOneConstant(VL) && isNullConstant(Scalar))
2355     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, DAG.getUNDEF(VT),
2356                        DAG.getConstant(0, DL, XLenVT), VL);
2357 
2358   // Otherwise use the more complicated splatting algorithm.
2359   return splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
2360 }
2361 
2362 // Is the mask a slidedown that shifts in undefs.
2363 static int matchShuffleAsSlideDown(ArrayRef<int> Mask) {
2364   int Size = Mask.size();
2365 
2366   // Elements shifted in should be undef.
2367   auto CheckUndefs = [&](int Shift) {
2368     for (int i = Size - Shift; i != Size; ++i)
2369       if (Mask[i] >= 0)
2370         return false;
2371     return true;
2372   };
2373 
2374   // Elements should be shifted or undef.
2375   auto MatchShift = [&](int Shift) {
2376     for (int i = 0; i != Size - Shift; ++i)
2377        if (Mask[i] >= 0 && Mask[i] != Shift + i)
2378          return false;
2379     return true;
2380   };
2381 
2382   // Try all possible shifts.
2383   for (int Shift = 1; Shift != Size; ++Shift)
2384     if (CheckUndefs(Shift) && MatchShift(Shift))
2385       return Shift;
2386 
2387   // No match.
2388   return -1;
2389 }
2390 
2391 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2392                                 const RISCVSubtarget &Subtarget) {
2393   // We need to be able to widen elements to the next larger integer type.
2394   if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors())
2395     return false;
2396 
2397   int Size = Mask.size();
2398   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2399 
2400   int Srcs[] = {-1, -1};
2401   for (int i = 0; i != Size; ++i) {
2402     // Ignore undef elements.
2403     if (Mask[i] < 0)
2404       continue;
2405 
2406     // Is this an even or odd element.
2407     int Pol = i % 2;
2408 
2409     // Ensure we consistently use the same source for this element polarity.
2410     int Src = Mask[i] / Size;
2411     if (Srcs[Pol] < 0)
2412       Srcs[Pol] = Src;
2413     if (Srcs[Pol] != Src)
2414       return false;
2415 
2416     // Make sure the element within the source is appropriate for this element
2417     // in the destination.
2418     int Elt = Mask[i] % Size;
2419     if (Elt != i / 2)
2420       return false;
2421   }
2422 
2423   // We need to find a source for each polarity and they can't be the same.
2424   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2425     return false;
2426 
2427   // Swap the sources if the second source was in the even polarity.
2428   SwapSources = Srcs[0] > Srcs[1];
2429 
2430   return true;
2431 }
2432 
2433 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2434                                    const RISCVSubtarget &Subtarget) {
2435   SDValue V1 = Op.getOperand(0);
2436   SDValue V2 = Op.getOperand(1);
2437   SDLoc DL(Op);
2438   MVT XLenVT = Subtarget.getXLenVT();
2439   MVT VT = Op.getSimpleValueType();
2440   unsigned NumElts = VT.getVectorNumElements();
2441   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2442 
2443   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2444 
2445   SDValue TrueMask, VL;
2446   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2447 
2448   if (SVN->isSplat()) {
2449     const int Lane = SVN->getSplatIndex();
2450     if (Lane >= 0) {
2451       MVT SVT = VT.getVectorElementType();
2452 
2453       // Turn splatted vector load into a strided load with an X0 stride.
2454       SDValue V = V1;
2455       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2456       // with undef.
2457       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2458       int Offset = Lane;
2459       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2460         int OpElements =
2461             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2462         V = V.getOperand(Offset / OpElements);
2463         Offset %= OpElements;
2464       }
2465 
2466       // We need to ensure the load isn't atomic or volatile.
2467       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2468         auto *Ld = cast<LoadSDNode>(V);
2469         Offset *= SVT.getStoreSize();
2470         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2471                                                    TypeSize::Fixed(Offset), DL);
2472 
2473         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2474         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2475           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2476           SDValue IntID =
2477               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2478           SDValue Ops[] = {Ld->getChain(),
2479                            IntID,
2480                            DAG.getUNDEF(ContainerVT),
2481                            NewAddr,
2482                            DAG.getRegister(RISCV::X0, XLenVT),
2483                            VL};
2484           SDValue NewLoad = DAG.getMemIntrinsicNode(
2485               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2486               DAG.getMachineFunction().getMachineMemOperand(
2487                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2488           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2489           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2490         }
2491 
2492         // Otherwise use a scalar load and splat. This will give the best
2493         // opportunity to fold a splat into the operation. ISel can turn it into
2494         // the x0 strided load if we aren't able to fold away the select.
2495         if (SVT.isFloatingPoint())
2496           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2497                           Ld->getPointerInfo().getWithOffset(Offset),
2498                           Ld->getOriginalAlign(),
2499                           Ld->getMemOperand()->getFlags());
2500         else
2501           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2502                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2503                              Ld->getOriginalAlign(),
2504                              Ld->getMemOperand()->getFlags());
2505         DAG.makeEquivalentMemoryOrdering(Ld, V);
2506 
2507         unsigned Opc =
2508             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2509         SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, V, VL);
2510         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2511       }
2512 
2513       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2514       assert(Lane < (int)NumElts && "Unexpected lane!");
2515       SDValue Gather =
2516           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2517                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2518       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2519     }
2520   }
2521 
2522   ArrayRef<int> Mask = SVN->getMask();
2523 
2524   // Try to match as a slidedown.
2525   int SlideAmt = matchShuffleAsSlideDown(Mask);
2526   if (SlideAmt >= 0) {
2527     // TODO: Should we reduce the VL to account for the upper undef elements?
2528     // Requires additional vsetvlis, but might be faster to execute.
2529     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2530     SDValue SlideDown =
2531         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
2532                     DAG.getUNDEF(ContainerVT), V1,
2533                     DAG.getConstant(SlideAmt, DL, XLenVT),
2534                     TrueMask, VL);
2535     return convertFromScalableVector(VT, SlideDown, DAG, Subtarget);
2536   }
2537 
2538   // Detect an interleave shuffle and lower to
2539   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2540   bool SwapSources;
2541   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2542     // Swap sources if needed.
2543     if (SwapSources)
2544       std::swap(V1, V2);
2545 
2546     // Extract the lower half of the vectors.
2547     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2548     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2549                      DAG.getConstant(0, DL, XLenVT));
2550     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2551                      DAG.getConstant(0, DL, XLenVT));
2552 
2553     // Double the element width and halve the number of elements in an int type.
2554     unsigned EltBits = VT.getScalarSizeInBits();
2555     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2556     MVT WideIntVT =
2557         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2558     // Convert this to a scalable vector. We need to base this on the
2559     // destination size to ensure there's always a type with a smaller LMUL.
2560     MVT WideIntContainerVT =
2561         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2562 
2563     // Convert sources to scalable vectors with the same element count as the
2564     // larger type.
2565     MVT HalfContainerVT = MVT::getVectorVT(
2566         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2567     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2568     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2569 
2570     // Cast sources to integer.
2571     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2572     MVT IntHalfVT =
2573         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2574     V1 = DAG.getBitcast(IntHalfVT, V1);
2575     V2 = DAG.getBitcast(IntHalfVT, V2);
2576 
2577     // Freeze V2 since we use it twice and we need to be sure that the add and
2578     // multiply see the same value.
2579     V2 = DAG.getNode(ISD::FREEZE, DL, IntHalfVT, V2);
2580 
2581     // Recreate TrueMask using the widened type's element count.
2582     MVT MaskVT =
2583         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2584     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2585 
2586     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2587     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2588                               V2, TrueMask, VL);
2589     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2590     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2591                                      DAG.getAllOnesConstant(DL, XLenVT));
2592     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2593                                    V2, Multiplier, TrueMask, VL);
2594     // Add the new copies to our previous addition giving us 2^eltbits copies of
2595     // V2. This is equivalent to shifting V2 left by eltbits. This should
2596     // combine with the vwmulu.vv above to form vwmaccu.vv.
2597     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2598                       TrueMask, VL);
2599     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2600     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2601     // vector VT.
2602     ContainerVT =
2603         MVT::getVectorVT(VT.getVectorElementType(),
2604                          WideIntContainerVT.getVectorElementCount() * 2);
2605     Add = DAG.getBitcast(ContainerVT, Add);
2606     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2607   }
2608 
2609   // Detect shuffles which can be re-expressed as vector selects; these are
2610   // shuffles in which each element in the destination is taken from an element
2611   // at the corresponding index in either source vectors.
2612   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2613     int MaskIndex = MaskIdx.value();
2614     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2615   });
2616 
2617   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2618 
2619   SmallVector<SDValue> MaskVals;
2620   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2621   // merged with a second vrgather.
2622   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2623 
2624   // By default we preserve the original operand order, and use a mask to
2625   // select LHS as true and RHS as false. However, since RVV vector selects may
2626   // feature splats but only on the LHS, we may choose to invert our mask and
2627   // instead select between RHS and LHS.
2628   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2629   bool InvertMask = IsSelect == SwapOps;
2630 
2631   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2632   // half.
2633   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2634 
2635   // Now construct the mask that will be used by the vselect or blended
2636   // vrgather operation. For vrgathers, construct the appropriate indices into
2637   // each vector.
2638   for (int MaskIndex : Mask) {
2639     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2640     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2641     if (!IsSelect) {
2642       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2643       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2644                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2645                                      : DAG.getUNDEF(XLenVT));
2646       GatherIndicesRHS.push_back(
2647           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2648                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2649       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2650         ++LHSIndexCounts[MaskIndex];
2651       if (!IsLHSOrUndefIndex)
2652         ++RHSIndexCounts[MaskIndex - NumElts];
2653     }
2654   }
2655 
2656   if (SwapOps) {
2657     std::swap(V1, V2);
2658     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2659   }
2660 
2661   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2662   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2663   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2664 
2665   if (IsSelect)
2666     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2667 
2668   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2669     // On such a large vector we're unable to use i8 as the index type.
2670     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2671     // may involve vector splitting if we're already at LMUL=8, or our
2672     // user-supplied maximum fixed-length LMUL.
2673     return SDValue();
2674   }
2675 
2676   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2677   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2678   MVT IndexVT = VT.changeTypeToInteger();
2679   // Since we can't introduce illegal index types at this stage, use i16 and
2680   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2681   // than XLenVT.
2682   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2683     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2684     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2685   }
2686 
2687   MVT IndexContainerVT =
2688       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2689 
2690   SDValue Gather;
2691   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2692   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2693   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2694     Gather = lowerScalarSplat(SplatValue, VL, ContainerVT, DL, DAG, Subtarget);
2695   } else {
2696     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2697     // If only one index is used, we can use a "splat" vrgather.
2698     // TODO: We can splat the most-common index and fix-up any stragglers, if
2699     // that's beneficial.
2700     if (LHSIndexCounts.size() == 1) {
2701       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2702       Gather =
2703           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2704                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2705     } else {
2706       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2707       LHSIndices =
2708           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2709 
2710       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2711                            TrueMask, VL);
2712     }
2713   }
2714 
2715   // If a second vector operand is used by this shuffle, blend it in with an
2716   // additional vrgather.
2717   if (!V2.isUndef()) {
2718     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2719     // If only one index is used, we can use a "splat" vrgather.
2720     // TODO: We can splat the most-common index and fix-up any stragglers, if
2721     // that's beneficial.
2722     if (RHSIndexCounts.size() == 1) {
2723       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2724       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2725                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2726     } else {
2727       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2728       RHSIndices =
2729           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2730       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2731                        VL);
2732     }
2733 
2734     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2735     SelectMask =
2736         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2737 
2738     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2739                          Gather, VL);
2740   }
2741 
2742   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2743 }
2744 
2745 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2746                                      SDLoc DL, SelectionDAG &DAG,
2747                                      const RISCVSubtarget &Subtarget) {
2748   if (VT.isScalableVector())
2749     return DAG.getFPExtendOrRound(Op, DL, VT);
2750   assert(VT.isFixedLengthVector() &&
2751          "Unexpected value type for RVV FP extend/round lowering");
2752   SDValue Mask, VL;
2753   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2754   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2755                         ? RISCVISD::FP_EXTEND_VL
2756                         : RISCVISD::FP_ROUND_VL;
2757   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2758 }
2759 
2760 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2761 // the exponent.
2762 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2763   MVT VT = Op.getSimpleValueType();
2764   unsigned EltSize = VT.getScalarSizeInBits();
2765   SDValue Src = Op.getOperand(0);
2766   SDLoc DL(Op);
2767 
2768   // We need a FP type that can represent the value.
2769   // TODO: Use f16 for i8 when possible?
2770   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2771   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2772 
2773   // Legal types should have been checked in the RISCVTargetLowering
2774   // constructor.
2775   // TODO: Splitting may make sense in some cases.
2776   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2777          "Expected legal float type!");
2778 
2779   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2780   // The trailing zero count is equal to log2 of this single bit value.
2781   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2782     SDValue Neg =
2783         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2784     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2785   }
2786 
2787   // We have a legal FP type, convert to it.
2788   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2789   // Bitcast to integer and shift the exponent to the LSB.
2790   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2791   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2792   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2793   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2794                               DAG.getConstant(ShiftAmt, DL, IntVT));
2795   // Truncate back to original type to allow vnsrl.
2796   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2797   // The exponent contains log2 of the value in biased form.
2798   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2799 
2800   // For trailing zeros, we just need to subtract the bias.
2801   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2802     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2803                        DAG.getConstant(ExponentBias, DL, VT));
2804 
2805   // For leading zeros, we need to remove the bias and convert from log2 to
2806   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2807   unsigned Adjust = ExponentBias + (EltSize - 1);
2808   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2809 }
2810 
2811 // While RVV has alignment restrictions, we should always be able to load as a
2812 // legal equivalently-sized byte-typed vector instead. This method is
2813 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2814 // the load is already correctly-aligned, it returns SDValue().
2815 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2816                                                     SelectionDAG &DAG) const {
2817   auto *Load = cast<LoadSDNode>(Op);
2818   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2819 
2820   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2821                                      Load->getMemoryVT(),
2822                                      *Load->getMemOperand()))
2823     return SDValue();
2824 
2825   SDLoc DL(Op);
2826   MVT VT = Op.getSimpleValueType();
2827   unsigned EltSizeBits = VT.getScalarSizeInBits();
2828   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2829          "Unexpected unaligned RVV load type");
2830   MVT NewVT =
2831       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2832   assert(NewVT.isValid() &&
2833          "Expecting equally-sized RVV vector types to be legal");
2834   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2835                           Load->getPointerInfo(), Load->getOriginalAlign(),
2836                           Load->getMemOperand()->getFlags());
2837   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2838 }
2839 
2840 // While RVV has alignment restrictions, we should always be able to store as a
2841 // legal equivalently-sized byte-typed vector instead. This method is
2842 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
2843 // returns SDValue() if the store is already correctly aligned.
2844 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
2845                                                      SelectionDAG &DAG) const {
2846   auto *Store = cast<StoreSDNode>(Op);
2847   assert(Store && Store->getValue().getValueType().isVector() &&
2848          "Expected vector store");
2849 
2850   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2851                                      Store->getMemoryVT(),
2852                                      *Store->getMemOperand()))
2853     return SDValue();
2854 
2855   SDLoc DL(Op);
2856   SDValue StoredVal = Store->getValue();
2857   MVT VT = StoredVal.getSimpleValueType();
2858   unsigned EltSizeBits = VT.getScalarSizeInBits();
2859   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2860          "Unexpected unaligned RVV store type");
2861   MVT NewVT =
2862       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2863   assert(NewVT.isValid() &&
2864          "Expecting equally-sized RVV vector types to be legal");
2865   StoredVal = DAG.getBitcast(NewVT, StoredVal);
2866   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
2867                       Store->getPointerInfo(), Store->getOriginalAlign(),
2868                       Store->getMemOperand()->getFlags());
2869 }
2870 
2871 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
2872                                             SelectionDAG &DAG) const {
2873   switch (Op.getOpcode()) {
2874   default:
2875     report_fatal_error("unimplemented operand");
2876   case ISD::GlobalAddress:
2877     return lowerGlobalAddress(Op, DAG);
2878   case ISD::BlockAddress:
2879     return lowerBlockAddress(Op, DAG);
2880   case ISD::ConstantPool:
2881     return lowerConstantPool(Op, DAG);
2882   case ISD::JumpTable:
2883     return lowerJumpTable(Op, DAG);
2884   case ISD::GlobalTLSAddress:
2885     return lowerGlobalTLSAddress(Op, DAG);
2886   case ISD::SELECT:
2887     return lowerSELECT(Op, DAG);
2888   case ISD::BRCOND:
2889     return lowerBRCOND(Op, DAG);
2890   case ISD::VASTART:
2891     return lowerVASTART(Op, DAG);
2892   case ISD::FRAMEADDR:
2893     return lowerFRAMEADDR(Op, DAG);
2894   case ISD::RETURNADDR:
2895     return lowerRETURNADDR(Op, DAG);
2896   case ISD::SHL_PARTS:
2897     return lowerShiftLeftParts(Op, DAG);
2898   case ISD::SRA_PARTS:
2899     return lowerShiftRightParts(Op, DAG, true);
2900   case ISD::SRL_PARTS:
2901     return lowerShiftRightParts(Op, DAG, false);
2902   case ISD::BITCAST: {
2903     SDLoc DL(Op);
2904     EVT VT = Op.getValueType();
2905     SDValue Op0 = Op.getOperand(0);
2906     EVT Op0VT = Op0.getValueType();
2907     MVT XLenVT = Subtarget.getXLenVT();
2908     if (VT.isFixedLengthVector()) {
2909       // We can handle fixed length vector bitcasts with a simple replacement
2910       // in isel.
2911       if (Op0VT.isFixedLengthVector())
2912         return Op;
2913       // When bitcasting from scalar to fixed-length vector, insert the scalar
2914       // into a one-element vector of the result type, and perform a vector
2915       // bitcast.
2916       if (!Op0VT.isVector()) {
2917         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
2918         if (!isTypeLegal(BVT))
2919           return SDValue();
2920         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
2921                                               DAG.getUNDEF(BVT), Op0,
2922                                               DAG.getConstant(0, DL, XLenVT)));
2923       }
2924       return SDValue();
2925     }
2926     // Custom-legalize bitcasts from fixed-length vector types to scalar types
2927     // thus: bitcast the vector to a one-element vector type whose element type
2928     // is the same as the result type, and extract the first element.
2929     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
2930       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
2931       if (!isTypeLegal(BVT))
2932         return SDValue();
2933       SDValue BVec = DAG.getBitcast(BVT, Op0);
2934       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
2935                          DAG.getConstant(0, DL, XLenVT));
2936     }
2937     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
2938       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
2939       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
2940       return FPConv;
2941     }
2942     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
2943         Subtarget.hasStdExtF()) {
2944       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
2945       SDValue FPConv =
2946           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
2947       return FPConv;
2948     }
2949     return SDValue();
2950   }
2951   case ISD::INTRINSIC_WO_CHAIN:
2952     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2953   case ISD::INTRINSIC_W_CHAIN:
2954     return LowerINTRINSIC_W_CHAIN(Op, DAG);
2955   case ISD::INTRINSIC_VOID:
2956     return LowerINTRINSIC_VOID(Op, DAG);
2957   case ISD::BSWAP:
2958   case ISD::BITREVERSE: {
2959     MVT VT = Op.getSimpleValueType();
2960     SDLoc DL(Op);
2961     if (Subtarget.hasStdExtZbp()) {
2962       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
2963       // Start with the maximum immediate value which is the bitwidth - 1.
2964       unsigned Imm = VT.getSizeInBits() - 1;
2965       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
2966       if (Op.getOpcode() == ISD::BSWAP)
2967         Imm &= ~0x7U;
2968       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
2969                          DAG.getConstant(Imm, DL, VT));
2970     }
2971     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
2972     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
2973     // Expand bitreverse to a bswap(rev8) followed by brev8.
2974     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
2975     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
2976     // as brev8 by an isel pattern.
2977     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
2978                        DAG.getConstant(7, DL, VT));
2979   }
2980   case ISD::FSHL:
2981   case ISD::FSHR: {
2982     MVT VT = Op.getSimpleValueType();
2983     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
2984     SDLoc DL(Op);
2985     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
2986     // use log(XLen) bits. Mask the shift amount accordingly to prevent
2987     // accidentally setting the extra bit.
2988     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
2989     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
2990                                 DAG.getConstant(ShAmtWidth, DL, VT));
2991     // fshl and fshr concatenate their operands in the same order. fsr and fsl
2992     // instruction use different orders. fshl will return its first operand for
2993     // shift of zero, fshr will return its second operand. fsl and fsr both
2994     // return rs1 so the ISD nodes need to have different operand orders.
2995     // Shift amount is in rs2.
2996     SDValue Op0 = Op.getOperand(0);
2997     SDValue Op1 = Op.getOperand(1);
2998     unsigned Opc = RISCVISD::FSL;
2999     if (Op.getOpcode() == ISD::FSHR) {
3000       std::swap(Op0, Op1);
3001       Opc = RISCVISD::FSR;
3002     }
3003     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3004   }
3005   case ISD::TRUNCATE: {
3006     SDLoc DL(Op);
3007     MVT VT = Op.getSimpleValueType();
3008     // Only custom-lower vector truncates
3009     if (!VT.isVector())
3010       return Op;
3011 
3012     // Truncates to mask types are handled differently
3013     if (VT.getVectorElementType() == MVT::i1)
3014       return lowerVectorMaskTrunc(Op, DAG);
3015 
3016     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
3017     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
3018     // truncate by one power of two at a time.
3019     MVT DstEltVT = VT.getVectorElementType();
3020 
3021     SDValue Src = Op.getOperand(0);
3022     MVT SrcVT = Src.getSimpleValueType();
3023     MVT SrcEltVT = SrcVT.getVectorElementType();
3024 
3025     assert(DstEltVT.bitsLT(SrcEltVT) &&
3026            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
3027            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
3028            "Unexpected vector truncate lowering");
3029 
3030     MVT ContainerVT = SrcVT;
3031     if (SrcVT.isFixedLengthVector()) {
3032       ContainerVT = getContainerForFixedLengthVector(SrcVT);
3033       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3034     }
3035 
3036     SDValue Result = Src;
3037     SDValue Mask, VL;
3038     std::tie(Mask, VL) =
3039         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
3040     LLVMContext &Context = *DAG.getContext();
3041     const ElementCount Count = ContainerVT.getVectorElementCount();
3042     do {
3043       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
3044       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
3045       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
3046                            Mask, VL);
3047     } while (SrcEltVT != DstEltVT);
3048 
3049     if (SrcVT.isFixedLengthVector())
3050       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3051 
3052     return Result;
3053   }
3054   case ISD::ANY_EXTEND:
3055   case ISD::ZERO_EXTEND:
3056     if (Op.getOperand(0).getValueType().isVector() &&
3057         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3058       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3059     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3060   case ISD::SIGN_EXTEND:
3061     if (Op.getOperand(0).getValueType().isVector() &&
3062         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3063       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3064     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3065   case ISD::SPLAT_VECTOR_PARTS:
3066     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3067   case ISD::INSERT_VECTOR_ELT:
3068     return lowerINSERT_VECTOR_ELT(Op, DAG);
3069   case ISD::EXTRACT_VECTOR_ELT:
3070     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3071   case ISD::VSCALE: {
3072     MVT VT = Op.getSimpleValueType();
3073     SDLoc DL(Op);
3074     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3075     // We define our scalable vector types for lmul=1 to use a 64 bit known
3076     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3077     // vscale as VLENB / 8.
3078     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3079     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3080       report_fatal_error("Support for VLEN==32 is incomplete.");
3081     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3082       // We assume VLENB is a multiple of 8. We manually choose the best shift
3083       // here because SimplifyDemandedBits isn't always able to simplify it.
3084       uint64_t Val = Op.getConstantOperandVal(0);
3085       if (isPowerOf2_64(Val)) {
3086         uint64_t Log2 = Log2_64(Val);
3087         if (Log2 < 3)
3088           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3089                              DAG.getConstant(3 - Log2, DL, VT));
3090         if (Log2 > 3)
3091           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3092                              DAG.getConstant(Log2 - 3, DL, VT));
3093         return VLENB;
3094       }
3095       // If the multiplier is a multiple of 8, scale it down to avoid needing
3096       // to shift the VLENB value.
3097       if ((Val % 8) == 0)
3098         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3099                            DAG.getConstant(Val / 8, DL, VT));
3100     }
3101 
3102     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3103                                  DAG.getConstant(3, DL, VT));
3104     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3105   }
3106   case ISD::FPOWI: {
3107     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3108     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3109     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3110         Op.getOperand(1).getValueType() == MVT::i32) {
3111       SDLoc DL(Op);
3112       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3113       SDValue Powi =
3114           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3115       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3116                          DAG.getIntPtrConstant(0, DL));
3117     }
3118     return SDValue();
3119   }
3120   case ISD::FP_EXTEND: {
3121     // RVV can only do fp_extend to types double the size as the source. We
3122     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3123     // via f32.
3124     SDLoc DL(Op);
3125     MVT VT = Op.getSimpleValueType();
3126     SDValue Src = Op.getOperand(0);
3127     MVT SrcVT = Src.getSimpleValueType();
3128 
3129     // Prepare any fixed-length vector operands.
3130     MVT ContainerVT = VT;
3131     if (SrcVT.isFixedLengthVector()) {
3132       ContainerVT = getContainerForFixedLengthVector(VT);
3133       MVT SrcContainerVT =
3134           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3135       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3136     }
3137 
3138     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3139         SrcVT.getVectorElementType() != MVT::f16) {
3140       // For scalable vectors, we only need to close the gap between
3141       // vXf16->vXf64.
3142       if (!VT.isFixedLengthVector())
3143         return Op;
3144       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3145       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3146       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3147     }
3148 
3149     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3150     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3151     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3152         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3153 
3154     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3155                                            DL, DAG, Subtarget);
3156     if (VT.isFixedLengthVector())
3157       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3158     return Extend;
3159   }
3160   case ISD::FP_ROUND: {
3161     // RVV can only do fp_round to types half the size as the source. We
3162     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3163     // conversion instruction.
3164     SDLoc DL(Op);
3165     MVT VT = Op.getSimpleValueType();
3166     SDValue Src = Op.getOperand(0);
3167     MVT SrcVT = Src.getSimpleValueType();
3168 
3169     // Prepare any fixed-length vector operands.
3170     MVT ContainerVT = VT;
3171     if (VT.isFixedLengthVector()) {
3172       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3173       ContainerVT =
3174           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3175       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3176     }
3177 
3178     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3179         SrcVT.getVectorElementType() != MVT::f64) {
3180       // For scalable vectors, we only need to close the gap between
3181       // vXf64<->vXf16.
3182       if (!VT.isFixedLengthVector())
3183         return Op;
3184       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3185       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3186       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3187     }
3188 
3189     SDValue Mask, VL;
3190     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3191 
3192     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3193     SDValue IntermediateRound =
3194         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3195     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3196                                           DL, DAG, Subtarget);
3197 
3198     if (VT.isFixedLengthVector())
3199       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3200     return Round;
3201   }
3202   case ISD::FP_TO_SINT:
3203   case ISD::FP_TO_UINT:
3204   case ISD::SINT_TO_FP:
3205   case ISD::UINT_TO_FP: {
3206     // RVV can only do fp<->int conversions to types half/double the size as
3207     // the source. We custom-lower any conversions that do two hops into
3208     // sequences.
3209     MVT VT = Op.getSimpleValueType();
3210     if (!VT.isVector())
3211       return Op;
3212     SDLoc DL(Op);
3213     SDValue Src = Op.getOperand(0);
3214     MVT EltVT = VT.getVectorElementType();
3215     MVT SrcVT = Src.getSimpleValueType();
3216     MVT SrcEltVT = SrcVT.getVectorElementType();
3217     unsigned EltSize = EltVT.getSizeInBits();
3218     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3219     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3220            "Unexpected vector element types");
3221 
3222     bool IsInt2FP = SrcEltVT.isInteger();
3223     // Widening conversions
3224     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
3225       if (IsInt2FP) {
3226         // Do a regular integer sign/zero extension then convert to float.
3227         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
3228                                       VT.getVectorElementCount());
3229         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3230                                  ? ISD::ZERO_EXTEND
3231                                  : ISD::SIGN_EXTEND;
3232         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3233         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3234       }
3235       // FP2Int
3236       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3237       // Do one doubling fp_extend then complete the operation by converting
3238       // to int.
3239       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3240       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3241       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3242     }
3243 
3244     // Narrowing conversions
3245     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
3246       if (IsInt2FP) {
3247         // One narrowing int_to_fp, then an fp_round.
3248         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3249         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3250         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3251         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3252       }
3253       // FP2Int
3254       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3255       // representable by the integer, the result is poison.
3256       MVT IVecVT =
3257           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
3258                            VT.getVectorElementCount());
3259       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3260       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3261     }
3262 
3263     // Scalable vectors can exit here. Patterns will handle equally-sized
3264     // conversions halving/doubling ones.
3265     if (!VT.isFixedLengthVector())
3266       return Op;
3267 
3268     // For fixed-length vectors we lower to a custom "VL" node.
3269     unsigned RVVOpc = 0;
3270     switch (Op.getOpcode()) {
3271     default:
3272       llvm_unreachable("Impossible opcode");
3273     case ISD::FP_TO_SINT:
3274       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3275       break;
3276     case ISD::FP_TO_UINT:
3277       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3278       break;
3279     case ISD::SINT_TO_FP:
3280       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3281       break;
3282     case ISD::UINT_TO_FP:
3283       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3284       break;
3285     }
3286 
3287     MVT ContainerVT, SrcContainerVT;
3288     // Derive the reference container type from the larger vector type.
3289     if (SrcEltSize > EltSize) {
3290       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3291       ContainerVT =
3292           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3293     } else {
3294       ContainerVT = getContainerForFixedLengthVector(VT);
3295       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3296     }
3297 
3298     SDValue Mask, VL;
3299     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3300 
3301     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3302     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3303     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3304   }
3305   case ISD::FP_TO_SINT_SAT:
3306   case ISD::FP_TO_UINT_SAT:
3307     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3308   case ISD::FTRUNC:
3309   case ISD::FCEIL:
3310   case ISD::FFLOOR:
3311     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3312   case ISD::VECREDUCE_ADD:
3313   case ISD::VECREDUCE_UMAX:
3314   case ISD::VECREDUCE_SMAX:
3315   case ISD::VECREDUCE_UMIN:
3316   case ISD::VECREDUCE_SMIN:
3317     return lowerVECREDUCE(Op, DAG);
3318   case ISD::VECREDUCE_AND:
3319   case ISD::VECREDUCE_OR:
3320   case ISD::VECREDUCE_XOR:
3321     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3322       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3323     return lowerVECREDUCE(Op, DAG);
3324   case ISD::VECREDUCE_FADD:
3325   case ISD::VECREDUCE_SEQ_FADD:
3326   case ISD::VECREDUCE_FMIN:
3327   case ISD::VECREDUCE_FMAX:
3328     return lowerFPVECREDUCE(Op, DAG);
3329   case ISD::VP_REDUCE_ADD:
3330   case ISD::VP_REDUCE_UMAX:
3331   case ISD::VP_REDUCE_SMAX:
3332   case ISD::VP_REDUCE_UMIN:
3333   case ISD::VP_REDUCE_SMIN:
3334   case ISD::VP_REDUCE_FADD:
3335   case ISD::VP_REDUCE_SEQ_FADD:
3336   case ISD::VP_REDUCE_FMIN:
3337   case ISD::VP_REDUCE_FMAX:
3338     return lowerVPREDUCE(Op, DAG);
3339   case ISD::VP_REDUCE_AND:
3340   case ISD::VP_REDUCE_OR:
3341   case ISD::VP_REDUCE_XOR:
3342     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3343       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3344     return lowerVPREDUCE(Op, DAG);
3345   case ISD::INSERT_SUBVECTOR:
3346     return lowerINSERT_SUBVECTOR(Op, DAG);
3347   case ISD::EXTRACT_SUBVECTOR:
3348     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3349   case ISD::STEP_VECTOR:
3350     return lowerSTEP_VECTOR(Op, DAG);
3351   case ISD::VECTOR_REVERSE:
3352     return lowerVECTOR_REVERSE(Op, DAG);
3353   case ISD::BUILD_VECTOR:
3354     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3355   case ISD::SPLAT_VECTOR:
3356     if (Op.getValueType().getVectorElementType() == MVT::i1)
3357       return lowerVectorMaskSplat(Op, DAG);
3358     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3359   case ISD::VECTOR_SHUFFLE:
3360     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3361   case ISD::CONCAT_VECTORS: {
3362     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3363     // better than going through the stack, as the default expansion does.
3364     SDLoc DL(Op);
3365     MVT VT = Op.getSimpleValueType();
3366     unsigned NumOpElts =
3367         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3368     SDValue Vec = DAG.getUNDEF(VT);
3369     for (const auto &OpIdx : enumerate(Op->ops())) {
3370       SDValue SubVec = OpIdx.value();
3371       // Don't insert undef subvectors.
3372       if (SubVec.isUndef())
3373         continue;
3374       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3375                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3376     }
3377     return Vec;
3378   }
3379   case ISD::LOAD:
3380     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3381       return V;
3382     if (Op.getValueType().isFixedLengthVector())
3383       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3384     return Op;
3385   case ISD::STORE:
3386     if (auto V = expandUnalignedRVVStore(Op, DAG))
3387       return V;
3388     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3389       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3390     return Op;
3391   case ISD::MLOAD:
3392   case ISD::VP_LOAD:
3393     return lowerMaskedLoad(Op, DAG);
3394   case ISD::MSTORE:
3395   case ISD::VP_STORE:
3396     return lowerMaskedStore(Op, DAG);
3397   case ISD::SETCC:
3398     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3399   case ISD::ADD:
3400     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3401   case ISD::SUB:
3402     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3403   case ISD::MUL:
3404     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3405   case ISD::MULHS:
3406     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3407   case ISD::MULHU:
3408     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3409   case ISD::AND:
3410     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3411                                               RISCVISD::AND_VL);
3412   case ISD::OR:
3413     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3414                                               RISCVISD::OR_VL);
3415   case ISD::XOR:
3416     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3417                                               RISCVISD::XOR_VL);
3418   case ISD::SDIV:
3419     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3420   case ISD::SREM:
3421     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3422   case ISD::UDIV:
3423     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3424   case ISD::UREM:
3425     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3426   case ISD::SHL:
3427   case ISD::SRA:
3428   case ISD::SRL:
3429     if (Op.getSimpleValueType().isFixedLengthVector())
3430       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3431     // This can be called for an i32 shift amount that needs to be promoted.
3432     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3433            "Unexpected custom legalisation");
3434     return SDValue();
3435   case ISD::SADDSAT:
3436     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3437   case ISD::UADDSAT:
3438     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3439   case ISD::SSUBSAT:
3440     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3441   case ISD::USUBSAT:
3442     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3443   case ISD::FADD:
3444     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3445   case ISD::FSUB:
3446     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3447   case ISD::FMUL:
3448     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3449   case ISD::FDIV:
3450     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3451   case ISD::FNEG:
3452     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3453   case ISD::FABS:
3454     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3455   case ISD::FSQRT:
3456     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3457   case ISD::FMA:
3458     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3459   case ISD::SMIN:
3460     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3461   case ISD::SMAX:
3462     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3463   case ISD::UMIN:
3464     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3465   case ISD::UMAX:
3466     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3467   case ISD::FMINNUM:
3468     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3469   case ISD::FMAXNUM:
3470     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3471   case ISD::ABS:
3472     return lowerABS(Op, DAG);
3473   case ISD::CTLZ_ZERO_UNDEF:
3474   case ISD::CTTZ_ZERO_UNDEF:
3475     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3476   case ISD::VSELECT:
3477     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3478   case ISD::FCOPYSIGN:
3479     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3480   case ISD::MGATHER:
3481   case ISD::VP_GATHER:
3482     return lowerMaskedGather(Op, DAG);
3483   case ISD::MSCATTER:
3484   case ISD::VP_SCATTER:
3485     return lowerMaskedScatter(Op, DAG);
3486   case ISD::FLT_ROUNDS_:
3487     return lowerGET_ROUNDING(Op, DAG);
3488   case ISD::SET_ROUNDING:
3489     return lowerSET_ROUNDING(Op, DAG);
3490   case ISD::VP_SELECT:
3491     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3492   case ISD::VP_MERGE:
3493     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3494   case ISD::VP_ADD:
3495     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3496   case ISD::VP_SUB:
3497     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3498   case ISD::VP_MUL:
3499     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3500   case ISD::VP_SDIV:
3501     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3502   case ISD::VP_UDIV:
3503     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3504   case ISD::VP_SREM:
3505     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3506   case ISD::VP_UREM:
3507     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3508   case ISD::VP_AND:
3509     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3510   case ISD::VP_OR:
3511     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3512   case ISD::VP_XOR:
3513     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3514   case ISD::VP_ASHR:
3515     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3516   case ISD::VP_LSHR:
3517     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3518   case ISD::VP_SHL:
3519     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3520   case ISD::VP_FADD:
3521     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3522   case ISD::VP_FSUB:
3523     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3524   case ISD::VP_FMUL:
3525     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3526   case ISD::VP_FDIV:
3527     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3528   }
3529 }
3530 
3531 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3532                              SelectionDAG &DAG, unsigned Flags) {
3533   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3534 }
3535 
3536 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3537                              SelectionDAG &DAG, unsigned Flags) {
3538   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3539                                    Flags);
3540 }
3541 
3542 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3543                              SelectionDAG &DAG, unsigned Flags) {
3544   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3545                                    N->getOffset(), Flags);
3546 }
3547 
3548 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3549                              SelectionDAG &DAG, unsigned Flags) {
3550   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3551 }
3552 
3553 template <class NodeTy>
3554 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3555                                      bool IsLocal) const {
3556   SDLoc DL(N);
3557   EVT Ty = getPointerTy(DAG.getDataLayout());
3558 
3559   if (isPositionIndependent()) {
3560     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3561     if (IsLocal)
3562       // Use PC-relative addressing to access the symbol. This generates the
3563       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3564       // %pcrel_lo(auipc)).
3565       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3566 
3567     // Use PC-relative addressing to access the GOT for this symbol, then load
3568     // the address from the GOT. This generates the pattern (PseudoLA sym),
3569     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3570     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3571   }
3572 
3573   switch (getTargetMachine().getCodeModel()) {
3574   default:
3575     report_fatal_error("Unsupported code model for lowering");
3576   case CodeModel::Small: {
3577     // Generate a sequence for accessing addresses within the first 2 GiB of
3578     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3579     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3580     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3581     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3582     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3583   }
3584   case CodeModel::Medium: {
3585     // Generate a sequence for accessing addresses within any 2GiB range within
3586     // the address space. This generates the pattern (PseudoLLA sym), which
3587     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3588     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3589     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3590   }
3591   }
3592 }
3593 
3594 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3595                                                 SelectionDAG &DAG) const {
3596   SDLoc DL(Op);
3597   EVT Ty = Op.getValueType();
3598   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3599   int64_t Offset = N->getOffset();
3600   MVT XLenVT = Subtarget.getXLenVT();
3601 
3602   const GlobalValue *GV = N->getGlobal();
3603   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3604   SDValue Addr = getAddr(N, DAG, IsLocal);
3605 
3606   // In order to maximise the opportunity for common subexpression elimination,
3607   // emit a separate ADD node for the global address offset instead of folding
3608   // it in the global address node. Later peephole optimisations may choose to
3609   // fold it back in when profitable.
3610   if (Offset != 0)
3611     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3612                        DAG.getConstant(Offset, DL, XLenVT));
3613   return Addr;
3614 }
3615 
3616 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3617                                                SelectionDAG &DAG) const {
3618   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3619 
3620   return getAddr(N, DAG);
3621 }
3622 
3623 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3624                                                SelectionDAG &DAG) const {
3625   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3626 
3627   return getAddr(N, DAG);
3628 }
3629 
3630 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3631                                             SelectionDAG &DAG) const {
3632   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3633 
3634   return getAddr(N, DAG);
3635 }
3636 
3637 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3638                                               SelectionDAG &DAG,
3639                                               bool UseGOT) const {
3640   SDLoc DL(N);
3641   EVT Ty = getPointerTy(DAG.getDataLayout());
3642   const GlobalValue *GV = N->getGlobal();
3643   MVT XLenVT = Subtarget.getXLenVT();
3644 
3645   if (UseGOT) {
3646     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3647     // load the address from the GOT and add the thread pointer. This generates
3648     // the pattern (PseudoLA_TLS_IE sym), which expands to
3649     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3650     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3651     SDValue Load =
3652         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3653 
3654     // Add the thread pointer.
3655     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3656     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3657   }
3658 
3659   // Generate a sequence for accessing the address relative to the thread
3660   // pointer, with the appropriate adjustment for the thread pointer offset.
3661   // This generates the pattern
3662   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3663   SDValue AddrHi =
3664       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3665   SDValue AddrAdd =
3666       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3667   SDValue AddrLo =
3668       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3669 
3670   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3671   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3672   SDValue MNAdd = SDValue(
3673       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3674       0);
3675   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3676 }
3677 
3678 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3679                                                SelectionDAG &DAG) const {
3680   SDLoc DL(N);
3681   EVT Ty = getPointerTy(DAG.getDataLayout());
3682   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3683   const GlobalValue *GV = N->getGlobal();
3684 
3685   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3686   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3687   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3688   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3689   SDValue Load =
3690       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3691 
3692   // Prepare argument list to generate call.
3693   ArgListTy Args;
3694   ArgListEntry Entry;
3695   Entry.Node = Load;
3696   Entry.Ty = CallTy;
3697   Args.push_back(Entry);
3698 
3699   // Setup call to __tls_get_addr.
3700   TargetLowering::CallLoweringInfo CLI(DAG);
3701   CLI.setDebugLoc(DL)
3702       .setChain(DAG.getEntryNode())
3703       .setLibCallee(CallingConv::C, CallTy,
3704                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3705                     std::move(Args));
3706 
3707   return LowerCallTo(CLI).first;
3708 }
3709 
3710 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3711                                                    SelectionDAG &DAG) const {
3712   SDLoc DL(Op);
3713   EVT Ty = Op.getValueType();
3714   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3715   int64_t Offset = N->getOffset();
3716   MVT XLenVT = Subtarget.getXLenVT();
3717 
3718   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3719 
3720   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3721       CallingConv::GHC)
3722     report_fatal_error("In GHC calling convention TLS is not supported");
3723 
3724   SDValue Addr;
3725   switch (Model) {
3726   case TLSModel::LocalExec:
3727     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3728     break;
3729   case TLSModel::InitialExec:
3730     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3731     break;
3732   case TLSModel::LocalDynamic:
3733   case TLSModel::GeneralDynamic:
3734     Addr = getDynamicTLSAddr(N, DAG);
3735     break;
3736   }
3737 
3738   // In order to maximise the opportunity for common subexpression elimination,
3739   // emit a separate ADD node for the global address offset instead of folding
3740   // it in the global address node. Later peephole optimisations may choose to
3741   // fold it back in when profitable.
3742   if (Offset != 0)
3743     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3744                        DAG.getConstant(Offset, DL, XLenVT));
3745   return Addr;
3746 }
3747 
3748 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3749   SDValue CondV = Op.getOperand(0);
3750   SDValue TrueV = Op.getOperand(1);
3751   SDValue FalseV = Op.getOperand(2);
3752   SDLoc DL(Op);
3753   MVT VT = Op.getSimpleValueType();
3754   MVT XLenVT = Subtarget.getXLenVT();
3755 
3756   // Lower vector SELECTs to VSELECTs by splatting the condition.
3757   if (VT.isVector()) {
3758     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3759     SDValue CondSplat = VT.isScalableVector()
3760                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3761                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3762     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3763   }
3764 
3765   // If the result type is XLenVT and CondV is the output of a SETCC node
3766   // which also operated on XLenVT inputs, then merge the SETCC node into the
3767   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3768   // compare+branch instructions. i.e.:
3769   // (select (setcc lhs, rhs, cc), truev, falsev)
3770   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3771   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3772       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3773     SDValue LHS = CondV.getOperand(0);
3774     SDValue RHS = CondV.getOperand(1);
3775     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3776     ISD::CondCode CCVal = CC->get();
3777 
3778     // Special case for a select of 2 constants that have a diffence of 1.
3779     // Normally this is done by DAGCombine, but if the select is introduced by
3780     // type legalization or op legalization, we miss it. Restricting to SETLT
3781     // case for now because that is what signed saturating add/sub need.
3782     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3783     // but we would probably want to swap the true/false values if the condition
3784     // is SETGE/SETLE to avoid an XORI.
3785     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3786         CCVal == ISD::SETLT) {
3787       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3788       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3789       if (TrueVal - 1 == FalseVal)
3790         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3791       if (TrueVal + 1 == FalseVal)
3792         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3793     }
3794 
3795     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3796 
3797     SDValue TargetCC = DAG.getCondCode(CCVal);
3798     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3799     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3800   }
3801 
3802   // Otherwise:
3803   // (select condv, truev, falsev)
3804   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3805   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3806   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3807 
3808   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3809 
3810   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3811 }
3812 
3813 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3814   SDValue CondV = Op.getOperand(1);
3815   SDLoc DL(Op);
3816   MVT XLenVT = Subtarget.getXLenVT();
3817 
3818   if (CondV.getOpcode() == ISD::SETCC &&
3819       CondV.getOperand(0).getValueType() == XLenVT) {
3820     SDValue LHS = CondV.getOperand(0);
3821     SDValue RHS = CondV.getOperand(1);
3822     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3823 
3824     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3825 
3826     SDValue TargetCC = DAG.getCondCode(CCVal);
3827     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3828                        LHS, RHS, TargetCC, Op.getOperand(2));
3829   }
3830 
3831   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3832                      CondV, DAG.getConstant(0, DL, XLenVT),
3833                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3834 }
3835 
3836 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3837   MachineFunction &MF = DAG.getMachineFunction();
3838   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3839 
3840   SDLoc DL(Op);
3841   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3842                                  getPointerTy(MF.getDataLayout()));
3843 
3844   // vastart just stores the address of the VarArgsFrameIndex slot into the
3845   // memory location argument.
3846   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3847   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3848                       MachinePointerInfo(SV));
3849 }
3850 
3851 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3852                                             SelectionDAG &DAG) const {
3853   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3854   MachineFunction &MF = DAG.getMachineFunction();
3855   MachineFrameInfo &MFI = MF.getFrameInfo();
3856   MFI.setFrameAddressIsTaken(true);
3857   Register FrameReg = RI.getFrameRegister(MF);
3858   int XLenInBytes = Subtarget.getXLen() / 8;
3859 
3860   EVT VT = Op.getValueType();
3861   SDLoc DL(Op);
3862   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
3863   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3864   while (Depth--) {
3865     int Offset = -(XLenInBytes * 2);
3866     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
3867                               DAG.getIntPtrConstant(Offset, DL));
3868     FrameAddr =
3869         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
3870   }
3871   return FrameAddr;
3872 }
3873 
3874 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
3875                                              SelectionDAG &DAG) const {
3876   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
3877   MachineFunction &MF = DAG.getMachineFunction();
3878   MachineFrameInfo &MFI = MF.getFrameInfo();
3879   MFI.setReturnAddressIsTaken(true);
3880   MVT XLenVT = Subtarget.getXLenVT();
3881   int XLenInBytes = Subtarget.getXLen() / 8;
3882 
3883   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3884     return SDValue();
3885 
3886   EVT VT = Op.getValueType();
3887   SDLoc DL(Op);
3888   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3889   if (Depth) {
3890     int Off = -XLenInBytes;
3891     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
3892     SDValue Offset = DAG.getConstant(Off, DL, VT);
3893     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3894                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3895                        MachinePointerInfo());
3896   }
3897 
3898   // Return the value of the return address register, marking it an implicit
3899   // live-in.
3900   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
3901   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
3902 }
3903 
3904 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
3905                                                  SelectionDAG &DAG) const {
3906   SDLoc DL(Op);
3907   SDValue Lo = Op.getOperand(0);
3908   SDValue Hi = Op.getOperand(1);
3909   SDValue Shamt = Op.getOperand(2);
3910   EVT VT = Lo.getValueType();
3911 
3912   // if Shamt-XLEN < 0: // Shamt < XLEN
3913   //   Lo = Lo << Shamt
3914   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 - Shamt))
3915   // else:
3916   //   Lo = 0
3917   //   Hi = Lo << (Shamt-XLEN)
3918 
3919   SDValue Zero = DAG.getConstant(0, DL, VT);
3920   SDValue One = DAG.getConstant(1, DL, VT);
3921   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3922   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3923   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3924   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3925 
3926   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
3927   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
3928   SDValue ShiftRightLo =
3929       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
3930   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
3931   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
3932   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
3933 
3934   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3935 
3936   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
3937   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3938 
3939   SDValue Parts[2] = {Lo, Hi};
3940   return DAG.getMergeValues(Parts, DL);
3941 }
3942 
3943 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
3944                                                   bool IsSRA) const {
3945   SDLoc DL(Op);
3946   SDValue Lo = Op.getOperand(0);
3947   SDValue Hi = Op.getOperand(1);
3948   SDValue Shamt = Op.getOperand(2);
3949   EVT VT = Lo.getValueType();
3950 
3951   // SRA expansion:
3952   //   if Shamt-XLEN < 0: // Shamt < XLEN
3953   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3954   //     Hi = Hi >>s Shamt
3955   //   else:
3956   //     Lo = Hi >>s (Shamt-XLEN);
3957   //     Hi = Hi >>s (XLEN-1)
3958   //
3959   // SRL expansion:
3960   //   if Shamt-XLEN < 0: // Shamt < XLEN
3961   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (XLEN-1 - Shamt))
3962   //     Hi = Hi >>u Shamt
3963   //   else:
3964   //     Lo = Hi >>u (Shamt-XLEN);
3965   //     Hi = 0;
3966 
3967   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
3968 
3969   SDValue Zero = DAG.getConstant(0, DL, VT);
3970   SDValue One = DAG.getConstant(1, DL, VT);
3971   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
3972   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
3973   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
3974   SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
3975 
3976   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
3977   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
3978   SDValue ShiftLeftHi =
3979       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
3980   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
3981   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
3982   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
3983   SDValue HiFalse =
3984       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
3985 
3986   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
3987 
3988   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
3989   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
3990 
3991   SDValue Parts[2] = {Lo, Hi};
3992   return DAG.getMergeValues(Parts, DL);
3993 }
3994 
3995 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
3996 // legal equivalently-sized i8 type, so we can use that as a go-between.
3997 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
3998                                                   SelectionDAG &DAG) const {
3999   SDLoc DL(Op);
4000   MVT VT = Op.getSimpleValueType();
4001   SDValue SplatVal = Op.getOperand(0);
4002   // All-zeros or all-ones splats are handled specially.
4003   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4004     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4005     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4006   }
4007   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4008     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4009     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4010   }
4011   MVT XLenVT = Subtarget.getXLenVT();
4012   assert(SplatVal.getValueType() == XLenVT &&
4013          "Unexpected type for i1 splat value");
4014   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4015   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4016                          DAG.getConstant(1, DL, XLenVT));
4017   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4018   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4019   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4020 }
4021 
4022 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4023 // illegal (currently only vXi64 RV32).
4024 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4025 // them to SPLAT_VECTOR_I64
4026 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4027                                                      SelectionDAG &DAG) const {
4028   SDLoc DL(Op);
4029   MVT VecVT = Op.getSimpleValueType();
4030   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4031          "Unexpected SPLAT_VECTOR_PARTS lowering");
4032 
4033   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4034   SDValue Lo = Op.getOperand(0);
4035   SDValue Hi = Op.getOperand(1);
4036 
4037   if (VecVT.isFixedLengthVector()) {
4038     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4039     SDLoc DL(Op);
4040     SDValue Mask, VL;
4041     std::tie(Mask, VL) =
4042         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4043 
4044     SDValue Res = splatPartsI64WithVL(DL, ContainerVT, Lo, Hi, VL, DAG);
4045     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4046   }
4047 
4048   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4049     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4050     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4051     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4052     // node in order to try and match RVV vector/scalar instructions.
4053     if ((LoC >> 31) == HiC)
4054       return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
4055   }
4056 
4057   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4058   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4059       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4060       Hi.getConstantOperandVal(1) == 31)
4061     return DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, Lo);
4062 
4063   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4064   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, Lo, Hi,
4065                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, MVT::i64));
4066 }
4067 
4068 // Custom-lower extensions from mask vectors by using a vselect either with 1
4069 // for zero/any-extension or -1 for sign-extension:
4070 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4071 // Note that any-extension is lowered identically to zero-extension.
4072 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4073                                                 int64_t ExtTrueVal) const {
4074   SDLoc DL(Op);
4075   MVT VecVT = Op.getSimpleValueType();
4076   SDValue Src = Op.getOperand(0);
4077   // Only custom-lower extensions from mask types
4078   assert(Src.getValueType().isVector() &&
4079          Src.getValueType().getVectorElementType() == MVT::i1);
4080 
4081   MVT XLenVT = Subtarget.getXLenVT();
4082   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4083   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4084 
4085   if (VecVT.isScalableVector()) {
4086     // Be careful not to introduce illegal scalar types at this stage, and be
4087     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
4088     // illegal and must be expanded. Since we know that the constants are
4089     // sign-extended 32-bit values, we use SPLAT_VECTOR_I64 directly.
4090     bool IsRV32E64 =
4091         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
4092 
4093     if (!IsRV32E64) {
4094       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
4095       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
4096     } else {
4097       SplatZero = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatZero);
4098       SplatTrueVal =
4099           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VecVT, SplatTrueVal);
4100     }
4101 
4102     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4103   }
4104 
4105   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4106   MVT I1ContainerVT =
4107       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4108 
4109   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4110 
4111   SDValue Mask, VL;
4112   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4113 
4114   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero, VL);
4115   SplatTrueVal =
4116       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatTrueVal, VL);
4117   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4118                                SplatTrueVal, SplatZero, VL);
4119 
4120   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4121 }
4122 
4123 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4124     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4125   MVT ExtVT = Op.getSimpleValueType();
4126   // Only custom-lower extensions from fixed-length vector types.
4127   if (!ExtVT.isFixedLengthVector())
4128     return Op;
4129   MVT VT = Op.getOperand(0).getSimpleValueType();
4130   // Grab the canonical container type for the extended type. Infer the smaller
4131   // type from that to ensure the same number of vector elements, as we know
4132   // the LMUL will be sufficient to hold the smaller type.
4133   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4134   // Get the extended container type manually to ensure the same number of
4135   // vector elements between source and dest.
4136   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4137                                      ContainerExtVT.getVectorElementCount());
4138 
4139   SDValue Op1 =
4140       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4141 
4142   SDLoc DL(Op);
4143   SDValue Mask, VL;
4144   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4145 
4146   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4147 
4148   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4149 }
4150 
4151 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4152 // setcc operation:
4153 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4154 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
4155                                                   SelectionDAG &DAG) const {
4156   SDLoc DL(Op);
4157   EVT MaskVT = Op.getValueType();
4158   // Only expect to custom-lower truncations to mask types
4159   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4160          "Unexpected type for vector mask lowering");
4161   SDValue Src = Op.getOperand(0);
4162   MVT VecVT = Src.getSimpleValueType();
4163 
4164   // If this is a fixed vector, we need to convert it to a scalable vector.
4165   MVT ContainerVT = VecVT;
4166   if (VecVT.isFixedLengthVector()) {
4167     ContainerVT = getContainerForFixedLengthVector(VecVT);
4168     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4169   }
4170 
4171   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4172   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4173 
4174   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatOne);
4175   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, SplatZero);
4176 
4177   if (VecVT.isScalableVector()) {
4178     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
4179     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
4180   }
4181 
4182   SDValue Mask, VL;
4183   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4184 
4185   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4186   SDValue Trunc =
4187       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4188   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4189                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4190   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4191 }
4192 
4193 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4194 // first position of a vector, and that vector is slid up to the insert index.
4195 // By limiting the active vector length to index+1 and merging with the
4196 // original vector (with an undisturbed tail policy for elements >= VL), we
4197 // achieve the desired result of leaving all elements untouched except the one
4198 // at VL-1, which is replaced with the desired value.
4199 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4200                                                     SelectionDAG &DAG) const {
4201   SDLoc DL(Op);
4202   MVT VecVT = Op.getSimpleValueType();
4203   SDValue Vec = Op.getOperand(0);
4204   SDValue Val = Op.getOperand(1);
4205   SDValue Idx = Op.getOperand(2);
4206 
4207   if (VecVT.getVectorElementType() == MVT::i1) {
4208     // FIXME: For now we just promote to an i8 vector and insert into that,
4209     // but this is probably not optimal.
4210     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4211     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4212     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4213     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4214   }
4215 
4216   MVT ContainerVT = VecVT;
4217   // If the operand is a fixed-length vector, convert to a scalable one.
4218   if (VecVT.isFixedLengthVector()) {
4219     ContainerVT = getContainerForFixedLengthVector(VecVT);
4220     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4221   }
4222 
4223   MVT XLenVT = Subtarget.getXLenVT();
4224 
4225   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4226   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4227   // Even i64-element vectors on RV32 can be lowered without scalar
4228   // legalization if the most-significant 32 bits of the value are not affected
4229   // by the sign-extension of the lower 32 bits.
4230   // TODO: We could also catch sign extensions of a 32-bit value.
4231   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4232     const auto *CVal = cast<ConstantSDNode>(Val);
4233     if (isInt<32>(CVal->getSExtValue())) {
4234       IsLegalInsert = true;
4235       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4236     }
4237   }
4238 
4239   SDValue Mask, VL;
4240   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4241 
4242   SDValue ValInVec;
4243 
4244   if (IsLegalInsert) {
4245     unsigned Opc =
4246         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4247     if (isNullConstant(Idx)) {
4248       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4249       if (!VecVT.isFixedLengthVector())
4250         return Vec;
4251       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4252     }
4253     ValInVec =
4254         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4255   } else {
4256     // On RV32, i64-element vectors must be specially handled to place the
4257     // value at element 0, by using two vslide1up instructions in sequence on
4258     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4259     // this.
4260     SDValue One = DAG.getConstant(1, DL, XLenVT);
4261     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4262     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4263     MVT I32ContainerVT =
4264         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4265     SDValue I32Mask =
4266         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4267     // Limit the active VL to two.
4268     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4269     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4270     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4271     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, Zero,
4272                            InsertI64VL);
4273     // First slide in the hi value, then the lo in underneath it.
4274     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4275                            ValHi, I32Mask, InsertI64VL);
4276     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, ValInVec,
4277                            ValLo, I32Mask, InsertI64VL);
4278     // Bitcast back to the right container type.
4279     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4280   }
4281 
4282   // Now that the value is in a vector, slide it into position.
4283   SDValue InsertVL =
4284       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4285   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4286                                 ValInVec, Idx, Mask, InsertVL);
4287   if (!VecVT.isFixedLengthVector())
4288     return Slideup;
4289   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4290 }
4291 
4292 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4293 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4294 // types this is done using VMV_X_S to allow us to glean information about the
4295 // sign bits of the result.
4296 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4297                                                      SelectionDAG &DAG) const {
4298   SDLoc DL(Op);
4299   SDValue Idx = Op.getOperand(1);
4300   SDValue Vec = Op.getOperand(0);
4301   EVT EltVT = Op.getValueType();
4302   MVT VecVT = Vec.getSimpleValueType();
4303   MVT XLenVT = Subtarget.getXLenVT();
4304 
4305   if (VecVT.getVectorElementType() == MVT::i1) {
4306     if (VecVT.isFixedLengthVector()) {
4307       unsigned NumElts = VecVT.getVectorNumElements();
4308       if (NumElts >= 8) {
4309         MVT WideEltVT;
4310         unsigned WidenVecLen;
4311         SDValue ExtractElementIdx;
4312         SDValue ExtractBitIdx;
4313         unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors();
4314         MVT LargestEltVT = MVT::getIntegerVT(
4315             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4316         if (NumElts <= LargestEltVT.getSizeInBits()) {
4317           assert(isPowerOf2_32(NumElts) &&
4318                  "the number of elements should be power of 2");
4319           WideEltVT = MVT::getIntegerVT(NumElts);
4320           WidenVecLen = 1;
4321           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4322           ExtractBitIdx = Idx;
4323         } else {
4324           WideEltVT = LargestEltVT;
4325           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4326           // extract element index = index / element width
4327           ExtractElementIdx = DAG.getNode(
4328               ISD::SRL, DL, XLenVT, Idx,
4329               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4330           // mask bit index = index % element width
4331           ExtractBitIdx = DAG.getNode(
4332               ISD::AND, DL, XLenVT, Idx,
4333               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4334         }
4335         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4336         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4337         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4338                                          Vec, ExtractElementIdx);
4339         // Extract the bit from GPR.
4340         SDValue ShiftRight =
4341             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4342         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4343                            DAG.getConstant(1, DL, XLenVT));
4344       }
4345     }
4346     // Otherwise, promote to an i8 vector and extract from that.
4347     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4348     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4349     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4350   }
4351 
4352   // If this is a fixed vector, we need to convert it to a scalable vector.
4353   MVT ContainerVT = VecVT;
4354   if (VecVT.isFixedLengthVector()) {
4355     ContainerVT = getContainerForFixedLengthVector(VecVT);
4356     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4357   }
4358 
4359   // If the index is 0, the vector is already in the right position.
4360   if (!isNullConstant(Idx)) {
4361     // Use a VL of 1 to avoid processing more elements than we need.
4362     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4363     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4364     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4365     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4366                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4367   }
4368 
4369   if (!EltVT.isInteger()) {
4370     // Floating-point extracts are handled in TableGen.
4371     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4372                        DAG.getConstant(0, DL, XLenVT));
4373   }
4374 
4375   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4376   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4377 }
4378 
4379 // Some RVV intrinsics may claim that they want an integer operand to be
4380 // promoted or expanded.
4381 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
4382                                           const RISCVSubtarget &Subtarget) {
4383   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4384           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4385          "Unexpected opcode");
4386 
4387   if (!Subtarget.hasVInstructions())
4388     return SDValue();
4389 
4390   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4391   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4392   SDLoc DL(Op);
4393 
4394   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4395       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4396   if (!II || !II->hasSplatOperand())
4397     return SDValue();
4398 
4399   unsigned SplatOp = II->SplatOperand + 1 + HasChain;
4400   assert(SplatOp < Op.getNumOperands());
4401 
4402   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4403   SDValue &ScalarOp = Operands[SplatOp];
4404   MVT OpVT = ScalarOp.getSimpleValueType();
4405   MVT XLenVT = Subtarget.getXLenVT();
4406 
4407   // If this isn't a scalar, or its type is XLenVT we're done.
4408   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4409     return SDValue();
4410 
4411   // Simplest case is that the operand needs to be promoted to XLenVT.
4412   if (OpVT.bitsLT(XLenVT)) {
4413     // If the operand is a constant, sign extend to increase our chances
4414     // of being able to use a .vi instruction. ANY_EXTEND would become a
4415     // a zero extend and the simm5 check in isel would fail.
4416     // FIXME: Should we ignore the upper bits in isel instead?
4417     unsigned ExtOpc =
4418         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4419     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4420     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4421   }
4422 
4423   // Use the previous operand to get the vXi64 VT. The result might be a mask
4424   // VT for compares. Using the previous operand assumes that the previous
4425   // operand will never have a smaller element size than a scalar operand and
4426   // that a widening operation never uses SEW=64.
4427   // NOTE: If this fails the below assert, we can probably just find the
4428   // element count from any operand or result and use it to construct the VT.
4429   assert(II->SplatOperand > 0 && "Unexpected splat operand!");
4430   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4431 
4432   // The more complex case is when the scalar is larger than XLenVT.
4433   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4434          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4435 
4436   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4437   // on the instruction to sign-extend since SEW>XLEN.
4438   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4439     if (isInt<32>(CVal->getSExtValue())) {
4440       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4441       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4442     }
4443   }
4444 
4445   // We need to convert the scalar to a splat vector.
4446   // FIXME: Can we implicitly truncate the scalar if it is known to
4447   // be sign extended?
4448   SDValue VL = getVLOperand(Op);
4449   assert(VL.getValueType() == XLenVT);
4450   ScalarOp = splatSplitI64WithVL(DL, VT, ScalarOp, VL, DAG);
4451   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4452 }
4453 
4454 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4455                                                      SelectionDAG &DAG) const {
4456   unsigned IntNo = Op.getConstantOperandVal(0);
4457   SDLoc DL(Op);
4458   MVT XLenVT = Subtarget.getXLenVT();
4459 
4460   switch (IntNo) {
4461   default:
4462     break; // Don't custom lower most intrinsics.
4463   case Intrinsic::thread_pointer: {
4464     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4465     return DAG.getRegister(RISCV::X4, PtrVT);
4466   }
4467   case Intrinsic::riscv_orc_b:
4468   case Intrinsic::riscv_brev8: {
4469     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4470     unsigned Opc =
4471         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4472     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4473                        DAG.getConstant(7, DL, XLenVT));
4474   }
4475   case Intrinsic::riscv_grev:
4476   case Intrinsic::riscv_gorc: {
4477     unsigned Opc =
4478         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4479     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4480   }
4481   case Intrinsic::riscv_zip:
4482   case Intrinsic::riscv_unzip: {
4483     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4484     // For i32 the immdiate is 15. For i64 the immediate is 31.
4485     unsigned Opc =
4486         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4487     unsigned BitWidth = Op.getValueSizeInBits();
4488     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4489     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4490                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4491   }
4492   case Intrinsic::riscv_shfl:
4493   case Intrinsic::riscv_unshfl: {
4494     unsigned Opc =
4495         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4496     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4497   }
4498   case Intrinsic::riscv_bcompress:
4499   case Intrinsic::riscv_bdecompress: {
4500     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4501                                                        : RISCVISD::BDECOMPRESS;
4502     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4503   }
4504   case Intrinsic::riscv_bfp:
4505     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4506                        Op.getOperand(2));
4507   case Intrinsic::riscv_fsl:
4508     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4509                        Op.getOperand(2), Op.getOperand(3));
4510   case Intrinsic::riscv_fsr:
4511     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4512                        Op.getOperand(2), Op.getOperand(3));
4513   case Intrinsic::riscv_vmv_x_s:
4514     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4515     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4516                        Op.getOperand(1));
4517   case Intrinsic::riscv_vmv_v_x:
4518     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4519                             Op.getSimpleValueType(), DL, DAG, Subtarget);
4520   case Intrinsic::riscv_vfmv_v_f:
4521     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4522                        Op.getOperand(1), Op.getOperand(2));
4523   case Intrinsic::riscv_vmv_s_x: {
4524     SDValue Scalar = Op.getOperand(2);
4525 
4526     if (Scalar.getValueType().bitsLE(XLenVT)) {
4527       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4528       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4529                          Op.getOperand(1), Scalar, Op.getOperand(3));
4530     }
4531 
4532     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4533 
4534     // This is an i64 value that lives in two scalar registers. We have to
4535     // insert this in a convoluted way. First we build vXi64 splat containing
4536     // the/ two values that we assemble using some bit math. Next we'll use
4537     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4538     // to merge element 0 from our splat into the source vector.
4539     // FIXME: This is probably not the best way to do this, but it is
4540     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4541     // point.
4542     //   sw lo, (a0)
4543     //   sw hi, 4(a0)
4544     //   vlse vX, (a0)
4545     //
4546     //   vid.v      vVid
4547     //   vmseq.vx   mMask, vVid, 0
4548     //   vmerge.vvm vDest, vSrc, vVal, mMask
4549     MVT VT = Op.getSimpleValueType();
4550     SDValue Vec = Op.getOperand(1);
4551     SDValue VL = getVLOperand(Op);
4552 
4553     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, Scalar, VL, DAG);
4554     SDValue SplattedIdx = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
4555                                       DAG.getConstant(0, DL, MVT::i32), VL);
4556 
4557     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4558     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4559     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4560     SDValue SelectCond =
4561         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4562                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4563     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4564                        Vec, VL);
4565   }
4566   case Intrinsic::riscv_vslide1up:
4567   case Intrinsic::riscv_vslide1down:
4568   case Intrinsic::riscv_vslide1up_mask:
4569   case Intrinsic::riscv_vslide1down_mask: {
4570     // We need to special case these when the scalar is larger than XLen.
4571     unsigned NumOps = Op.getNumOperands();
4572     bool IsMasked = NumOps == 7;
4573     unsigned OpOffset = IsMasked ? 1 : 0;
4574     SDValue Scalar = Op.getOperand(2 + OpOffset);
4575     if (Scalar.getValueType().bitsLE(XLenVT))
4576       break;
4577 
4578     // Splatting a sign extended constant is fine.
4579     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
4580       if (isInt<32>(CVal->getSExtValue()))
4581         break;
4582 
4583     MVT VT = Op.getSimpleValueType();
4584     assert(VT.getVectorElementType() == MVT::i64 &&
4585            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
4586 
4587     // Convert the vector source to the equivalent nxvXi32 vector.
4588     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4589     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(1 + OpOffset));
4590 
4591     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4592                                    DAG.getConstant(0, DL, XLenVT));
4593     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4594                                    DAG.getConstant(1, DL, XLenVT));
4595 
4596     // Double the VL since we halved SEW.
4597     SDValue VL = getVLOperand(Op);
4598     SDValue I32VL =
4599         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4600 
4601     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4602     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4603 
4604     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4605     // instructions.
4606     if (IntNo == Intrinsic::riscv_vslide1up ||
4607         IntNo == Intrinsic::riscv_vslide1up_mask) {
4608       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarHi,
4609                         I32Mask, I32VL);
4610       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Vec, ScalarLo,
4611                         I32Mask, I32VL);
4612     } else {
4613       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarLo,
4614                         I32Mask, I32VL);
4615       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Vec, ScalarHi,
4616                         I32Mask, I32VL);
4617     }
4618 
4619     // Convert back to nxvXi64.
4620     Vec = DAG.getBitcast(VT, Vec);
4621 
4622     if (!IsMasked)
4623       return Vec;
4624 
4625     // Apply mask after the operation.
4626     SDValue Mask = Op.getOperand(NumOps - 3);
4627     SDValue MaskedOff = Op.getOperand(1);
4628     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4629   }
4630   }
4631 
4632   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4633 }
4634 
4635 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4636                                                     SelectionDAG &DAG) const {
4637   unsigned IntNo = Op.getConstantOperandVal(1);
4638   switch (IntNo) {
4639   default:
4640     break;
4641   case Intrinsic::riscv_masked_strided_load: {
4642     SDLoc DL(Op);
4643     MVT XLenVT = Subtarget.getXLenVT();
4644 
4645     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4646     // the selection of the masked intrinsics doesn't do this for us.
4647     SDValue Mask = Op.getOperand(5);
4648     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4649 
4650     MVT VT = Op->getSimpleValueType(0);
4651     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4652 
4653     SDValue PassThru = Op.getOperand(2);
4654     if (!IsUnmasked) {
4655       MVT MaskVT =
4656           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4657       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4658       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4659     }
4660 
4661     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4662 
4663     SDValue IntID = DAG.getTargetConstant(
4664         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4665         XLenVT);
4666 
4667     auto *Load = cast<MemIntrinsicSDNode>(Op);
4668     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4669     if (IsUnmasked)
4670       Ops.push_back(DAG.getUNDEF(ContainerVT));
4671     else
4672       Ops.push_back(PassThru);
4673     Ops.push_back(Op.getOperand(3)); // Ptr
4674     Ops.push_back(Op.getOperand(4)); // Stride
4675     if (!IsUnmasked)
4676       Ops.push_back(Mask);
4677     Ops.push_back(VL);
4678     if (!IsUnmasked) {
4679       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4680       Ops.push_back(Policy);
4681     }
4682 
4683     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4684     SDValue Result =
4685         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4686                                 Load->getMemoryVT(), Load->getMemOperand());
4687     SDValue Chain = Result.getValue(1);
4688     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4689     return DAG.getMergeValues({Result, Chain}, DL);
4690   }
4691   }
4692 
4693   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4694 }
4695 
4696 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4697                                                  SelectionDAG &DAG) const {
4698   unsigned IntNo = Op.getConstantOperandVal(1);
4699   switch (IntNo) {
4700   default:
4701     break;
4702   case Intrinsic::riscv_masked_strided_store: {
4703     SDLoc DL(Op);
4704     MVT XLenVT = Subtarget.getXLenVT();
4705 
4706     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4707     // the selection of the masked intrinsics doesn't do this for us.
4708     SDValue Mask = Op.getOperand(5);
4709     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4710 
4711     SDValue Val = Op.getOperand(2);
4712     MVT VT = Val.getSimpleValueType();
4713     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4714 
4715     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4716     if (!IsUnmasked) {
4717       MVT MaskVT =
4718           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4719       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4720     }
4721 
4722     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4723 
4724     SDValue IntID = DAG.getTargetConstant(
4725         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4726         XLenVT);
4727 
4728     auto *Store = cast<MemIntrinsicSDNode>(Op);
4729     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4730     Ops.push_back(Val);
4731     Ops.push_back(Op.getOperand(3)); // Ptr
4732     Ops.push_back(Op.getOperand(4)); // Stride
4733     if (!IsUnmasked)
4734       Ops.push_back(Mask);
4735     Ops.push_back(VL);
4736 
4737     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4738                                    Ops, Store->getMemoryVT(),
4739                                    Store->getMemOperand());
4740   }
4741   }
4742 
4743   return SDValue();
4744 }
4745 
4746 static MVT getLMUL1VT(MVT VT) {
4747   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4748          "Unexpected vector MVT");
4749   return MVT::getScalableVectorVT(
4750       VT.getVectorElementType(),
4751       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4752 }
4753 
4754 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4755   switch (ISDOpcode) {
4756   default:
4757     llvm_unreachable("Unhandled reduction");
4758   case ISD::VECREDUCE_ADD:
4759     return RISCVISD::VECREDUCE_ADD_VL;
4760   case ISD::VECREDUCE_UMAX:
4761     return RISCVISD::VECREDUCE_UMAX_VL;
4762   case ISD::VECREDUCE_SMAX:
4763     return RISCVISD::VECREDUCE_SMAX_VL;
4764   case ISD::VECREDUCE_UMIN:
4765     return RISCVISD::VECREDUCE_UMIN_VL;
4766   case ISD::VECREDUCE_SMIN:
4767     return RISCVISD::VECREDUCE_SMIN_VL;
4768   case ISD::VECREDUCE_AND:
4769     return RISCVISD::VECREDUCE_AND_VL;
4770   case ISD::VECREDUCE_OR:
4771     return RISCVISD::VECREDUCE_OR_VL;
4772   case ISD::VECREDUCE_XOR:
4773     return RISCVISD::VECREDUCE_XOR_VL;
4774   }
4775 }
4776 
4777 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4778                                                          SelectionDAG &DAG,
4779                                                          bool IsVP) const {
4780   SDLoc DL(Op);
4781   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4782   MVT VecVT = Vec.getSimpleValueType();
4783   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4784           Op.getOpcode() == ISD::VECREDUCE_OR ||
4785           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4786           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4787           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4788           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4789          "Unexpected reduction lowering");
4790 
4791   MVT XLenVT = Subtarget.getXLenVT();
4792   assert(Op.getValueType() == XLenVT &&
4793          "Expected reduction output to be legalized to XLenVT");
4794 
4795   MVT ContainerVT = VecVT;
4796   if (VecVT.isFixedLengthVector()) {
4797     ContainerVT = getContainerForFixedLengthVector(VecVT);
4798     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4799   }
4800 
4801   SDValue Mask, VL;
4802   if (IsVP) {
4803     Mask = Op.getOperand(2);
4804     VL = Op.getOperand(3);
4805   } else {
4806     std::tie(Mask, VL) =
4807         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4808   }
4809 
4810   unsigned BaseOpc;
4811   ISD::CondCode CC;
4812   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4813 
4814   switch (Op.getOpcode()) {
4815   default:
4816     llvm_unreachable("Unhandled reduction");
4817   case ISD::VECREDUCE_AND:
4818   case ISD::VP_REDUCE_AND: {
4819     // vcpop ~x == 0
4820     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
4821     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
4822     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4823     CC = ISD::SETEQ;
4824     BaseOpc = ISD::AND;
4825     break;
4826   }
4827   case ISD::VECREDUCE_OR:
4828   case ISD::VP_REDUCE_OR:
4829     // vcpop x != 0
4830     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4831     CC = ISD::SETNE;
4832     BaseOpc = ISD::OR;
4833     break;
4834   case ISD::VECREDUCE_XOR:
4835   case ISD::VP_REDUCE_XOR: {
4836     // ((vcpop x) & 1) != 0
4837     SDValue One = DAG.getConstant(1, DL, XLenVT);
4838     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
4839     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
4840     CC = ISD::SETNE;
4841     BaseOpc = ISD::XOR;
4842     break;
4843   }
4844   }
4845 
4846   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
4847 
4848   if (!IsVP)
4849     return SetCC;
4850 
4851   // Now include the start value in the operation.
4852   // Note that we must return the start value when no elements are operated
4853   // upon. The vcpop instructions we've emitted in each case above will return
4854   // 0 for an inactive vector, and so we've already received the neutral value:
4855   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
4856   // can simply include the start value.
4857   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
4858 }
4859 
4860 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
4861                                             SelectionDAG &DAG) const {
4862   SDLoc DL(Op);
4863   SDValue Vec = Op.getOperand(0);
4864   EVT VecEVT = Vec.getValueType();
4865 
4866   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
4867 
4868   // Due to ordering in legalize types we may have a vector type that needs to
4869   // be split. Do that manually so we can get down to a legal type.
4870   while (getTypeAction(*DAG.getContext(), VecEVT) ==
4871          TargetLowering::TypeSplitVector) {
4872     SDValue Lo, Hi;
4873     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
4874     VecEVT = Lo.getValueType();
4875     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
4876   }
4877 
4878   // TODO: The type may need to be widened rather than split. Or widened before
4879   // it can be split.
4880   if (!isTypeLegal(VecEVT))
4881     return SDValue();
4882 
4883   MVT VecVT = VecEVT.getSimpleVT();
4884   MVT VecEltVT = VecVT.getVectorElementType();
4885   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
4886 
4887   MVT ContainerVT = VecVT;
4888   if (VecVT.isFixedLengthVector()) {
4889     ContainerVT = getContainerForFixedLengthVector(VecVT);
4890     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4891   }
4892 
4893   MVT M1VT = getLMUL1VT(ContainerVT);
4894   MVT XLenVT = Subtarget.getXLenVT();
4895 
4896   SDValue Mask, VL;
4897   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4898 
4899   SDValue NeutralElem =
4900       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
4901   SDValue IdentitySplat = lowerScalarSplat(
4902       NeutralElem, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4903   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
4904                                   IdentitySplat, Mask, VL);
4905   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4906                              DAG.getConstant(0, DL, XLenVT));
4907   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
4908 }
4909 
4910 // Given a reduction op, this function returns the matching reduction opcode,
4911 // the vector SDValue and the scalar SDValue required to lower this to a
4912 // RISCVISD node.
4913 static std::tuple<unsigned, SDValue, SDValue>
4914 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
4915   SDLoc DL(Op);
4916   auto Flags = Op->getFlags();
4917   unsigned Opcode = Op.getOpcode();
4918   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
4919   switch (Opcode) {
4920   default:
4921     llvm_unreachable("Unhandled reduction");
4922   case ISD::VECREDUCE_FADD: {
4923     // Use positive zero if we can. It is cheaper to materialize.
4924     SDValue Zero =
4925         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
4926     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
4927   }
4928   case ISD::VECREDUCE_SEQ_FADD:
4929     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
4930                            Op.getOperand(0));
4931   case ISD::VECREDUCE_FMIN:
4932     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
4933                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4934   case ISD::VECREDUCE_FMAX:
4935     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
4936                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
4937   }
4938 }
4939 
4940 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
4941                                               SelectionDAG &DAG) const {
4942   SDLoc DL(Op);
4943   MVT VecEltVT = Op.getSimpleValueType();
4944 
4945   unsigned RVVOpcode;
4946   SDValue VectorVal, ScalarVal;
4947   std::tie(RVVOpcode, VectorVal, ScalarVal) =
4948       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
4949   MVT VecVT = VectorVal.getSimpleValueType();
4950 
4951   MVT ContainerVT = VecVT;
4952   if (VecVT.isFixedLengthVector()) {
4953     ContainerVT = getContainerForFixedLengthVector(VecVT);
4954     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
4955   }
4956 
4957   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
4958   MVT XLenVT = Subtarget.getXLenVT();
4959 
4960   SDValue Mask, VL;
4961   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4962 
4963   SDValue ScalarSplat = lowerScalarSplat(
4964       ScalarVal, DAG.getConstant(1, DL, XLenVT), M1VT, DL, DAG, Subtarget);
4965   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
4966                                   VectorVal, ScalarSplat, Mask, VL);
4967   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
4968                      DAG.getConstant(0, DL, XLenVT));
4969 }
4970 
4971 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
4972   switch (ISDOpcode) {
4973   default:
4974     llvm_unreachable("Unhandled reduction");
4975   case ISD::VP_REDUCE_ADD:
4976     return RISCVISD::VECREDUCE_ADD_VL;
4977   case ISD::VP_REDUCE_UMAX:
4978     return RISCVISD::VECREDUCE_UMAX_VL;
4979   case ISD::VP_REDUCE_SMAX:
4980     return RISCVISD::VECREDUCE_SMAX_VL;
4981   case ISD::VP_REDUCE_UMIN:
4982     return RISCVISD::VECREDUCE_UMIN_VL;
4983   case ISD::VP_REDUCE_SMIN:
4984     return RISCVISD::VECREDUCE_SMIN_VL;
4985   case ISD::VP_REDUCE_AND:
4986     return RISCVISD::VECREDUCE_AND_VL;
4987   case ISD::VP_REDUCE_OR:
4988     return RISCVISD::VECREDUCE_OR_VL;
4989   case ISD::VP_REDUCE_XOR:
4990     return RISCVISD::VECREDUCE_XOR_VL;
4991   case ISD::VP_REDUCE_FADD:
4992     return RISCVISD::VECREDUCE_FADD_VL;
4993   case ISD::VP_REDUCE_SEQ_FADD:
4994     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
4995   case ISD::VP_REDUCE_FMAX:
4996     return RISCVISD::VECREDUCE_FMAX_VL;
4997   case ISD::VP_REDUCE_FMIN:
4998     return RISCVISD::VECREDUCE_FMIN_VL;
4999   }
5000 }
5001 
5002 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5003                                            SelectionDAG &DAG) const {
5004   SDLoc DL(Op);
5005   SDValue Vec = Op.getOperand(1);
5006   EVT VecEVT = Vec.getValueType();
5007 
5008   // TODO: The type may need to be widened rather than split. Or widened before
5009   // it can be split.
5010   if (!isTypeLegal(VecEVT))
5011     return SDValue();
5012 
5013   MVT VecVT = VecEVT.getSimpleVT();
5014   MVT VecEltVT = VecVT.getVectorElementType();
5015   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5016 
5017   MVT ContainerVT = VecVT;
5018   if (VecVT.isFixedLengthVector()) {
5019     ContainerVT = getContainerForFixedLengthVector(VecVT);
5020     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5021   }
5022 
5023   SDValue VL = Op.getOperand(3);
5024   SDValue Mask = Op.getOperand(2);
5025 
5026   MVT M1VT = getLMUL1VT(ContainerVT);
5027   MVT XLenVT = Subtarget.getXLenVT();
5028   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5029 
5030   SDValue StartSplat =
5031       lowerScalarSplat(Op.getOperand(0), DAG.getConstant(1, DL, XLenVT), M1VT,
5032                        DL, DAG, Subtarget);
5033   SDValue Reduction =
5034       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5035   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5036                              DAG.getConstant(0, DL, XLenVT));
5037   if (!VecVT.isInteger())
5038     return Elt0;
5039   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5040 }
5041 
5042 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5043                                                    SelectionDAG &DAG) const {
5044   SDValue Vec = Op.getOperand(0);
5045   SDValue SubVec = Op.getOperand(1);
5046   MVT VecVT = Vec.getSimpleValueType();
5047   MVT SubVecVT = SubVec.getSimpleValueType();
5048 
5049   SDLoc DL(Op);
5050   MVT XLenVT = Subtarget.getXLenVT();
5051   unsigned OrigIdx = Op.getConstantOperandVal(2);
5052   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5053 
5054   // We don't have the ability to slide mask vectors up indexed by their i1
5055   // elements; the smallest we can do is i8. Often we are able to bitcast to
5056   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5057   // into a scalable one, we might not necessarily have enough scalable
5058   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5059   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5060       (OrigIdx != 0 || !Vec.isUndef())) {
5061     if (VecVT.getVectorMinNumElements() >= 8 &&
5062         SubVecVT.getVectorMinNumElements() >= 8) {
5063       assert(OrigIdx % 8 == 0 && "Invalid index");
5064       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5065              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5066              "Unexpected mask vector lowering");
5067       OrigIdx /= 8;
5068       SubVecVT =
5069           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5070                            SubVecVT.isScalableVector());
5071       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5072                                VecVT.isScalableVector());
5073       Vec = DAG.getBitcast(VecVT, Vec);
5074       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5075     } else {
5076       // We can't slide this mask vector up indexed by its i1 elements.
5077       // This poses a problem when we wish to insert a scalable vector which
5078       // can't be re-expressed as a larger type. Just choose the slow path and
5079       // extend to a larger type, then truncate back down.
5080       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5081       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5082       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5083       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5084       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5085                         Op.getOperand(2));
5086       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5087       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5088     }
5089   }
5090 
5091   // If the subvector vector is a fixed-length type, we cannot use subregister
5092   // manipulation to simplify the codegen; we don't know which register of a
5093   // LMUL group contains the specific subvector as we only know the minimum
5094   // register size. Therefore we must slide the vector group up the full
5095   // amount.
5096   if (SubVecVT.isFixedLengthVector()) {
5097     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5098       return Op;
5099     MVT ContainerVT = VecVT;
5100     if (VecVT.isFixedLengthVector()) {
5101       ContainerVT = getContainerForFixedLengthVector(VecVT);
5102       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5103     }
5104     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5105                          DAG.getUNDEF(ContainerVT), SubVec,
5106                          DAG.getConstant(0, DL, XLenVT));
5107     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5108       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5109       return DAG.getBitcast(Op.getValueType(), SubVec);
5110     }
5111     SDValue Mask =
5112         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5113     // Set the vector length to only the number of elements we care about. Note
5114     // that for slideup this includes the offset.
5115     SDValue VL =
5116         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5117     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5118     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5119                                   SubVec, SlideupAmt, Mask, VL);
5120     if (VecVT.isFixedLengthVector())
5121       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5122     return DAG.getBitcast(Op.getValueType(), Slideup);
5123   }
5124 
5125   unsigned SubRegIdx, RemIdx;
5126   std::tie(SubRegIdx, RemIdx) =
5127       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5128           VecVT, SubVecVT, OrigIdx, TRI);
5129 
5130   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5131   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5132                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5133                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5134 
5135   // 1. If the Idx has been completely eliminated and this subvector's size is
5136   // a vector register or a multiple thereof, or the surrounding elements are
5137   // undef, then this is a subvector insert which naturally aligns to a vector
5138   // register. These can easily be handled using subregister manipulation.
5139   // 2. If the subvector is smaller than a vector register, then the insertion
5140   // must preserve the undisturbed elements of the register. We do this by
5141   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5142   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5143   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5144   // LMUL=1 type back into the larger vector (resolving to another subregister
5145   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5146   // to avoid allocating a large register group to hold our subvector.
5147   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5148     return Op;
5149 
5150   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5151   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5152   // (in our case undisturbed). This means we can set up a subvector insertion
5153   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5154   // size of the subvector.
5155   MVT InterSubVT = VecVT;
5156   SDValue AlignedExtract = Vec;
5157   unsigned AlignedIdx = OrigIdx - RemIdx;
5158   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5159     InterSubVT = getLMUL1VT(VecVT);
5160     // Extract a subvector equal to the nearest full vector register type. This
5161     // should resolve to a EXTRACT_SUBREG instruction.
5162     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5163                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5164   }
5165 
5166   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5167   // For scalable vectors this must be further multiplied by vscale.
5168   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5169 
5170   SDValue Mask, VL;
5171   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5172 
5173   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5174   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5175   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5176   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5177 
5178   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5179                        DAG.getUNDEF(InterSubVT), SubVec,
5180                        DAG.getConstant(0, DL, XLenVT));
5181 
5182   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5183                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5184 
5185   // If required, insert this subvector back into the correct vector register.
5186   // This should resolve to an INSERT_SUBREG instruction.
5187   if (VecVT.bitsGT(InterSubVT))
5188     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5189                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5190 
5191   // We might have bitcast from a mask type: cast back to the original type if
5192   // required.
5193   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5194 }
5195 
5196 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5197                                                     SelectionDAG &DAG) const {
5198   SDValue Vec = Op.getOperand(0);
5199   MVT SubVecVT = Op.getSimpleValueType();
5200   MVT VecVT = Vec.getSimpleValueType();
5201 
5202   SDLoc DL(Op);
5203   MVT XLenVT = Subtarget.getXLenVT();
5204   unsigned OrigIdx = Op.getConstantOperandVal(1);
5205   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5206 
5207   // We don't have the ability to slide mask vectors down indexed by their i1
5208   // elements; the smallest we can do is i8. Often we are able to bitcast to
5209   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5210   // from a scalable one, we might not necessarily have enough scalable
5211   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5212   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5213     if (VecVT.getVectorMinNumElements() >= 8 &&
5214         SubVecVT.getVectorMinNumElements() >= 8) {
5215       assert(OrigIdx % 8 == 0 && "Invalid index");
5216       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5217              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5218              "Unexpected mask vector lowering");
5219       OrigIdx /= 8;
5220       SubVecVT =
5221           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5222                            SubVecVT.isScalableVector());
5223       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5224                                VecVT.isScalableVector());
5225       Vec = DAG.getBitcast(VecVT, Vec);
5226     } else {
5227       // We can't slide this mask vector down, indexed by its i1 elements.
5228       // This poses a problem when we wish to extract a scalable vector which
5229       // can't be re-expressed as a larger type. Just choose the slow path and
5230       // extend to a larger type, then truncate back down.
5231       // TODO: We could probably improve this when extracting certain fixed
5232       // from fixed, where we can extract as i8 and shift the correct element
5233       // right to reach the desired subvector?
5234       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5235       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5236       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5237       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5238                         Op.getOperand(1));
5239       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5240       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5241     }
5242   }
5243 
5244   // If the subvector vector is a fixed-length type, we cannot use subregister
5245   // manipulation to simplify the codegen; we don't know which register of a
5246   // LMUL group contains the specific subvector as we only know the minimum
5247   // register size. Therefore we must slide the vector group down the full
5248   // amount.
5249   if (SubVecVT.isFixedLengthVector()) {
5250     // With an index of 0 this is a cast-like subvector, which can be performed
5251     // with subregister operations.
5252     if (OrigIdx == 0)
5253       return Op;
5254     MVT ContainerVT = VecVT;
5255     if (VecVT.isFixedLengthVector()) {
5256       ContainerVT = getContainerForFixedLengthVector(VecVT);
5257       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5258     }
5259     SDValue Mask =
5260         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5261     // Set the vector length to only the number of elements we care about. This
5262     // avoids sliding down elements we're going to discard straight away.
5263     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5264     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5265     SDValue Slidedown =
5266         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5267                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5268     // Now we can use a cast-like subvector extract to get the result.
5269     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5270                             DAG.getConstant(0, DL, XLenVT));
5271     return DAG.getBitcast(Op.getValueType(), Slidedown);
5272   }
5273 
5274   unsigned SubRegIdx, RemIdx;
5275   std::tie(SubRegIdx, RemIdx) =
5276       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5277           VecVT, SubVecVT, OrigIdx, TRI);
5278 
5279   // If the Idx has been completely eliminated then this is a subvector extract
5280   // which naturally aligns to a vector register. These can easily be handled
5281   // using subregister manipulation.
5282   if (RemIdx == 0)
5283     return Op;
5284 
5285   // Else we must shift our vector register directly to extract the subvector.
5286   // Do this using VSLIDEDOWN.
5287 
5288   // If the vector type is an LMUL-group type, extract a subvector equal to the
5289   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5290   // instruction.
5291   MVT InterSubVT = VecVT;
5292   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5293     InterSubVT = getLMUL1VT(VecVT);
5294     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5295                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5296   }
5297 
5298   // Slide this vector register down by the desired number of elements in order
5299   // to place the desired subvector starting at element 0.
5300   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5301   // For scalable vectors this must be further multiplied by vscale.
5302   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5303 
5304   SDValue Mask, VL;
5305   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5306   SDValue Slidedown =
5307       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5308                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5309 
5310   // Now the vector is in the right position, extract our final subvector. This
5311   // should resolve to a COPY.
5312   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5313                           DAG.getConstant(0, DL, XLenVT));
5314 
5315   // We might have bitcast from a mask type: cast back to the original type if
5316   // required.
5317   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5318 }
5319 
5320 // Lower step_vector to the vid instruction. Any non-identity step value must
5321 // be accounted for my manual expansion.
5322 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5323                                               SelectionDAG &DAG) const {
5324   SDLoc DL(Op);
5325   MVT VT = Op.getSimpleValueType();
5326   MVT XLenVT = Subtarget.getXLenVT();
5327   SDValue Mask, VL;
5328   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5329   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5330   uint64_t StepValImm = Op.getConstantOperandVal(0);
5331   if (StepValImm != 1) {
5332     if (isPowerOf2_64(StepValImm)) {
5333       SDValue StepVal =
5334           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT,
5335                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5336       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5337     } else {
5338       SDValue StepVal = lowerScalarSplat(
5339           DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), VL, VT,
5340           DL, DAG, Subtarget);
5341       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5342     }
5343   }
5344   return StepVec;
5345 }
5346 
5347 // Implement vector_reverse using vrgather.vv with indices determined by
5348 // subtracting the id of each element from (VLMAX-1). This will convert
5349 // the indices like so:
5350 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5351 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5352 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5353                                                  SelectionDAG &DAG) const {
5354   SDLoc DL(Op);
5355   MVT VecVT = Op.getSimpleValueType();
5356   unsigned EltSize = VecVT.getScalarSizeInBits();
5357   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5358 
5359   unsigned MaxVLMAX = 0;
5360   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5361   if (VectorBitsMax != 0)
5362     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
5363 
5364   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5365   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5366 
5367   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5368   // to use vrgatherei16.vv.
5369   // TODO: It's also possible to use vrgatherei16.vv for other types to
5370   // decrease register width for the index calculation.
5371   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5372     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5373     // Reverse each half, then reassemble them in reverse order.
5374     // NOTE: It's also possible that after splitting that VLMAX no longer
5375     // requires vrgatherei16.vv.
5376     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5377       SDValue Lo, Hi;
5378       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5379       EVT LoVT, HiVT;
5380       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5381       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5382       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5383       // Reassemble the low and high pieces reversed.
5384       // FIXME: This is a CONCAT_VECTORS.
5385       SDValue Res =
5386           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5387                       DAG.getIntPtrConstant(0, DL));
5388       return DAG.getNode(
5389           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5390           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5391     }
5392 
5393     // Just promote the int type to i16 which will double the LMUL.
5394     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5395     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5396   }
5397 
5398   MVT XLenVT = Subtarget.getXLenVT();
5399   SDValue Mask, VL;
5400   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5401 
5402   // Calculate VLMAX-1 for the desired SEW.
5403   unsigned MinElts = VecVT.getVectorMinNumElements();
5404   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5405                               DAG.getConstant(MinElts, DL, XLenVT));
5406   SDValue VLMinus1 =
5407       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5408 
5409   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5410   bool IsRV32E64 =
5411       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5412   SDValue SplatVL;
5413   if (!IsRV32E64)
5414     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5415   else
5416     SplatVL = DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, IntVT, VLMinus1);
5417 
5418   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5419   SDValue Indices =
5420       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5421 
5422   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5423 }
5424 
5425 SDValue
5426 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5427                                                      SelectionDAG &DAG) const {
5428   SDLoc DL(Op);
5429   auto *Load = cast<LoadSDNode>(Op);
5430 
5431   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5432                                         Load->getMemoryVT(),
5433                                         *Load->getMemOperand()) &&
5434          "Expecting a correctly-aligned load");
5435 
5436   MVT VT = Op.getSimpleValueType();
5437   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5438 
5439   SDValue VL =
5440       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5441 
5442   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5443   SDValue NewLoad = DAG.getMemIntrinsicNode(
5444       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
5445       Load->getMemoryVT(), Load->getMemOperand());
5446 
5447   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5448   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5449 }
5450 
5451 SDValue
5452 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5453                                                       SelectionDAG &DAG) const {
5454   SDLoc DL(Op);
5455   auto *Store = cast<StoreSDNode>(Op);
5456 
5457   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5458                                         Store->getMemoryVT(),
5459                                         *Store->getMemOperand()) &&
5460          "Expecting a correctly-aligned store");
5461 
5462   SDValue StoreVal = Store->getValue();
5463   MVT VT = StoreVal.getSimpleValueType();
5464 
5465   // If the size less than a byte, we need to pad with zeros to make a byte.
5466   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5467     VT = MVT::v8i1;
5468     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5469                            DAG.getConstant(0, DL, VT), StoreVal,
5470                            DAG.getIntPtrConstant(0, DL));
5471   }
5472 
5473   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5474 
5475   SDValue VL =
5476       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5477 
5478   SDValue NewValue =
5479       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5480   return DAG.getMemIntrinsicNode(
5481       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
5482       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
5483       Store->getMemoryVT(), Store->getMemOperand());
5484 }
5485 
5486 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5487                                              SelectionDAG &DAG) const {
5488   SDLoc DL(Op);
5489   MVT VT = Op.getSimpleValueType();
5490 
5491   const auto *MemSD = cast<MemSDNode>(Op);
5492   EVT MemVT = MemSD->getMemoryVT();
5493   MachineMemOperand *MMO = MemSD->getMemOperand();
5494   SDValue Chain = MemSD->getChain();
5495   SDValue BasePtr = MemSD->getBasePtr();
5496 
5497   SDValue Mask, PassThru, VL;
5498   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5499     Mask = VPLoad->getMask();
5500     PassThru = DAG.getUNDEF(VT);
5501     VL = VPLoad->getVectorLength();
5502   } else {
5503     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5504     Mask = MLoad->getMask();
5505     PassThru = MLoad->getPassThru();
5506   }
5507 
5508   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5509 
5510   MVT XLenVT = Subtarget.getXLenVT();
5511 
5512   MVT ContainerVT = VT;
5513   if (VT.isFixedLengthVector()) {
5514     ContainerVT = getContainerForFixedLengthVector(VT);
5515     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5516     if (!IsUnmasked) {
5517       MVT MaskVT =
5518           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5519       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5520     }
5521   }
5522 
5523   if (!VL)
5524     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5525 
5526   unsigned IntID =
5527       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5528   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5529   if (IsUnmasked)
5530     Ops.push_back(DAG.getUNDEF(ContainerVT));
5531   else
5532     Ops.push_back(PassThru);
5533   Ops.push_back(BasePtr);
5534   if (!IsUnmasked)
5535     Ops.push_back(Mask);
5536   Ops.push_back(VL);
5537   if (!IsUnmasked)
5538     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5539 
5540   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5541 
5542   SDValue Result =
5543       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5544   Chain = Result.getValue(1);
5545 
5546   if (VT.isFixedLengthVector())
5547     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5548 
5549   return DAG.getMergeValues({Result, Chain}, DL);
5550 }
5551 
5552 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5553                                               SelectionDAG &DAG) const {
5554   SDLoc DL(Op);
5555 
5556   const auto *MemSD = cast<MemSDNode>(Op);
5557   EVT MemVT = MemSD->getMemoryVT();
5558   MachineMemOperand *MMO = MemSD->getMemOperand();
5559   SDValue Chain = MemSD->getChain();
5560   SDValue BasePtr = MemSD->getBasePtr();
5561   SDValue Val, Mask, VL;
5562 
5563   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5564     Val = VPStore->getValue();
5565     Mask = VPStore->getMask();
5566     VL = VPStore->getVectorLength();
5567   } else {
5568     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5569     Val = MStore->getValue();
5570     Mask = MStore->getMask();
5571   }
5572 
5573   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5574 
5575   MVT VT = Val.getSimpleValueType();
5576   MVT XLenVT = Subtarget.getXLenVT();
5577 
5578   MVT ContainerVT = VT;
5579   if (VT.isFixedLengthVector()) {
5580     ContainerVT = getContainerForFixedLengthVector(VT);
5581 
5582     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5583     if (!IsUnmasked) {
5584       MVT MaskVT =
5585           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5586       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5587     }
5588   }
5589 
5590   if (!VL)
5591     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5592 
5593   unsigned IntID =
5594       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5595   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5596   Ops.push_back(Val);
5597   Ops.push_back(BasePtr);
5598   if (!IsUnmasked)
5599     Ops.push_back(Mask);
5600   Ops.push_back(VL);
5601 
5602   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5603                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5604 }
5605 
5606 SDValue
5607 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5608                                                       SelectionDAG &DAG) const {
5609   MVT InVT = Op.getOperand(0).getSimpleValueType();
5610   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5611 
5612   MVT VT = Op.getSimpleValueType();
5613 
5614   SDValue Op1 =
5615       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5616   SDValue Op2 =
5617       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5618 
5619   SDLoc DL(Op);
5620   SDValue VL =
5621       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5622 
5623   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5624   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5625 
5626   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5627                             Op.getOperand(2), Mask, VL);
5628 
5629   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5630 }
5631 
5632 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5633     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5634   MVT VT = Op.getSimpleValueType();
5635 
5636   if (VT.getVectorElementType() == MVT::i1)
5637     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5638 
5639   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5640 }
5641 
5642 SDValue
5643 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5644                                                       SelectionDAG &DAG) const {
5645   unsigned Opc;
5646   switch (Op.getOpcode()) {
5647   default: llvm_unreachable("Unexpected opcode!");
5648   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5649   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5650   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5651   }
5652 
5653   return lowerToScalableOp(Op, DAG, Opc);
5654 }
5655 
5656 // Lower vector ABS to smax(X, sub(0, X)).
5657 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5658   SDLoc DL(Op);
5659   MVT VT = Op.getSimpleValueType();
5660   SDValue X = Op.getOperand(0);
5661 
5662   assert(VT.isFixedLengthVector() && "Unexpected type");
5663 
5664   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5665   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5666 
5667   SDValue Mask, VL;
5668   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5669 
5670   SDValue SplatZero =
5671       DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
5672                   DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5673   SDValue NegX =
5674       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5675   SDValue Max =
5676       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5677 
5678   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5679 }
5680 
5681 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5682     SDValue Op, SelectionDAG &DAG) const {
5683   SDLoc DL(Op);
5684   MVT VT = Op.getSimpleValueType();
5685   SDValue Mag = Op.getOperand(0);
5686   SDValue Sign = Op.getOperand(1);
5687   assert(Mag.getValueType() == Sign.getValueType() &&
5688          "Can only handle COPYSIGN with matching types.");
5689 
5690   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5691   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5692   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5693 
5694   SDValue Mask, VL;
5695   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5696 
5697   SDValue CopySign =
5698       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5699 
5700   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5701 }
5702 
5703 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5704     SDValue Op, SelectionDAG &DAG) const {
5705   MVT VT = Op.getSimpleValueType();
5706   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5707 
5708   MVT I1ContainerVT =
5709       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5710 
5711   SDValue CC =
5712       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5713   SDValue Op1 =
5714       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5715   SDValue Op2 =
5716       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5717 
5718   SDLoc DL(Op);
5719   SDValue Mask, VL;
5720   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5721 
5722   SDValue Select =
5723       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5724 
5725   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5726 }
5727 
5728 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5729                                                unsigned NewOpc,
5730                                                bool HasMask) const {
5731   MVT VT = Op.getSimpleValueType();
5732   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5733 
5734   // Create list of operands by converting existing ones to scalable types.
5735   SmallVector<SDValue, 6> Ops;
5736   for (const SDValue &V : Op->op_values()) {
5737     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5738 
5739     // Pass through non-vector operands.
5740     if (!V.getValueType().isVector()) {
5741       Ops.push_back(V);
5742       continue;
5743     }
5744 
5745     // "cast" fixed length vector to a scalable vector.
5746     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5747            "Only fixed length vectors are supported!");
5748     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5749   }
5750 
5751   SDLoc DL(Op);
5752   SDValue Mask, VL;
5753   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5754   if (HasMask)
5755     Ops.push_back(Mask);
5756   Ops.push_back(VL);
5757 
5758   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
5759   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
5760 }
5761 
5762 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
5763 // * Operands of each node are assumed to be in the same order.
5764 // * The EVL operand is promoted from i32 to i64 on RV64.
5765 // * Fixed-length vectors are converted to their scalable-vector container
5766 //   types.
5767 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
5768                                        unsigned RISCVISDOpc) const {
5769   SDLoc DL(Op);
5770   MVT VT = Op.getSimpleValueType();
5771   SmallVector<SDValue, 4> Ops;
5772 
5773   for (const auto &OpIdx : enumerate(Op->ops())) {
5774     SDValue V = OpIdx.value();
5775     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5776     // Pass through operands which aren't fixed-length vectors.
5777     if (!V.getValueType().isFixedLengthVector()) {
5778       Ops.push_back(V);
5779       continue;
5780     }
5781     // "cast" fixed length vector to a scalable vector.
5782     MVT OpVT = V.getSimpleValueType();
5783     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
5784     assert(useRVVForFixedLengthVectorVT(OpVT) &&
5785            "Only fixed length vectors are supported!");
5786     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5787   }
5788 
5789   if (!VT.isFixedLengthVector())
5790     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
5791 
5792   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5793 
5794   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
5795 
5796   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
5797 }
5798 
5799 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
5800                                             unsigned MaskOpc,
5801                                             unsigned VecOpc) const {
5802   MVT VT = Op.getSimpleValueType();
5803   if (VT.getVectorElementType() != MVT::i1)
5804     return lowerVPOp(Op, DAG, VecOpc);
5805 
5806   // It is safe to drop mask parameter as masked-off elements are undef.
5807   SDValue Op1 = Op->getOperand(0);
5808   SDValue Op2 = Op->getOperand(1);
5809   SDValue VL = Op->getOperand(3);
5810 
5811   MVT ContainerVT = VT;
5812   const bool IsFixed = VT.isFixedLengthVector();
5813   if (IsFixed) {
5814     ContainerVT = getContainerForFixedLengthVector(VT);
5815     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
5816     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
5817   }
5818 
5819   SDLoc DL(Op);
5820   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
5821   if (!IsFixed)
5822     return Val;
5823   return convertFromScalableVector(VT, Val, DAG, Subtarget);
5824 }
5825 
5826 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
5827 // matched to a RVV indexed load. The RVV indexed load instructions only
5828 // support the "unsigned unscaled" addressing mode; indices are implicitly
5829 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5830 // signed or scaled indexing is extended to the XLEN value type and scaled
5831 // accordingly.
5832 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
5833                                                SelectionDAG &DAG) const {
5834   SDLoc DL(Op);
5835   MVT VT = Op.getSimpleValueType();
5836 
5837   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5838   EVT MemVT = MemSD->getMemoryVT();
5839   MachineMemOperand *MMO = MemSD->getMemOperand();
5840   SDValue Chain = MemSD->getChain();
5841   SDValue BasePtr = MemSD->getBasePtr();
5842 
5843   ISD::LoadExtType LoadExtType;
5844   SDValue Index, Mask, PassThru, VL;
5845 
5846   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
5847     Index = VPGN->getIndex();
5848     Mask = VPGN->getMask();
5849     PassThru = DAG.getUNDEF(VT);
5850     VL = VPGN->getVectorLength();
5851     // VP doesn't support extending loads.
5852     LoadExtType = ISD::NON_EXTLOAD;
5853   } else {
5854     // Else it must be a MGATHER.
5855     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
5856     Index = MGN->getIndex();
5857     Mask = MGN->getMask();
5858     PassThru = MGN->getPassThru();
5859     LoadExtType = MGN->getExtensionType();
5860   }
5861 
5862   MVT IndexVT = Index.getSimpleValueType();
5863   MVT XLenVT = Subtarget.getXLenVT();
5864 
5865   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5866          "Unexpected VTs!");
5867   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5868   // Targets have to explicitly opt-in for extending vector loads.
5869   assert(LoadExtType == ISD::NON_EXTLOAD &&
5870          "Unexpected extending MGATHER/VP_GATHER");
5871   (void)LoadExtType;
5872 
5873   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5874   // the selection of the masked intrinsics doesn't do this for us.
5875   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5876 
5877   MVT ContainerVT = VT;
5878   if (VT.isFixedLengthVector()) {
5879     // We need to use the larger of the result and index type to determine the
5880     // scalable type to use so we don't increase LMUL for any operand/result.
5881     if (VT.bitsGE(IndexVT)) {
5882       ContainerVT = getContainerForFixedLengthVector(VT);
5883       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5884                                  ContainerVT.getVectorElementCount());
5885     } else {
5886       IndexVT = getContainerForFixedLengthVector(IndexVT);
5887       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
5888                                      IndexVT.getVectorElementCount());
5889     }
5890 
5891     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
5892 
5893     if (!IsUnmasked) {
5894       MVT MaskVT =
5895           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5896       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5897       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5898     }
5899   }
5900 
5901   if (!VL)
5902     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5903 
5904   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
5905     IndexVT = IndexVT.changeVectorElementType(XLenVT);
5906     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
5907                                    VL);
5908     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
5909                         TrueMask, VL);
5910   }
5911 
5912   unsigned IntID =
5913       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
5914   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5915   if (IsUnmasked)
5916     Ops.push_back(DAG.getUNDEF(ContainerVT));
5917   else
5918     Ops.push_back(PassThru);
5919   Ops.push_back(BasePtr);
5920   Ops.push_back(Index);
5921   if (!IsUnmasked)
5922     Ops.push_back(Mask);
5923   Ops.push_back(VL);
5924   if (!IsUnmasked)
5925     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5926 
5927   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5928   SDValue Result =
5929       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5930   Chain = Result.getValue(1);
5931 
5932   if (VT.isFixedLengthVector())
5933     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5934 
5935   return DAG.getMergeValues({Result, Chain}, DL);
5936 }
5937 
5938 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
5939 // matched to a RVV indexed store. The RVV indexed store instructions only
5940 // support the "unsigned unscaled" addressing mode; indices are implicitly
5941 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
5942 // signed or scaled indexing is extended to the XLEN value type and scaled
5943 // accordingly.
5944 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
5945                                                 SelectionDAG &DAG) const {
5946   SDLoc DL(Op);
5947   const auto *MemSD = cast<MemSDNode>(Op.getNode());
5948   EVT MemVT = MemSD->getMemoryVT();
5949   MachineMemOperand *MMO = MemSD->getMemOperand();
5950   SDValue Chain = MemSD->getChain();
5951   SDValue BasePtr = MemSD->getBasePtr();
5952 
5953   bool IsTruncatingStore = false;
5954   SDValue Index, Mask, Val, VL;
5955 
5956   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
5957     Index = VPSN->getIndex();
5958     Mask = VPSN->getMask();
5959     Val = VPSN->getValue();
5960     VL = VPSN->getVectorLength();
5961     // VP doesn't support truncating stores.
5962     IsTruncatingStore = false;
5963   } else {
5964     // Else it must be a MSCATTER.
5965     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
5966     Index = MSN->getIndex();
5967     Mask = MSN->getMask();
5968     Val = MSN->getValue();
5969     IsTruncatingStore = MSN->isTruncatingStore();
5970   }
5971 
5972   MVT VT = Val.getSimpleValueType();
5973   MVT IndexVT = Index.getSimpleValueType();
5974   MVT XLenVT = Subtarget.getXLenVT();
5975 
5976   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
5977          "Unexpected VTs!");
5978   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
5979   // Targets have to explicitly opt-in for extending vector loads and
5980   // truncating vector stores.
5981   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
5982   (void)IsTruncatingStore;
5983 
5984   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5985   // the selection of the masked intrinsics doesn't do this for us.
5986   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5987 
5988   MVT ContainerVT = VT;
5989   if (VT.isFixedLengthVector()) {
5990     // We need to use the larger of the value and index type to determine the
5991     // scalable type to use so we don't increase LMUL for any operand/result.
5992     if (VT.bitsGE(IndexVT)) {
5993       ContainerVT = getContainerForFixedLengthVector(VT);
5994       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
5995                                  ContainerVT.getVectorElementCount());
5996     } else {
5997       IndexVT = getContainerForFixedLengthVector(IndexVT);
5998       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
5999                                      IndexVT.getVectorElementCount());
6000     }
6001 
6002     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6003     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6004 
6005     if (!IsUnmasked) {
6006       MVT MaskVT =
6007           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6008       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6009     }
6010   }
6011 
6012   if (!VL)
6013     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6014 
6015   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6016     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6017     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6018                                    VL);
6019     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6020                         TrueMask, VL);
6021   }
6022 
6023   unsigned IntID =
6024       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6025   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6026   Ops.push_back(Val);
6027   Ops.push_back(BasePtr);
6028   Ops.push_back(Index);
6029   if (!IsUnmasked)
6030     Ops.push_back(Mask);
6031   Ops.push_back(VL);
6032 
6033   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6034                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6035 }
6036 
6037 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6038                                                SelectionDAG &DAG) const {
6039   const MVT XLenVT = Subtarget.getXLenVT();
6040   SDLoc DL(Op);
6041   SDValue Chain = Op->getOperand(0);
6042   SDValue SysRegNo = DAG.getTargetConstant(
6043       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6044   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6045   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6046 
6047   // Encoding used for rounding mode in RISCV differs from that used in
6048   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6049   // table, which consists of a sequence of 4-bit fields, each representing
6050   // corresponding FLT_ROUNDS mode.
6051   static const int Table =
6052       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6053       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6054       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6055       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6056       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6057 
6058   SDValue Shift =
6059       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6060   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6061                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6062   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6063                                DAG.getConstant(7, DL, XLenVT));
6064 
6065   return DAG.getMergeValues({Masked, Chain}, DL);
6066 }
6067 
6068 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6069                                                SelectionDAG &DAG) const {
6070   const MVT XLenVT = Subtarget.getXLenVT();
6071   SDLoc DL(Op);
6072   SDValue Chain = Op->getOperand(0);
6073   SDValue RMValue = Op->getOperand(1);
6074   SDValue SysRegNo = DAG.getTargetConstant(
6075       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6076 
6077   // Encoding used for rounding mode in RISCV differs from that used in
6078   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6079   // a table, which consists of a sequence of 4-bit fields, each representing
6080   // corresponding RISCV mode.
6081   static const unsigned Table =
6082       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6083       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6084       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6085       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6086       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6087 
6088   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6089                               DAG.getConstant(2, DL, XLenVT));
6090   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6091                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6092   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6093                         DAG.getConstant(0x7, DL, XLenVT));
6094   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6095                      RMValue);
6096 }
6097 
6098 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6099   switch (IntNo) {
6100   default:
6101     llvm_unreachable("Unexpected Intrinsic");
6102   case Intrinsic::riscv_grev:
6103     return RISCVISD::GREVW;
6104   case Intrinsic::riscv_gorc:
6105     return RISCVISD::GORCW;
6106   case Intrinsic::riscv_bcompress:
6107     return RISCVISD::BCOMPRESSW;
6108   case Intrinsic::riscv_bdecompress:
6109     return RISCVISD::BDECOMPRESSW;
6110   case Intrinsic::riscv_bfp:
6111     return RISCVISD::BFPW;
6112   case Intrinsic::riscv_fsl:
6113     return RISCVISD::FSLW;
6114   case Intrinsic::riscv_fsr:
6115     return RISCVISD::FSRW;
6116   }
6117 }
6118 
6119 // Converts the given intrinsic to a i64 operation with any extension.
6120 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6121                                          unsigned IntNo) {
6122   SDLoc DL(N);
6123   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6124   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6125   SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6126   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2);
6127   // ReplaceNodeResults requires we maintain the same type for the return value.
6128   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6129 }
6130 
6131 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6132 // form of the given Opcode.
6133 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6134   switch (Opcode) {
6135   default:
6136     llvm_unreachable("Unexpected opcode");
6137   case ISD::SHL:
6138     return RISCVISD::SLLW;
6139   case ISD::SRA:
6140     return RISCVISD::SRAW;
6141   case ISD::SRL:
6142     return RISCVISD::SRLW;
6143   case ISD::SDIV:
6144     return RISCVISD::DIVW;
6145   case ISD::UDIV:
6146     return RISCVISD::DIVUW;
6147   case ISD::UREM:
6148     return RISCVISD::REMUW;
6149   case ISD::ROTL:
6150     return RISCVISD::ROLW;
6151   case ISD::ROTR:
6152     return RISCVISD::RORW;
6153   case RISCVISD::GREV:
6154     return RISCVISD::GREVW;
6155   case RISCVISD::GORC:
6156     return RISCVISD::GORCW;
6157   }
6158 }
6159 
6160 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6161 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6162 // otherwise be promoted to i64, making it difficult to select the
6163 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6164 // type i8/i16/i32 is lost.
6165 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6166                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6167   SDLoc DL(N);
6168   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6169   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6170   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6171   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6172   // ReplaceNodeResults requires we maintain the same type for the return value.
6173   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6174 }
6175 
6176 // Converts the given 32-bit operation to a i64 operation with signed extension
6177 // semantic to reduce the signed extension instructions.
6178 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6179   SDLoc DL(N);
6180   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6181   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6182   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6183   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6184                                DAG.getValueType(MVT::i32));
6185   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6186 }
6187 
6188 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6189                                              SmallVectorImpl<SDValue> &Results,
6190                                              SelectionDAG &DAG) const {
6191   SDLoc DL(N);
6192   switch (N->getOpcode()) {
6193   default:
6194     llvm_unreachable("Don't know how to custom type legalize this operation!");
6195   case ISD::STRICT_FP_TO_SINT:
6196   case ISD::STRICT_FP_TO_UINT:
6197   case ISD::FP_TO_SINT:
6198   case ISD::FP_TO_UINT: {
6199     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6200            "Unexpected custom legalisation");
6201     bool IsStrict = N->isStrictFPOpcode();
6202     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6203                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6204     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6205     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6206         TargetLowering::TypeSoftenFloat) {
6207       if (!isTypeLegal(Op0.getValueType()))
6208         return;
6209       if (IsStrict) {
6210         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6211                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6212         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6213         SDValue Res = DAG.getNode(
6214             Opc, DL, VTs, N->getOperand(0), Op0,
6215             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6216         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6217         Results.push_back(Res.getValue(1));
6218         return;
6219       }
6220       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6221       SDValue Res =
6222           DAG.getNode(Opc, DL, MVT::i64, Op0,
6223                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6224       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6225       return;
6226     }
6227     // If the FP type needs to be softened, emit a library call using the 'si'
6228     // version. If we left it to default legalization we'd end up with 'di'. If
6229     // the FP type doesn't need to be softened just let generic type
6230     // legalization promote the result type.
6231     RTLIB::Libcall LC;
6232     if (IsSigned)
6233       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6234     else
6235       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6236     MakeLibCallOptions CallOptions;
6237     EVT OpVT = Op0.getValueType();
6238     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6239     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6240     SDValue Result;
6241     std::tie(Result, Chain) =
6242         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6243     Results.push_back(Result);
6244     if (IsStrict)
6245       Results.push_back(Chain);
6246     break;
6247   }
6248   case ISD::READCYCLECOUNTER: {
6249     assert(!Subtarget.is64Bit() &&
6250            "READCYCLECOUNTER only has custom type legalization on riscv32");
6251 
6252     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6253     SDValue RCW =
6254         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6255 
6256     Results.push_back(
6257         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6258     Results.push_back(RCW.getValue(2));
6259     break;
6260   }
6261   case ISD::MUL: {
6262     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6263     unsigned XLen = Subtarget.getXLen();
6264     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6265     if (Size > XLen) {
6266       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6267       SDValue LHS = N->getOperand(0);
6268       SDValue RHS = N->getOperand(1);
6269       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6270 
6271       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6272       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6273       // We need exactly one side to be unsigned.
6274       if (LHSIsU == RHSIsU)
6275         return;
6276 
6277       auto MakeMULPair = [&](SDValue S, SDValue U) {
6278         MVT XLenVT = Subtarget.getXLenVT();
6279         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6280         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6281         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6282         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6283         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6284       };
6285 
6286       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6287       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6288 
6289       // The other operand should be signed, but still prefer MULH when
6290       // possible.
6291       if (RHSIsU && LHSIsS && !RHSIsS)
6292         Results.push_back(MakeMULPair(LHS, RHS));
6293       else if (LHSIsU && RHSIsS && !LHSIsS)
6294         Results.push_back(MakeMULPair(RHS, LHS));
6295 
6296       return;
6297     }
6298     LLVM_FALLTHROUGH;
6299   }
6300   case ISD::ADD:
6301   case ISD::SUB:
6302     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6303            "Unexpected custom legalisation");
6304     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6305     break;
6306   case ISD::SHL:
6307   case ISD::SRA:
6308   case ISD::SRL:
6309     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6310            "Unexpected custom legalisation");
6311     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6312       Results.push_back(customLegalizeToWOp(N, DAG));
6313       break;
6314     }
6315 
6316     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6317     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6318     // shift amount.
6319     if (N->getOpcode() == ISD::SHL) {
6320       SDLoc DL(N);
6321       SDValue NewOp0 =
6322           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6323       SDValue NewOp1 =
6324           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6325       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6326       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6327                                    DAG.getValueType(MVT::i32));
6328       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6329     }
6330 
6331     break;
6332   case ISD::ROTL:
6333   case ISD::ROTR:
6334     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6335            "Unexpected custom legalisation");
6336     Results.push_back(customLegalizeToWOp(N, DAG));
6337     break;
6338   case ISD::CTTZ:
6339   case ISD::CTTZ_ZERO_UNDEF:
6340   case ISD::CTLZ:
6341   case ISD::CTLZ_ZERO_UNDEF: {
6342     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6343            "Unexpected custom legalisation");
6344 
6345     SDValue NewOp0 =
6346         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6347     bool IsCTZ =
6348         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6349     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6350     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6351     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6352     return;
6353   }
6354   case ISD::SDIV:
6355   case ISD::UDIV:
6356   case ISD::UREM: {
6357     MVT VT = N->getSimpleValueType(0);
6358     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6359            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6360            "Unexpected custom legalisation");
6361     // Don't promote division/remainder by constant since we should expand those
6362     // to multiply by magic constant.
6363     // FIXME: What if the expansion is disabled for minsize.
6364     if (N->getOperand(1).getOpcode() == ISD::Constant)
6365       return;
6366 
6367     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6368     // the upper 32 bits. For other types we need to sign or zero extend
6369     // based on the opcode.
6370     unsigned ExtOpc = ISD::ANY_EXTEND;
6371     if (VT != MVT::i32)
6372       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6373                                            : ISD::ZERO_EXTEND;
6374 
6375     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6376     break;
6377   }
6378   case ISD::UADDO:
6379   case ISD::USUBO: {
6380     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6381            "Unexpected custom legalisation");
6382     bool IsAdd = N->getOpcode() == ISD::UADDO;
6383     // Create an ADDW or SUBW.
6384     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6385     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6386     SDValue Res =
6387         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6388     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6389                       DAG.getValueType(MVT::i32));
6390 
6391     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
6392     // Since the inputs are sign extended from i32, this is equivalent to
6393     // comparing the lower 32 bits.
6394     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6395     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6396                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
6397 
6398     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6399     Results.push_back(Overflow);
6400     return;
6401   }
6402   case ISD::UADDSAT:
6403   case ISD::USUBSAT: {
6404     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6405            "Unexpected custom legalisation");
6406     if (Subtarget.hasStdExtZbb()) {
6407       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6408       // sign extend allows overflow of the lower 32 bits to be detected on
6409       // the promoted size.
6410       SDValue LHS =
6411           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6412       SDValue RHS =
6413           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6414       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6415       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6416       return;
6417     }
6418 
6419     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6420     // promotion for UADDO/USUBO.
6421     Results.push_back(expandAddSubSat(N, DAG));
6422     return;
6423   }
6424   case ISD::BITCAST: {
6425     EVT VT = N->getValueType(0);
6426     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6427     SDValue Op0 = N->getOperand(0);
6428     EVT Op0VT = Op0.getValueType();
6429     MVT XLenVT = Subtarget.getXLenVT();
6430     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6431       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6432       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6433     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6434                Subtarget.hasStdExtF()) {
6435       SDValue FPConv =
6436           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6437       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6438     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6439                isTypeLegal(Op0VT)) {
6440       // Custom-legalize bitcasts from fixed-length vector types to illegal
6441       // scalar types in order to improve codegen. Bitcast the vector to a
6442       // one-element vector type whose element type is the same as the result
6443       // type, and extract the first element.
6444       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6445       if (isTypeLegal(BVT)) {
6446         SDValue BVec = DAG.getBitcast(BVT, Op0);
6447         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6448                                       DAG.getConstant(0, DL, XLenVT)));
6449       }
6450     }
6451     break;
6452   }
6453   case RISCVISD::GREV:
6454   case RISCVISD::GORC: {
6455     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6456            "Unexpected custom legalisation");
6457     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6458     // This is similar to customLegalizeToWOp, except that we pass the second
6459     // operand (a TargetConstant) straight through: it is already of type
6460     // XLenVT.
6461     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6462     SDValue NewOp0 =
6463         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6464     SDValue NewOp1 =
6465         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6466     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6467     // ReplaceNodeResults requires we maintain the same type for the return
6468     // value.
6469     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6470     break;
6471   }
6472   case RISCVISD::SHFL: {
6473     // There is no SHFLIW instruction, but we can just promote the operation.
6474     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6475            "Unexpected custom legalisation");
6476     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6477     SDValue NewOp0 =
6478         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6479     SDValue NewOp1 =
6480         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6481     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
6482     // ReplaceNodeResults requires we maintain the same type for the return
6483     // value.
6484     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6485     break;
6486   }
6487   case ISD::BSWAP:
6488   case ISD::BITREVERSE: {
6489     MVT VT = N->getSimpleValueType(0);
6490     MVT XLenVT = Subtarget.getXLenVT();
6491     assert((VT == MVT::i8 || VT == MVT::i16 ||
6492             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6493            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6494     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6495     unsigned Imm = VT.getSizeInBits() - 1;
6496     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6497     if (N->getOpcode() == ISD::BSWAP)
6498       Imm &= ~0x7U;
6499     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
6500     SDValue GREVI =
6501         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
6502     // ReplaceNodeResults requires we maintain the same type for the return
6503     // value.
6504     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6505     break;
6506   }
6507   case ISD::FSHL:
6508   case ISD::FSHR: {
6509     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6510            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6511     SDValue NewOp0 =
6512         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6513     SDValue NewOp1 =
6514         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6515     SDValue NewShAmt =
6516         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6517     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6518     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
6519     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
6520                            DAG.getConstant(0x1f, DL, MVT::i64));
6521     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
6522     // instruction use different orders. fshl will return its first operand for
6523     // shift of zero, fshr will return its second operand. fsl and fsr both
6524     // return rs1 so the ISD nodes need to have different operand orders.
6525     // Shift amount is in rs2.
6526     unsigned Opc = RISCVISD::FSLW;
6527     if (N->getOpcode() == ISD::FSHR) {
6528       std::swap(NewOp0, NewOp1);
6529       Opc = RISCVISD::FSRW;
6530     }
6531     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
6532     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6533     break;
6534   }
6535   case ISD::EXTRACT_VECTOR_ELT: {
6536     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6537     // type is illegal (currently only vXi64 RV32).
6538     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6539     // transferred to the destination register. We issue two of these from the
6540     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6541     // first element.
6542     SDValue Vec = N->getOperand(0);
6543     SDValue Idx = N->getOperand(1);
6544 
6545     // The vector type hasn't been legalized yet so we can't issue target
6546     // specific nodes if it needs legalization.
6547     // FIXME: We would manually legalize if it's important.
6548     if (!isTypeLegal(Vec.getValueType()))
6549       return;
6550 
6551     MVT VecVT = Vec.getSimpleValueType();
6552 
6553     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6554            VecVT.getVectorElementType() == MVT::i64 &&
6555            "Unexpected EXTRACT_VECTOR_ELT legalization");
6556 
6557     // If this is a fixed vector, we need to convert it to a scalable vector.
6558     MVT ContainerVT = VecVT;
6559     if (VecVT.isFixedLengthVector()) {
6560       ContainerVT = getContainerForFixedLengthVector(VecVT);
6561       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6562     }
6563 
6564     MVT XLenVT = Subtarget.getXLenVT();
6565 
6566     // Use a VL of 1 to avoid processing more elements than we need.
6567     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6568     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6569     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6570 
6571     // Unless the index is known to be 0, we must slide the vector down to get
6572     // the desired element into index 0.
6573     if (!isNullConstant(Idx)) {
6574       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6575                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6576     }
6577 
6578     // Extract the lower XLEN bits of the correct vector element.
6579     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6580 
6581     // To extract the upper XLEN bits of the vector element, shift the first
6582     // element right by 32 bits and re-extract the lower XLEN bits.
6583     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6584                                      DAG.getConstant(32, DL, XLenVT), VL);
6585     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6586                                  ThirtyTwoV, Mask, VL);
6587 
6588     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6589 
6590     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6591     break;
6592   }
6593   case ISD::INTRINSIC_WO_CHAIN: {
6594     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6595     switch (IntNo) {
6596     default:
6597       llvm_unreachable(
6598           "Don't know how to custom type legalize this intrinsic!");
6599     case Intrinsic::riscv_grev:
6600     case Intrinsic::riscv_gorc:
6601     case Intrinsic::riscv_bcompress:
6602     case Intrinsic::riscv_bdecompress:
6603     case Intrinsic::riscv_bfp: {
6604       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6605              "Unexpected custom legalisation");
6606       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
6607       break;
6608     }
6609     case Intrinsic::riscv_fsl:
6610     case Intrinsic::riscv_fsr: {
6611       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6612              "Unexpected custom legalisation");
6613       SDValue NewOp1 =
6614           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6615       SDValue NewOp2 =
6616           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6617       SDValue NewOp3 =
6618           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3));
6619       unsigned Opc = getRISCVWOpcodeByIntr(IntNo);
6620       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3);
6621       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6622       break;
6623     }
6624     case Intrinsic::riscv_orc_b: {
6625       // Lower to the GORCI encoding for orc.b with the operand extended.
6626       SDValue NewOp =
6627           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6628       // If Zbp is enabled, use GORCIW which will sign extend the result.
6629       unsigned Opc =
6630           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6631       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6632                                 DAG.getConstant(7, DL, MVT::i64));
6633       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6634       return;
6635     }
6636     case Intrinsic::riscv_shfl:
6637     case Intrinsic::riscv_unshfl: {
6638       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6639              "Unexpected custom legalisation");
6640       SDValue NewOp1 =
6641           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6642       SDValue NewOp2 =
6643           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6644       unsigned Opc =
6645           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6646       // There is no (UN)SHFLIW. If the control word is a constant, we can use
6647       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
6648       // will be shuffled the same way as the lower 32 bit half, but the two
6649       // halves won't cross.
6650       if (isa<ConstantSDNode>(NewOp2)) {
6651         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6652                              DAG.getConstant(0xf, DL, MVT::i64));
6653         Opc =
6654             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6655       }
6656       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6657       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6658       break;
6659     }
6660     case Intrinsic::riscv_vmv_x_s: {
6661       EVT VT = N->getValueType(0);
6662       MVT XLenVT = Subtarget.getXLenVT();
6663       if (VT.bitsLT(XLenVT)) {
6664         // Simple case just extract using vmv.x.s and truncate.
6665         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6666                                       Subtarget.getXLenVT(), N->getOperand(1));
6667         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6668         return;
6669       }
6670 
6671       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6672              "Unexpected custom legalization");
6673 
6674       // We need to do the move in two steps.
6675       SDValue Vec = N->getOperand(1);
6676       MVT VecVT = Vec.getSimpleValueType();
6677 
6678       // First extract the lower XLEN bits of the element.
6679       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6680 
6681       // To extract the upper XLEN bits of the vector element, shift the first
6682       // element right by 32 bits and re-extract the lower XLEN bits.
6683       SDValue VL = DAG.getConstant(1, DL, XLenVT);
6684       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
6685       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6686       SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT,
6687                                        DAG.getConstant(32, DL, XLenVT), VL);
6688       SDValue LShr32 =
6689           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
6690       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6691 
6692       Results.push_back(
6693           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6694       break;
6695     }
6696     }
6697     break;
6698   }
6699   case ISD::VECREDUCE_ADD:
6700   case ISD::VECREDUCE_AND:
6701   case ISD::VECREDUCE_OR:
6702   case ISD::VECREDUCE_XOR:
6703   case ISD::VECREDUCE_SMAX:
6704   case ISD::VECREDUCE_UMAX:
6705   case ISD::VECREDUCE_SMIN:
6706   case ISD::VECREDUCE_UMIN:
6707     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6708       Results.push_back(V);
6709     break;
6710   case ISD::VP_REDUCE_ADD:
6711   case ISD::VP_REDUCE_AND:
6712   case ISD::VP_REDUCE_OR:
6713   case ISD::VP_REDUCE_XOR:
6714   case ISD::VP_REDUCE_SMAX:
6715   case ISD::VP_REDUCE_UMAX:
6716   case ISD::VP_REDUCE_SMIN:
6717   case ISD::VP_REDUCE_UMIN:
6718     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6719       Results.push_back(V);
6720     break;
6721   case ISD::FLT_ROUNDS_: {
6722     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
6723     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
6724     Results.push_back(Res.getValue(0));
6725     Results.push_back(Res.getValue(1));
6726     break;
6727   }
6728   }
6729 }
6730 
6731 // A structure to hold one of the bit-manipulation patterns below. Together, a
6732 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
6733 //   (or (and (shl x, 1), 0xAAAAAAAA),
6734 //       (and (srl x, 1), 0x55555555))
6735 struct RISCVBitmanipPat {
6736   SDValue Op;
6737   unsigned ShAmt;
6738   bool IsSHL;
6739 
6740   bool formsPairWith(const RISCVBitmanipPat &Other) const {
6741     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
6742   }
6743 };
6744 
6745 // Matches patterns of the form
6746 //   (and (shl x, C2), (C1 << C2))
6747 //   (and (srl x, C2), C1)
6748 //   (shl (and x, C1), C2)
6749 //   (srl (and x, (C1 << C2)), C2)
6750 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
6751 // The expected masks for each shift amount are specified in BitmanipMasks where
6752 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
6753 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
6754 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
6755 // XLen is 64.
6756 static Optional<RISCVBitmanipPat>
6757 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
6758   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
6759          "Unexpected number of masks");
6760   Optional<uint64_t> Mask;
6761   // Optionally consume a mask around the shift operation.
6762   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
6763     Mask = Op.getConstantOperandVal(1);
6764     Op = Op.getOperand(0);
6765   }
6766   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
6767     return None;
6768   bool IsSHL = Op.getOpcode() == ISD::SHL;
6769 
6770   if (!isa<ConstantSDNode>(Op.getOperand(1)))
6771     return None;
6772   uint64_t ShAmt = Op.getConstantOperandVal(1);
6773 
6774   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
6775   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
6776     return None;
6777   // If we don't have enough masks for 64 bit, then we must be trying to
6778   // match SHFL so we're only allowed to shift 1/4 of the width.
6779   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
6780     return None;
6781 
6782   SDValue Src = Op.getOperand(0);
6783 
6784   // The expected mask is shifted left when the AND is found around SHL
6785   // patterns.
6786   //   ((x >> 1) & 0x55555555)
6787   //   ((x << 1) & 0xAAAAAAAA)
6788   bool SHLExpMask = IsSHL;
6789 
6790   if (!Mask) {
6791     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
6792     // the mask is all ones: consume that now.
6793     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
6794       Mask = Src.getConstantOperandVal(1);
6795       Src = Src.getOperand(0);
6796       // The expected mask is now in fact shifted left for SRL, so reverse the
6797       // decision.
6798       //   ((x & 0xAAAAAAAA) >> 1)
6799       //   ((x & 0x55555555) << 1)
6800       SHLExpMask = !SHLExpMask;
6801     } else {
6802       // Use a default shifted mask of all-ones if there's no AND, truncated
6803       // down to the expected width. This simplifies the logic later on.
6804       Mask = maskTrailingOnes<uint64_t>(Width);
6805       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
6806     }
6807   }
6808 
6809   unsigned MaskIdx = Log2_32(ShAmt);
6810   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
6811 
6812   if (SHLExpMask)
6813     ExpMask <<= ShAmt;
6814 
6815   if (Mask != ExpMask)
6816     return None;
6817 
6818   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
6819 }
6820 
6821 // Matches any of the following bit-manipulation patterns:
6822 //   (and (shl x, 1), (0x55555555 << 1))
6823 //   (and (srl x, 1), 0x55555555)
6824 //   (shl (and x, 0x55555555), 1)
6825 //   (srl (and x, (0x55555555 << 1)), 1)
6826 // where the shift amount and mask may vary thus:
6827 //   [1]  = 0x55555555 / 0xAAAAAAAA
6828 //   [2]  = 0x33333333 / 0xCCCCCCCC
6829 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
6830 //   [8]  = 0x00FF00FF / 0xFF00FF00
6831 //   [16] = 0x0000FFFF / 0xFFFFFFFF
6832 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
6833 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
6834   // These are the unshifted masks which we use to match bit-manipulation
6835   // patterns. They may be shifted left in certain circumstances.
6836   static const uint64_t BitmanipMasks[] = {
6837       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
6838       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
6839 
6840   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6841 }
6842 
6843 // Match the following pattern as a GREVI(W) operation
6844 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
6845 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
6846                                const RISCVSubtarget &Subtarget) {
6847   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6848   EVT VT = Op.getValueType();
6849 
6850   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6851     auto LHS = matchGREVIPat(Op.getOperand(0));
6852     auto RHS = matchGREVIPat(Op.getOperand(1));
6853     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
6854       SDLoc DL(Op);
6855       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
6856                          DAG.getConstant(LHS->ShAmt, DL, VT));
6857     }
6858   }
6859   return SDValue();
6860 }
6861 
6862 // Matches any the following pattern as a GORCI(W) operation
6863 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
6864 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
6865 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
6866 // Note that with the variant of 3.,
6867 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
6868 // the inner pattern will first be matched as GREVI and then the outer
6869 // pattern will be matched to GORC via the first rule above.
6870 // 4.  (or (rotl/rotr x, bitwidth/2), x)
6871 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
6872                                const RISCVSubtarget &Subtarget) {
6873   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6874   EVT VT = Op.getValueType();
6875 
6876   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
6877     SDLoc DL(Op);
6878     SDValue Op0 = Op.getOperand(0);
6879     SDValue Op1 = Op.getOperand(1);
6880 
6881     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
6882       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
6883           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
6884           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
6885         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
6886       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
6887       if ((Reverse.getOpcode() == ISD::ROTL ||
6888            Reverse.getOpcode() == ISD::ROTR) &&
6889           Reverse.getOperand(0) == X &&
6890           isa<ConstantSDNode>(Reverse.getOperand(1))) {
6891         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
6892         if (RotAmt == (VT.getSizeInBits() / 2))
6893           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
6894                              DAG.getConstant(RotAmt, DL, VT));
6895       }
6896       return SDValue();
6897     };
6898 
6899     // Check for either commutable permutation of (or (GREVI x, shamt), x)
6900     if (SDValue V = MatchOROfReverse(Op0, Op1))
6901       return V;
6902     if (SDValue V = MatchOROfReverse(Op1, Op0))
6903       return V;
6904 
6905     // OR is commutable so canonicalize its OR operand to the left
6906     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
6907       std::swap(Op0, Op1);
6908     if (Op0.getOpcode() != ISD::OR)
6909       return SDValue();
6910     SDValue OrOp0 = Op0.getOperand(0);
6911     SDValue OrOp1 = Op0.getOperand(1);
6912     auto LHS = matchGREVIPat(OrOp0);
6913     // OR is commutable so swap the operands and try again: x might have been
6914     // on the left
6915     if (!LHS) {
6916       std::swap(OrOp0, OrOp1);
6917       LHS = matchGREVIPat(OrOp0);
6918     }
6919     auto RHS = matchGREVIPat(Op1);
6920     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
6921       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
6922                          DAG.getConstant(LHS->ShAmt, DL, VT));
6923     }
6924   }
6925   return SDValue();
6926 }
6927 
6928 // Matches any of the following bit-manipulation patterns:
6929 //   (and (shl x, 1), (0x22222222 << 1))
6930 //   (and (srl x, 1), 0x22222222)
6931 //   (shl (and x, 0x22222222), 1)
6932 //   (srl (and x, (0x22222222 << 1)), 1)
6933 // where the shift amount and mask may vary thus:
6934 //   [1]  = 0x22222222 / 0x44444444
6935 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
6936 //   [4]  = 0x00F000F0 / 0x0F000F00
6937 //   [8]  = 0x0000FF00 / 0x00FF0000
6938 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
6939 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
6940   // These are the unshifted masks which we use to match bit-manipulation
6941   // patterns. They may be shifted left in certain circumstances.
6942   static const uint64_t BitmanipMasks[] = {
6943       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
6944       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
6945 
6946   return matchRISCVBitmanipPat(Op, BitmanipMasks);
6947 }
6948 
6949 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
6950 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
6951                                const RISCVSubtarget &Subtarget) {
6952   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
6953   EVT VT = Op.getValueType();
6954 
6955   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
6956     return SDValue();
6957 
6958   SDValue Op0 = Op.getOperand(0);
6959   SDValue Op1 = Op.getOperand(1);
6960 
6961   // Or is commutable so canonicalize the second OR to the LHS.
6962   if (Op0.getOpcode() != ISD::OR)
6963     std::swap(Op0, Op1);
6964   if (Op0.getOpcode() != ISD::OR)
6965     return SDValue();
6966 
6967   // We found an inner OR, so our operands are the operands of the inner OR
6968   // and the other operand of the outer OR.
6969   SDValue A = Op0.getOperand(0);
6970   SDValue B = Op0.getOperand(1);
6971   SDValue C = Op1;
6972 
6973   auto Match1 = matchSHFLPat(A);
6974   auto Match2 = matchSHFLPat(B);
6975 
6976   // If neither matched, we failed.
6977   if (!Match1 && !Match2)
6978     return SDValue();
6979 
6980   // We had at least one match. if one failed, try the remaining C operand.
6981   if (!Match1) {
6982     std::swap(A, C);
6983     Match1 = matchSHFLPat(A);
6984     if (!Match1)
6985       return SDValue();
6986   } else if (!Match2) {
6987     std::swap(B, C);
6988     Match2 = matchSHFLPat(B);
6989     if (!Match2)
6990       return SDValue();
6991   }
6992   assert(Match1 && Match2);
6993 
6994   // Make sure our matches pair up.
6995   if (!Match1->formsPairWith(*Match2))
6996     return SDValue();
6997 
6998   // All the remains is to make sure C is an AND with the same input, that masks
6999   // out the bits that are being shuffled.
7000   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7001       C.getOperand(0) != Match1->Op)
7002     return SDValue();
7003 
7004   uint64_t Mask = C.getConstantOperandVal(1);
7005 
7006   static const uint64_t BitmanipMasks[] = {
7007       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7008       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7009   };
7010 
7011   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7012   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7013   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7014 
7015   if (Mask != ExpMask)
7016     return SDValue();
7017 
7018   SDLoc DL(Op);
7019   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7020                      DAG.getConstant(Match1->ShAmt, DL, VT));
7021 }
7022 
7023 // Optimize (add (shl x, c0), (shl y, c1)) ->
7024 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7025 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7026                                   const RISCVSubtarget &Subtarget) {
7027   // Perform this optimization only in the zba extension.
7028   if (!Subtarget.hasStdExtZba())
7029     return SDValue();
7030 
7031   // Skip for vector types and larger types.
7032   EVT VT = N->getValueType(0);
7033   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7034     return SDValue();
7035 
7036   // The two operand nodes must be SHL and have no other use.
7037   SDValue N0 = N->getOperand(0);
7038   SDValue N1 = N->getOperand(1);
7039   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7040       !N0->hasOneUse() || !N1->hasOneUse())
7041     return SDValue();
7042 
7043   // Check c0 and c1.
7044   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7045   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7046   if (!N0C || !N1C)
7047     return SDValue();
7048   int64_t C0 = N0C->getSExtValue();
7049   int64_t C1 = N1C->getSExtValue();
7050   if (C0 <= 0 || C1 <= 0)
7051     return SDValue();
7052 
7053   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7054   int64_t Bits = std::min(C0, C1);
7055   int64_t Diff = std::abs(C0 - C1);
7056   if (Diff != 1 && Diff != 2 && Diff != 3)
7057     return SDValue();
7058 
7059   // Build nodes.
7060   SDLoc DL(N);
7061   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7062   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7063   SDValue NA0 =
7064       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7065   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7066   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7067 }
7068 
7069 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7070 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7071 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7072 // not undo itself, but they are redundant.
7073 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7074   SDValue Src = N->getOperand(0);
7075 
7076   if (Src.getOpcode() != N->getOpcode())
7077     return SDValue();
7078 
7079   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7080       !isa<ConstantSDNode>(Src.getOperand(1)))
7081     return SDValue();
7082 
7083   unsigned ShAmt1 = N->getConstantOperandVal(1);
7084   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7085   Src = Src.getOperand(0);
7086 
7087   unsigned CombinedShAmt;
7088   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
7089     CombinedShAmt = ShAmt1 | ShAmt2;
7090   else
7091     CombinedShAmt = ShAmt1 ^ ShAmt2;
7092 
7093   if (CombinedShAmt == 0)
7094     return Src;
7095 
7096   SDLoc DL(N);
7097   return DAG.getNode(
7098       N->getOpcode(), DL, N->getValueType(0), Src,
7099       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7100 }
7101 
7102 // Combine a constant select operand into its use:
7103 //
7104 // (and (select cond, -1, c), x)
7105 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7106 // (or  (select cond, 0, c), x)
7107 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7108 // (xor (select cond, 0, c), x)
7109 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7110 // (add (select cond, 0, c), x)
7111 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7112 // (sub x, (select cond, 0, c))
7113 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7114 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7115                                    SelectionDAG &DAG, bool AllOnes) {
7116   EVT VT = N->getValueType(0);
7117 
7118   // Skip vectors.
7119   if (VT.isVector())
7120     return SDValue();
7121 
7122   if ((Slct.getOpcode() != ISD::SELECT &&
7123        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7124       !Slct.hasOneUse())
7125     return SDValue();
7126 
7127   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7128     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7129   };
7130 
7131   bool SwapSelectOps;
7132   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7133   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7134   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7135   SDValue NonConstantVal;
7136   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7137     SwapSelectOps = false;
7138     NonConstantVal = FalseVal;
7139   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7140     SwapSelectOps = true;
7141     NonConstantVal = TrueVal;
7142   } else
7143     return SDValue();
7144 
7145   // Slct is now know to be the desired identity constant when CC is true.
7146   TrueVal = OtherOp;
7147   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7148   // Unless SwapSelectOps says the condition should be false.
7149   if (SwapSelectOps)
7150     std::swap(TrueVal, FalseVal);
7151 
7152   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7153     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7154                        {Slct.getOperand(0), Slct.getOperand(1),
7155                         Slct.getOperand(2), TrueVal, FalseVal});
7156 
7157   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7158                      {Slct.getOperand(0), TrueVal, FalseVal});
7159 }
7160 
7161 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7162 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7163                                               bool AllOnes) {
7164   SDValue N0 = N->getOperand(0);
7165   SDValue N1 = N->getOperand(1);
7166   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7167     return Result;
7168   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7169     return Result;
7170   return SDValue();
7171 }
7172 
7173 // Transform (add (mul x, c0), c1) ->
7174 //           (add (mul (add x, c1/c0), c0), c1%c0).
7175 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7176 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7177 // to an infinite loop in DAGCombine if transformed.
7178 // Or transform (add (mul x, c0), c1) ->
7179 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7180 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7181 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7182 // lead to an infinite loop in DAGCombine if transformed.
7183 // Or transform (add (mul x, c0), c1) ->
7184 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7185 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7186 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7187 // lead to an infinite loop in DAGCombine if transformed.
7188 // Or transform (add (mul x, c0), c1) ->
7189 //              (mul (add x, c1/c0), c0).
7190 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7191 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7192                                      const RISCVSubtarget &Subtarget) {
7193   // Skip for vector types and larger types.
7194   EVT VT = N->getValueType(0);
7195   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7196     return SDValue();
7197   // The first operand node must be a MUL and has no other use.
7198   SDValue N0 = N->getOperand(0);
7199   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7200     return SDValue();
7201   // Check if c0 and c1 match above conditions.
7202   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7203   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7204   if (!N0C || !N1C)
7205     return SDValue();
7206   // If N0C has multiple uses it's possible one of the cases in
7207   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7208   // in an infinite loop.
7209   if (!N0C->hasOneUse())
7210     return SDValue();
7211   int64_t C0 = N0C->getSExtValue();
7212   int64_t C1 = N1C->getSExtValue();
7213   int64_t CA, CB;
7214   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7215     return SDValue();
7216   // Search for proper CA (non-zero) and CB that both are simm12.
7217   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7218       !isInt<12>(C0 * (C1 / C0))) {
7219     CA = C1 / C0;
7220     CB = C1 % C0;
7221   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7222              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7223     CA = C1 / C0 + 1;
7224     CB = C1 % C0 - C0;
7225   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7226              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7227     CA = C1 / C0 - 1;
7228     CB = C1 % C0 + C0;
7229   } else
7230     return SDValue();
7231   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7232   SDLoc DL(N);
7233   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7234                              DAG.getConstant(CA, DL, VT));
7235   SDValue New1 =
7236       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7237   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7238 }
7239 
7240 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7241                                  const RISCVSubtarget &Subtarget) {
7242   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7243     return V;
7244   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7245     return V;
7246   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7247   //      (select lhs, rhs, cc, x, (add x, y))
7248   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7249 }
7250 
7251 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7252   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7253   //      (select lhs, rhs, cc, x, (sub x, y))
7254   SDValue N0 = N->getOperand(0);
7255   SDValue N1 = N->getOperand(1);
7256   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7257 }
7258 
7259 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7260   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7261   //      (select lhs, rhs, cc, x, (and x, y))
7262   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7263 }
7264 
7265 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7266                                 const RISCVSubtarget &Subtarget) {
7267   if (Subtarget.hasStdExtZbp()) {
7268     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7269       return GREV;
7270     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7271       return GORC;
7272     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7273       return SHFL;
7274   }
7275 
7276   // fold (or (select cond, 0, y), x) ->
7277   //      (select cond, x, (or x, y))
7278   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7279 }
7280 
7281 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7282   // fold (xor (select cond, 0, y), x) ->
7283   //      (select cond, x, (xor x, y))
7284   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7285 }
7286 
7287 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
7288 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
7289 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
7290 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
7291 // ADDW/SUBW/MULW.
7292 static SDValue performANY_EXTENDCombine(SDNode *N,
7293                                         TargetLowering::DAGCombinerInfo &DCI,
7294                                         const RISCVSubtarget &Subtarget) {
7295   if (!Subtarget.is64Bit())
7296     return SDValue();
7297 
7298   SelectionDAG &DAG = DCI.DAG;
7299 
7300   SDValue Src = N->getOperand(0);
7301   EVT VT = N->getValueType(0);
7302   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
7303     return SDValue();
7304 
7305   // The opcode must be one that can implicitly sign_extend.
7306   // FIXME: Additional opcodes.
7307   switch (Src.getOpcode()) {
7308   default:
7309     return SDValue();
7310   case ISD::MUL:
7311     if (!Subtarget.hasStdExtM())
7312       return SDValue();
7313     LLVM_FALLTHROUGH;
7314   case ISD::ADD:
7315   case ISD::SUB:
7316     break;
7317   }
7318 
7319   // Only handle cases where the result is used by a CopyToReg. That likely
7320   // means the value is a liveout of the basic block. This helps prevent
7321   // infinite combine loops like PR51206.
7322   if (none_of(N->uses(),
7323               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
7324     return SDValue();
7325 
7326   SmallVector<SDNode *, 4> SetCCs;
7327   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
7328                             UE = Src.getNode()->use_end();
7329        UI != UE; ++UI) {
7330     SDNode *User = *UI;
7331     if (User == N)
7332       continue;
7333     if (UI.getUse().getResNo() != Src.getResNo())
7334       continue;
7335     // All i32 setccs are legalized by sign extending operands.
7336     if (User->getOpcode() == ISD::SETCC) {
7337       SetCCs.push_back(User);
7338       continue;
7339     }
7340     // We don't know if we can extend this user.
7341     break;
7342   }
7343 
7344   // If we don't have any SetCCs, this isn't worthwhile.
7345   if (SetCCs.empty())
7346     return SDValue();
7347 
7348   SDLoc DL(N);
7349   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
7350   DCI.CombineTo(N, SExt);
7351 
7352   // Promote all the setccs.
7353   for (SDNode *SetCC : SetCCs) {
7354     SmallVector<SDValue, 4> Ops;
7355 
7356     for (unsigned j = 0; j != 2; ++j) {
7357       SDValue SOp = SetCC->getOperand(j);
7358       if (SOp == Src)
7359         Ops.push_back(SExt);
7360       else
7361         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
7362     }
7363 
7364     Ops.push_back(SetCC->getOperand(2));
7365     DCI.CombineTo(SetCC,
7366                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7367   }
7368   return SDValue(N, 0);
7369 }
7370 
7371 // Try to form VWMUL, VWMULU or VWMULSU.
7372 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
7373 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
7374                                        bool Commute) {
7375   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
7376   SDValue Op0 = N->getOperand(0);
7377   SDValue Op1 = N->getOperand(1);
7378   if (Commute)
7379     std::swap(Op0, Op1);
7380 
7381   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
7382   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
7383   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
7384   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
7385     return SDValue();
7386 
7387   SDValue Mask = N->getOperand(2);
7388   SDValue VL = N->getOperand(3);
7389 
7390   // Make sure the mask and VL match.
7391   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
7392     return SDValue();
7393 
7394   MVT VT = N->getSimpleValueType(0);
7395 
7396   // Determine the narrow size for a widening multiply.
7397   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7398   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7399                                   VT.getVectorElementCount());
7400 
7401   SDLoc DL(N);
7402 
7403   // See if the other operand is the same opcode.
7404   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
7405     if (!Op1.hasOneUse())
7406       return SDValue();
7407 
7408     // Make sure the mask and VL match.
7409     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
7410       return SDValue();
7411 
7412     Op1 = Op1.getOperand(0);
7413   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
7414     // The operand is a splat of a scalar.
7415 
7416     // The VL must be the same.
7417     if (Op1.getOperand(1) != VL)
7418       return SDValue();
7419 
7420     // Get the scalar value.
7421     Op1 = Op1.getOperand(0);
7422 
7423     // See if have enough sign bits or zero bits in the scalar to use a
7424     // widening multiply by splatting to smaller element size.
7425     unsigned EltBits = VT.getScalarSizeInBits();
7426     unsigned ScalarBits = Op1.getValueSizeInBits();
7427     // Make sure we're getting all element bits from the scalar register.
7428     // FIXME: Support implicit sign extension of vmv.v.x?
7429     if (ScalarBits < EltBits)
7430       return SDValue();
7431 
7432     if (IsSignExt) {
7433       if (DAG.ComputeNumSignBits(Op1) <= (ScalarBits - NarrowSize))
7434         return SDValue();
7435     } else {
7436       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7437       if (!DAG.MaskedValueIsZero(Op1, Mask))
7438         return SDValue();
7439     }
7440 
7441     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, Op1, VL);
7442   } else
7443     return SDValue();
7444 
7445   Op0 = Op0.getOperand(0);
7446 
7447   // Re-introduce narrower extends if needed.
7448   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
7449   if (Op0.getValueType() != NarrowVT)
7450     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7451   // vwmulsu requires second operand to be zero extended.
7452   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
7453   if (Op1.getValueType() != NarrowVT)
7454     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7455 
7456   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
7457   if (!IsVWMULSU)
7458     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
7459   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
7460 }
7461 
7462 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
7463   switch (Op.getOpcode()) {
7464   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
7465   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
7466   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
7467   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
7468   case ISD::FROUND:     return RISCVFPRndMode::RMM;
7469   }
7470 
7471   return RISCVFPRndMode::Invalid;
7472 }
7473 
7474 // Fold
7475 //   (fp_to_int (froundeven X)) -> fcvt X, rne
7476 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
7477 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
7478 //   (fp_to_int (fceil X))      -> fcvt X, rup
7479 //   (fp_to_int (fround X))     -> fcvt X, rmm
7480 static SDValue performFP_TO_INTCombine(SDNode *N,
7481                                        TargetLowering::DAGCombinerInfo &DCI,
7482                                        const RISCVSubtarget &Subtarget) {
7483   SelectionDAG &DAG = DCI.DAG;
7484   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7485   MVT XLenVT = Subtarget.getXLenVT();
7486 
7487   // Only handle XLen or i32 types. Other types narrower than XLen will
7488   // eventually be legalized to XLenVT.
7489   EVT VT = N->getValueType(0);
7490   if (VT != MVT::i32 && VT != XLenVT)
7491     return SDValue();
7492 
7493   SDValue Src = N->getOperand(0);
7494 
7495   // Ensure the FP type is also legal.
7496   if (!TLI.isTypeLegal(Src.getValueType()))
7497     return SDValue();
7498 
7499   // Don't do this for f16 with Zfhmin and not Zfh.
7500   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7501     return SDValue();
7502 
7503   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7504   if (FRM == RISCVFPRndMode::Invalid)
7505     return SDValue();
7506 
7507   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7508 
7509   unsigned Opc;
7510   if (VT == XLenVT)
7511     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7512   else
7513     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7514 
7515   SDLoc DL(N);
7516   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
7517                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7518   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
7519 }
7520 
7521 // Fold
7522 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
7523 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
7524 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
7525 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
7526 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
7527 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
7528                                        TargetLowering::DAGCombinerInfo &DCI,
7529                                        const RISCVSubtarget &Subtarget) {
7530   SelectionDAG &DAG = DCI.DAG;
7531   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7532   MVT XLenVT = Subtarget.getXLenVT();
7533 
7534   // Only handle XLen types. Other types narrower than XLen will eventually be
7535   // legalized to XLenVT.
7536   EVT DstVT = N->getValueType(0);
7537   if (DstVT != XLenVT)
7538     return SDValue();
7539 
7540   SDValue Src = N->getOperand(0);
7541 
7542   // Ensure the FP type is also legal.
7543   if (!TLI.isTypeLegal(Src.getValueType()))
7544     return SDValue();
7545 
7546   // Don't do this for f16 with Zfhmin and not Zfh.
7547   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
7548     return SDValue();
7549 
7550   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7551 
7552   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
7553   if (FRM == RISCVFPRndMode::Invalid)
7554     return SDValue();
7555 
7556   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
7557 
7558   unsigned Opc;
7559   if (SatVT == DstVT)
7560     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
7561   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
7562     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
7563   else
7564     return SDValue();
7565   // FIXME: Support other SatVTs by clamping before or after the conversion.
7566 
7567   Src = Src.getOperand(0);
7568 
7569   SDLoc DL(N);
7570   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
7571                                 DAG.getTargetConstant(FRM, DL, XLenVT));
7572 
7573   // RISCV FP-to-int conversions saturate to the destination register size, but
7574   // don't produce 0 for nan.
7575   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
7576   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
7577 }
7578 
7579 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
7580                                                DAGCombinerInfo &DCI) const {
7581   SelectionDAG &DAG = DCI.DAG;
7582 
7583   // Helper to call SimplifyDemandedBits on an operand of N where only some low
7584   // bits are demanded. N will be added to the Worklist if it was not deleted.
7585   // Caller should return SDValue(N, 0) if this returns true.
7586   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
7587     SDValue Op = N->getOperand(OpNo);
7588     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
7589     if (!SimplifyDemandedBits(Op, Mask, DCI))
7590       return false;
7591 
7592     if (N->getOpcode() != ISD::DELETED_NODE)
7593       DCI.AddToWorklist(N);
7594     return true;
7595   };
7596 
7597   switch (N->getOpcode()) {
7598   default:
7599     break;
7600   case RISCVISD::SplitF64: {
7601     SDValue Op0 = N->getOperand(0);
7602     // If the input to SplitF64 is just BuildPairF64 then the operation is
7603     // redundant. Instead, use BuildPairF64's operands directly.
7604     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
7605       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
7606 
7607     SDLoc DL(N);
7608 
7609     // It's cheaper to materialise two 32-bit integers than to load a double
7610     // from the constant pool and transfer it to integer registers through the
7611     // stack.
7612     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
7613       APInt V = C->getValueAPF().bitcastToAPInt();
7614       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
7615       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
7616       return DCI.CombineTo(N, Lo, Hi);
7617     }
7618 
7619     // This is a target-specific version of a DAGCombine performed in
7620     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7621     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7622     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7623     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7624         !Op0.getNode()->hasOneUse())
7625       break;
7626     SDValue NewSplitF64 =
7627         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
7628                     Op0.getOperand(0));
7629     SDValue Lo = NewSplitF64.getValue(0);
7630     SDValue Hi = NewSplitF64.getValue(1);
7631     APInt SignBit = APInt::getSignMask(32);
7632     if (Op0.getOpcode() == ISD::FNEG) {
7633       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
7634                                   DAG.getConstant(SignBit, DL, MVT::i32));
7635       return DCI.CombineTo(N, Lo, NewHi);
7636     }
7637     assert(Op0.getOpcode() == ISD::FABS);
7638     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
7639                                 DAG.getConstant(~SignBit, DL, MVT::i32));
7640     return DCI.CombineTo(N, Lo, NewHi);
7641   }
7642   case RISCVISD::SLLW:
7643   case RISCVISD::SRAW:
7644   case RISCVISD::SRLW:
7645   case RISCVISD::ROLW:
7646   case RISCVISD::RORW: {
7647     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7648     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7649         SimplifyDemandedLowBitsHelper(1, 5))
7650       return SDValue(N, 0);
7651     break;
7652   }
7653   case RISCVISD::CLZW:
7654   case RISCVISD::CTZW: {
7655     // Only the lower 32 bits of the first operand are read
7656     if (SimplifyDemandedLowBitsHelper(0, 32))
7657       return SDValue(N, 0);
7658     break;
7659   }
7660   case RISCVISD::GREV:
7661   case RISCVISD::GORC: {
7662     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
7663     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7664     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7665     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
7666       return SDValue(N, 0);
7667 
7668     return combineGREVI_GORCI(N, DAG);
7669   }
7670   case RISCVISD::GREVW:
7671   case RISCVISD::GORCW: {
7672     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
7673     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7674         SimplifyDemandedLowBitsHelper(1, 5))
7675       return SDValue(N, 0);
7676 
7677     return combineGREVI_GORCI(N, DAG);
7678   }
7679   case RISCVISD::SHFL:
7680   case RISCVISD::UNSHFL: {
7681     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
7682     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
7683     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
7684     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
7685       return SDValue(N, 0);
7686 
7687     break;
7688   }
7689   case RISCVISD::SHFLW:
7690   case RISCVISD::UNSHFLW: {
7691     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
7692     SDValue LHS = N->getOperand(0);
7693     SDValue RHS = N->getOperand(1);
7694     APInt LHSMask = APInt::getLowBitsSet(LHS.getValueSizeInBits(), 32);
7695     APInt RHSMask = APInt::getLowBitsSet(RHS.getValueSizeInBits(), 4);
7696     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7697         SimplifyDemandedLowBitsHelper(1, 4))
7698       return SDValue(N, 0);
7699 
7700     break;
7701   }
7702   case RISCVISD::BCOMPRESSW:
7703   case RISCVISD::BDECOMPRESSW: {
7704     // Only the lower 32 bits of LHS and RHS are read.
7705     if (SimplifyDemandedLowBitsHelper(0, 32) ||
7706         SimplifyDemandedLowBitsHelper(1, 32))
7707       return SDValue(N, 0);
7708 
7709     break;
7710   }
7711   case RISCVISD::FMV_X_ANYEXTH:
7712   case RISCVISD::FMV_X_ANYEXTW_RV64: {
7713     SDLoc DL(N);
7714     SDValue Op0 = N->getOperand(0);
7715     MVT VT = N->getSimpleValueType(0);
7716     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
7717     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
7718     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
7719     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
7720          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
7721         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7722          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
7723       assert(Op0.getOperand(0).getValueType() == VT &&
7724              "Unexpected value type!");
7725       return Op0.getOperand(0);
7726     }
7727 
7728     // This is a target-specific version of a DAGCombine performed in
7729     // DAGCombiner::visitBITCAST. It performs the equivalent of:
7730     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7731     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7732     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
7733         !Op0.getNode()->hasOneUse())
7734       break;
7735     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
7736     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
7737     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
7738     if (Op0.getOpcode() == ISD::FNEG)
7739       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
7740                          DAG.getConstant(SignBit, DL, VT));
7741 
7742     assert(Op0.getOpcode() == ISD::FABS);
7743     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
7744                        DAG.getConstant(~SignBit, DL, VT));
7745   }
7746   case ISD::ADD:
7747     return performADDCombine(N, DAG, Subtarget);
7748   case ISD::SUB:
7749     return performSUBCombine(N, DAG);
7750   case ISD::AND:
7751     return performANDCombine(N, DAG);
7752   case ISD::OR:
7753     return performORCombine(N, DAG, Subtarget);
7754   case ISD::XOR:
7755     return performXORCombine(N, DAG);
7756   case ISD::ANY_EXTEND:
7757     return performANY_EXTENDCombine(N, DCI, Subtarget);
7758   case ISD::ZERO_EXTEND:
7759     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
7760     // type legalization. This is safe because fp_to_uint produces poison if
7761     // it overflows.
7762     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
7763       SDValue Src = N->getOperand(0);
7764       if (Src.getOpcode() == ISD::FP_TO_UINT &&
7765           isTypeLegal(Src.getOperand(0).getValueType()))
7766         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
7767                            Src.getOperand(0));
7768       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
7769           isTypeLegal(Src.getOperand(1).getValueType())) {
7770         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
7771         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
7772                                   Src.getOperand(0), Src.getOperand(1));
7773         DCI.CombineTo(N, Res);
7774         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
7775         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
7776         return SDValue(N, 0); // Return N so it doesn't get rechecked.
7777       }
7778     }
7779     return SDValue();
7780   case RISCVISD::SELECT_CC: {
7781     // Transform
7782     SDValue LHS = N->getOperand(0);
7783     SDValue RHS = N->getOperand(1);
7784     SDValue TrueV = N->getOperand(3);
7785     SDValue FalseV = N->getOperand(4);
7786 
7787     // If the True and False values are the same, we don't need a select_cc.
7788     if (TrueV == FalseV)
7789       return TrueV;
7790 
7791     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
7792     if (!ISD::isIntEqualitySetCC(CCVal))
7793       break;
7794 
7795     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
7796     //      (select_cc X, Y, lt, trueV, falseV)
7797     // Sometimes the setcc is introduced after select_cc has been formed.
7798     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7799         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7800       // If we're looking for eq 0 instead of ne 0, we need to invert the
7801       // condition.
7802       bool Invert = CCVal == ISD::SETEQ;
7803       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7804       if (Invert)
7805         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7806 
7807       SDLoc DL(N);
7808       RHS = LHS.getOperand(1);
7809       LHS = LHS.getOperand(0);
7810       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7811 
7812       SDValue TargetCC = DAG.getCondCode(CCVal);
7813       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7814                          {LHS, RHS, TargetCC, TrueV, FalseV});
7815     }
7816 
7817     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
7818     //      (select_cc X, Y, eq/ne, trueV, falseV)
7819     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7820       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
7821                          {LHS.getOperand(0), LHS.getOperand(1),
7822                           N->getOperand(2), TrueV, FalseV});
7823     // (select_cc X, 1, setne, trueV, falseV) ->
7824     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
7825     // This can occur when legalizing some floating point comparisons.
7826     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7827     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7828       SDLoc DL(N);
7829       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7830       SDValue TargetCC = DAG.getCondCode(CCVal);
7831       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7832       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
7833                          {LHS, RHS, TargetCC, TrueV, FalseV});
7834     }
7835 
7836     break;
7837   }
7838   case RISCVISD::BR_CC: {
7839     SDValue LHS = N->getOperand(1);
7840     SDValue RHS = N->getOperand(2);
7841     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
7842     if (!ISD::isIntEqualitySetCC(CCVal))
7843       break;
7844 
7845     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
7846     //      (br_cc X, Y, lt, dest)
7847     // Sometimes the setcc is introduced after br_cc has been formed.
7848     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
7849         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
7850       // If we're looking for eq 0 instead of ne 0, we need to invert the
7851       // condition.
7852       bool Invert = CCVal == ISD::SETEQ;
7853       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7854       if (Invert)
7855         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7856 
7857       SDLoc DL(N);
7858       RHS = LHS.getOperand(1);
7859       LHS = LHS.getOperand(0);
7860       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
7861 
7862       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7863                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
7864                          N->getOperand(4));
7865     }
7866 
7867     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
7868     //      (br_cc X, Y, eq/ne, trueV, falseV)
7869     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
7870       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
7871                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
7872                          N->getOperand(3), N->getOperand(4));
7873 
7874     // (br_cc X, 1, setne, br_cc) ->
7875     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
7876     // This can occur when legalizing some floating point comparisons.
7877     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
7878     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
7879       SDLoc DL(N);
7880       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
7881       SDValue TargetCC = DAG.getCondCode(CCVal);
7882       RHS = DAG.getConstant(0, DL, LHS.getValueType());
7883       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
7884                          N->getOperand(0), LHS, RHS, TargetCC,
7885                          N->getOperand(4));
7886     }
7887     break;
7888   }
7889   case ISD::FP_TO_SINT:
7890   case ISD::FP_TO_UINT:
7891     return performFP_TO_INTCombine(N, DCI, Subtarget);
7892   case ISD::FP_TO_SINT_SAT:
7893   case ISD::FP_TO_UINT_SAT:
7894     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
7895   case ISD::FCOPYSIGN: {
7896     EVT VT = N->getValueType(0);
7897     if (!VT.isVector())
7898       break;
7899     // There is a form of VFSGNJ which injects the negated sign of its second
7900     // operand. Try and bubble any FNEG up after the extend/round to produce
7901     // this optimized pattern. Avoid modifying cases where FP_ROUND and
7902     // TRUNC=1.
7903     SDValue In2 = N->getOperand(1);
7904     // Avoid cases where the extend/round has multiple uses, as duplicating
7905     // those is typically more expensive than removing a fneg.
7906     if (!In2.hasOneUse())
7907       break;
7908     if (In2.getOpcode() != ISD::FP_EXTEND &&
7909         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
7910       break;
7911     In2 = In2.getOperand(0);
7912     if (In2.getOpcode() != ISD::FNEG)
7913       break;
7914     SDLoc DL(N);
7915     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
7916     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
7917                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
7918   }
7919   case ISD::MGATHER:
7920   case ISD::MSCATTER:
7921   case ISD::VP_GATHER:
7922   case ISD::VP_SCATTER: {
7923     if (!DCI.isBeforeLegalize())
7924       break;
7925     SDValue Index, ScaleOp;
7926     bool IsIndexScaled = false;
7927     bool IsIndexSigned = false;
7928     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
7929       Index = VPGSN->getIndex();
7930       ScaleOp = VPGSN->getScale();
7931       IsIndexScaled = VPGSN->isIndexScaled();
7932       IsIndexSigned = VPGSN->isIndexSigned();
7933     } else {
7934       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
7935       Index = MGSN->getIndex();
7936       ScaleOp = MGSN->getScale();
7937       IsIndexScaled = MGSN->isIndexScaled();
7938       IsIndexSigned = MGSN->isIndexSigned();
7939     }
7940     EVT IndexVT = Index.getValueType();
7941     MVT XLenVT = Subtarget.getXLenVT();
7942     // RISCV indexed loads only support the "unsigned unscaled" addressing
7943     // mode, so anything else must be manually legalized.
7944     bool NeedsIdxLegalization =
7945         IsIndexScaled ||
7946         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
7947     if (!NeedsIdxLegalization)
7948       break;
7949 
7950     SDLoc DL(N);
7951 
7952     // Any index legalization should first promote to XLenVT, so we don't lose
7953     // bits when scaling. This may create an illegal index type so we let
7954     // LLVM's legalization take care of the splitting.
7955     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
7956     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
7957       IndexVT = IndexVT.changeVectorElementType(XLenVT);
7958       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
7959                           DL, IndexVT, Index);
7960     }
7961 
7962     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
7963     if (IsIndexScaled && Scale != 1) {
7964       // Manually scale the indices by the element size.
7965       // TODO: Sanitize the scale operand here?
7966       // TODO: For VP nodes, should we use VP_SHL here?
7967       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
7968       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
7969       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
7970     }
7971 
7972     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
7973     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
7974       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
7975                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
7976                               VPGN->getScale(), VPGN->getMask(),
7977                               VPGN->getVectorLength()},
7978                              VPGN->getMemOperand(), NewIndexTy);
7979     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
7980       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
7981                               {VPSN->getChain(), VPSN->getValue(),
7982                                VPSN->getBasePtr(), Index, VPSN->getScale(),
7983                                VPSN->getMask(), VPSN->getVectorLength()},
7984                               VPSN->getMemOperand(), NewIndexTy);
7985     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
7986       return DAG.getMaskedGather(
7987           N->getVTList(), MGN->getMemoryVT(), DL,
7988           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
7989            MGN->getBasePtr(), Index, MGN->getScale()},
7990           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
7991     const auto *MSN = cast<MaskedScatterSDNode>(N);
7992     return DAG.getMaskedScatter(
7993         N->getVTList(), MSN->getMemoryVT(), DL,
7994         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
7995          Index, MSN->getScale()},
7996         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
7997   }
7998   case RISCVISD::SRA_VL:
7999   case RISCVISD::SRL_VL:
8000   case RISCVISD::SHL_VL: {
8001     SDValue ShAmt = N->getOperand(1);
8002     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8003       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8004       SDLoc DL(N);
8005       SDValue VL = N->getOperand(3);
8006       EVT VT = N->getValueType(0);
8007       ShAmt =
8008           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, ShAmt.getOperand(0), VL);
8009       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8010                          N->getOperand(2), N->getOperand(3));
8011     }
8012     break;
8013   }
8014   case ISD::SRA:
8015   case ISD::SRL:
8016   case ISD::SHL: {
8017     SDValue ShAmt = N->getOperand(1);
8018     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8019       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8020       SDLoc DL(N);
8021       EVT VT = N->getValueType(0);
8022       ShAmt =
8023           DAG.getNode(RISCVISD::SPLAT_VECTOR_I64, DL, VT, ShAmt.getOperand(0));
8024       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8025     }
8026     break;
8027   }
8028   case RISCVISD::MUL_VL:
8029     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8030       return V;
8031     // Mul is commutative.
8032     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8033   case ISD::STORE: {
8034     auto *Store = cast<StoreSDNode>(N);
8035     SDValue Val = Store->getValue();
8036     // Combine store of vmv.x.s to vse with VL of 1.
8037     // FIXME: Support FP.
8038     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8039       SDValue Src = Val.getOperand(0);
8040       EVT VecVT = Src.getValueType();
8041       EVT MemVT = Store->getMemoryVT();
8042       // The memory VT and the element type must match.
8043       if (VecVT.getVectorElementType() == MemVT) {
8044         SDLoc DL(N);
8045         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8046         return DAG.getStoreVP(
8047             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8048             DAG.getConstant(1, DL, MaskVT),
8049             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8050             Store->getMemOperand(), Store->getAddressingMode(),
8051             Store->isTruncatingStore(), /*IsCompress*/ false);
8052       }
8053     }
8054 
8055     break;
8056   }
8057   }
8058 
8059   return SDValue();
8060 }
8061 
8062 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8063     const SDNode *N, CombineLevel Level) const {
8064   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8065   // materialised in fewer instructions than `(OP _, c1)`:
8066   //
8067   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8068   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8069   SDValue N0 = N->getOperand(0);
8070   EVT Ty = N0.getValueType();
8071   if (Ty.isScalarInteger() &&
8072       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8073     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8074     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8075     if (C1 && C2) {
8076       const APInt &C1Int = C1->getAPIntValue();
8077       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8078 
8079       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8080       // and the combine should happen, to potentially allow further combines
8081       // later.
8082       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8083           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8084         return true;
8085 
8086       // We can materialise `c1` in an add immediate, so it's "free", and the
8087       // combine should be prevented.
8088       if (C1Int.getMinSignedBits() <= 64 &&
8089           isLegalAddImmediate(C1Int.getSExtValue()))
8090         return false;
8091 
8092       // Neither constant will fit into an immediate, so find materialisation
8093       // costs.
8094       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8095                                               Subtarget.getFeatureBits(),
8096                                               /*CompressionCost*/true);
8097       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8098           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8099           /*CompressionCost*/true);
8100 
8101       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8102       // combine should be prevented.
8103       if (C1Cost < ShiftedC1Cost)
8104         return false;
8105     }
8106   }
8107   return true;
8108 }
8109 
8110 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8111     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8112     TargetLoweringOpt &TLO) const {
8113   // Delay this optimization as late as possible.
8114   if (!TLO.LegalOps)
8115     return false;
8116 
8117   EVT VT = Op.getValueType();
8118   if (VT.isVector())
8119     return false;
8120 
8121   // Only handle AND for now.
8122   if (Op.getOpcode() != ISD::AND)
8123     return false;
8124 
8125   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8126   if (!C)
8127     return false;
8128 
8129   const APInt &Mask = C->getAPIntValue();
8130 
8131   // Clear all non-demanded bits initially.
8132   APInt ShrunkMask = Mask & DemandedBits;
8133 
8134   // Try to make a smaller immediate by setting undemanded bits.
8135 
8136   APInt ExpandedMask = Mask | ~DemandedBits;
8137 
8138   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8139     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8140   };
8141   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8142     if (NewMask == Mask)
8143       return true;
8144     SDLoc DL(Op);
8145     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8146     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8147     return TLO.CombineTo(Op, NewOp);
8148   };
8149 
8150   // If the shrunk mask fits in sign extended 12 bits, let the target
8151   // independent code apply it.
8152   if (ShrunkMask.isSignedIntN(12))
8153     return false;
8154 
8155   // Preserve (and X, 0xffff) when zext.h is supported.
8156   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8157     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8158     if (IsLegalMask(NewMask))
8159       return UseMask(NewMask);
8160   }
8161 
8162   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8163   if (VT == MVT::i64) {
8164     APInt NewMask = APInt(64, 0xffffffff);
8165     if (IsLegalMask(NewMask))
8166       return UseMask(NewMask);
8167   }
8168 
8169   // For the remaining optimizations, we need to be able to make a negative
8170   // number through a combination of mask and undemanded bits.
8171   if (!ExpandedMask.isNegative())
8172     return false;
8173 
8174   // What is the fewest number of bits we need to represent the negative number.
8175   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8176 
8177   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8178   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8179   APInt NewMask = ShrunkMask;
8180   if (MinSignedBits <= 12)
8181     NewMask.setBitsFrom(11);
8182   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8183     NewMask.setBitsFrom(31);
8184   else
8185     return false;
8186 
8187   // Check that our new mask is a subset of the demanded mask.
8188   assert(IsLegalMask(NewMask));
8189   return UseMask(NewMask);
8190 }
8191 
8192 static void computeGREV(APInt &Src, unsigned ShAmt) {
8193   ShAmt &= Src.getBitWidth() - 1;
8194   uint64_t x = Src.getZExtValue();
8195   if (ShAmt & 1)
8196     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
8197   if (ShAmt & 2)
8198     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
8199   if (ShAmt & 4)
8200     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
8201   if (ShAmt & 8)
8202     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
8203   if (ShAmt & 16)
8204     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
8205   if (ShAmt & 32)
8206     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
8207   Src = x;
8208 }
8209 
8210 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8211                                                         KnownBits &Known,
8212                                                         const APInt &DemandedElts,
8213                                                         const SelectionDAG &DAG,
8214                                                         unsigned Depth) const {
8215   unsigned BitWidth = Known.getBitWidth();
8216   unsigned Opc = Op.getOpcode();
8217   assert((Opc >= ISD::BUILTIN_OP_END ||
8218           Opc == ISD::INTRINSIC_WO_CHAIN ||
8219           Opc == ISD::INTRINSIC_W_CHAIN ||
8220           Opc == ISD::INTRINSIC_VOID) &&
8221          "Should use MaskedValueIsZero if you don't know whether Op"
8222          " is a target node!");
8223 
8224   Known.resetAll();
8225   switch (Opc) {
8226   default: break;
8227   case RISCVISD::SELECT_CC: {
8228     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
8229     // If we don't know any bits, early out.
8230     if (Known.isUnknown())
8231       break;
8232     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
8233 
8234     // Only known if known in both the LHS and RHS.
8235     Known = KnownBits::commonBits(Known, Known2);
8236     break;
8237   }
8238   case RISCVISD::REMUW: {
8239     KnownBits Known2;
8240     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8241     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8242     // We only care about the lower 32 bits.
8243     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
8244     // Restore the original width by sign extending.
8245     Known = Known.sext(BitWidth);
8246     break;
8247   }
8248   case RISCVISD::DIVUW: {
8249     KnownBits Known2;
8250     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8251     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8252     // We only care about the lower 32 bits.
8253     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
8254     // Restore the original width by sign extending.
8255     Known = Known.sext(BitWidth);
8256     break;
8257   }
8258   case RISCVISD::CTZW: {
8259     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8260     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
8261     unsigned LowBits = Log2_32(PossibleTZ) + 1;
8262     Known.Zero.setBitsFrom(LowBits);
8263     break;
8264   }
8265   case RISCVISD::CLZW: {
8266     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8267     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
8268     unsigned LowBits = Log2_32(PossibleLZ) + 1;
8269     Known.Zero.setBitsFrom(LowBits);
8270     break;
8271   }
8272   case RISCVISD::GREV:
8273   case RISCVISD::GREVW: {
8274     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8275       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8276       if (Opc == RISCVISD::GREVW)
8277         Known = Known.trunc(32);
8278       unsigned ShAmt = C->getZExtValue();
8279       computeGREV(Known.Zero, ShAmt);
8280       computeGREV(Known.One, ShAmt);
8281       if (Opc == RISCVISD::GREVW)
8282         Known = Known.sext(BitWidth);
8283     }
8284     break;
8285   }
8286   case RISCVISD::READ_VLENB: {
8287     // If we know the minimum VLen from Zvl extensions, we can use that to
8288     // determine the trailing zeros of VLENB.
8289     // FIXME: Limit to 128 bit vectors until we have more testing.
8290     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
8291     if (MinVLenB > 0)
8292       Known.Zero.setLowBits(Log2_32(MinVLenB));
8293     // We assume VLENB is no more than 65536 / 8 bytes.
8294     Known.Zero.setBitsFrom(14);
8295     break;
8296   }
8297   case ISD::INTRINSIC_W_CHAIN:
8298   case ISD::INTRINSIC_WO_CHAIN: {
8299     unsigned IntNo =
8300         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
8301     switch (IntNo) {
8302     default:
8303       // We can't do anything for most intrinsics.
8304       break;
8305     case Intrinsic::riscv_vsetvli:
8306     case Intrinsic::riscv_vsetvlimax:
8307     case Intrinsic::riscv_vsetvli_opt:
8308     case Intrinsic::riscv_vsetvlimax_opt:
8309       // Assume that VL output is positive and would fit in an int32_t.
8310       // TODO: VLEN might be capped at 16 bits in a future V spec update.
8311       if (BitWidth >= 32)
8312         Known.Zero.setBitsFrom(31);
8313       break;
8314     }
8315     break;
8316   }
8317   }
8318 }
8319 
8320 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
8321     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
8322     unsigned Depth) const {
8323   switch (Op.getOpcode()) {
8324   default:
8325     break;
8326   case RISCVISD::SELECT_CC: {
8327     unsigned Tmp =
8328         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
8329     if (Tmp == 1) return 1;  // Early out.
8330     unsigned Tmp2 =
8331         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
8332     return std::min(Tmp, Tmp2);
8333   }
8334   case RISCVISD::SLLW:
8335   case RISCVISD::SRAW:
8336   case RISCVISD::SRLW:
8337   case RISCVISD::DIVW:
8338   case RISCVISD::DIVUW:
8339   case RISCVISD::REMUW:
8340   case RISCVISD::ROLW:
8341   case RISCVISD::RORW:
8342   case RISCVISD::GREVW:
8343   case RISCVISD::GORCW:
8344   case RISCVISD::FSLW:
8345   case RISCVISD::FSRW:
8346   case RISCVISD::SHFLW:
8347   case RISCVISD::UNSHFLW:
8348   case RISCVISD::BCOMPRESSW:
8349   case RISCVISD::BDECOMPRESSW:
8350   case RISCVISD::BFPW:
8351   case RISCVISD::FCVT_W_RV64:
8352   case RISCVISD::FCVT_WU_RV64:
8353   case RISCVISD::STRICT_FCVT_W_RV64:
8354   case RISCVISD::STRICT_FCVT_WU_RV64:
8355     // TODO: As the result is sign-extended, this is conservatively correct. A
8356     // more precise answer could be calculated for SRAW depending on known
8357     // bits in the shift amount.
8358     return 33;
8359   case RISCVISD::SHFL:
8360   case RISCVISD::UNSHFL: {
8361     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
8362     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
8363     // will stay within the upper 32 bits. If there were more than 32 sign bits
8364     // before there will be at least 33 sign bits after.
8365     if (Op.getValueType() == MVT::i64 &&
8366         isa<ConstantSDNode>(Op.getOperand(1)) &&
8367         (Op.getConstantOperandVal(1) & 0x10) == 0) {
8368       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
8369       if (Tmp > 32)
8370         return 33;
8371     }
8372     break;
8373   }
8374   case RISCVISD::VMV_X_S: {
8375     // The number of sign bits of the scalar result is computed by obtaining the
8376     // element type of the input vector operand, subtracting its width from the
8377     // XLEN, and then adding one (sign bit within the element type). If the
8378     // element type is wider than XLen, the least-significant XLEN bits are
8379     // taken.
8380     unsigned XLen = Subtarget.getXLen();
8381     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
8382     if (EltBits <= XLen)
8383       return XLen - EltBits + 1;
8384     break;
8385   }
8386   }
8387 
8388   return 1;
8389 }
8390 
8391 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
8392                                                   MachineBasicBlock *BB) {
8393   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
8394 
8395   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
8396   // Should the count have wrapped while it was being read, we need to try
8397   // again.
8398   // ...
8399   // read:
8400   // rdcycleh x3 # load high word of cycle
8401   // rdcycle  x2 # load low word of cycle
8402   // rdcycleh x4 # load high word of cycle
8403   // bne x3, x4, read # check if high word reads match, otherwise try again
8404   // ...
8405 
8406   MachineFunction &MF = *BB->getParent();
8407   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8408   MachineFunction::iterator It = ++BB->getIterator();
8409 
8410   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8411   MF.insert(It, LoopMBB);
8412 
8413   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8414   MF.insert(It, DoneMBB);
8415 
8416   // Transfer the remainder of BB and its successor edges to DoneMBB.
8417   DoneMBB->splice(DoneMBB->begin(), BB,
8418                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8419   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
8420 
8421   BB->addSuccessor(LoopMBB);
8422 
8423   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8424   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
8425   Register LoReg = MI.getOperand(0).getReg();
8426   Register HiReg = MI.getOperand(1).getReg();
8427   DebugLoc DL = MI.getDebugLoc();
8428 
8429   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
8430   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
8431       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8432       .addReg(RISCV::X0);
8433   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
8434       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
8435       .addReg(RISCV::X0);
8436   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
8437       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
8438       .addReg(RISCV::X0);
8439 
8440   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
8441       .addReg(HiReg)
8442       .addReg(ReadAgainReg)
8443       .addMBB(LoopMBB);
8444 
8445   LoopMBB->addSuccessor(LoopMBB);
8446   LoopMBB->addSuccessor(DoneMBB);
8447 
8448   MI.eraseFromParent();
8449 
8450   return DoneMBB;
8451 }
8452 
8453 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
8454                                              MachineBasicBlock *BB) {
8455   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
8456 
8457   MachineFunction &MF = *BB->getParent();
8458   DebugLoc DL = MI.getDebugLoc();
8459   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8460   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8461   Register LoReg = MI.getOperand(0).getReg();
8462   Register HiReg = MI.getOperand(1).getReg();
8463   Register SrcReg = MI.getOperand(2).getReg();
8464   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
8465   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8466 
8467   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
8468                           RI);
8469   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8470   MachineMemOperand *MMOLo =
8471       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
8472   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8473       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
8474   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
8475       .addFrameIndex(FI)
8476       .addImm(0)
8477       .addMemOperand(MMOLo);
8478   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
8479       .addFrameIndex(FI)
8480       .addImm(4)
8481       .addMemOperand(MMOHi);
8482   MI.eraseFromParent(); // The pseudo instruction is gone now.
8483   return BB;
8484 }
8485 
8486 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
8487                                                  MachineBasicBlock *BB) {
8488   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
8489          "Unexpected instruction");
8490 
8491   MachineFunction &MF = *BB->getParent();
8492   DebugLoc DL = MI.getDebugLoc();
8493   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
8494   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
8495   Register DstReg = MI.getOperand(0).getReg();
8496   Register LoReg = MI.getOperand(1).getReg();
8497   Register HiReg = MI.getOperand(2).getReg();
8498   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
8499   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
8500 
8501   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
8502   MachineMemOperand *MMOLo =
8503       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
8504   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
8505       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
8506   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8507       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
8508       .addFrameIndex(FI)
8509       .addImm(0)
8510       .addMemOperand(MMOLo);
8511   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
8512       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
8513       .addFrameIndex(FI)
8514       .addImm(4)
8515       .addMemOperand(MMOHi);
8516   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
8517   MI.eraseFromParent(); // The pseudo instruction is gone now.
8518   return BB;
8519 }
8520 
8521 static bool isSelectPseudo(MachineInstr &MI) {
8522   switch (MI.getOpcode()) {
8523   default:
8524     return false;
8525   case RISCV::Select_GPR_Using_CC_GPR:
8526   case RISCV::Select_FPR16_Using_CC_GPR:
8527   case RISCV::Select_FPR32_Using_CC_GPR:
8528   case RISCV::Select_FPR64_Using_CC_GPR:
8529     return true;
8530   }
8531 }
8532 
8533 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
8534                                         unsigned RelOpcode, unsigned EqOpcode,
8535                                         const RISCVSubtarget &Subtarget) {
8536   DebugLoc DL = MI.getDebugLoc();
8537   Register DstReg = MI.getOperand(0).getReg();
8538   Register Src1Reg = MI.getOperand(1).getReg();
8539   Register Src2Reg = MI.getOperand(2).getReg();
8540   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
8541   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
8542   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
8543 
8544   // Save the current FFLAGS.
8545   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
8546 
8547   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
8548                  .addReg(Src1Reg)
8549                  .addReg(Src2Reg);
8550   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8551     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
8552 
8553   // Restore the FFLAGS.
8554   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
8555       .addReg(SavedFFlags, RegState::Kill);
8556 
8557   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
8558   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
8559                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
8560                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
8561   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
8562     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
8563 
8564   // Erase the pseudoinstruction.
8565   MI.eraseFromParent();
8566   return BB;
8567 }
8568 
8569 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
8570                                            MachineBasicBlock *BB,
8571                                            const RISCVSubtarget &Subtarget) {
8572   // To "insert" Select_* instructions, we actually have to insert the triangle
8573   // control-flow pattern.  The incoming instructions know the destination vreg
8574   // to set, the condition code register to branch on, the true/false values to
8575   // select between, and the condcode to use to select the appropriate branch.
8576   //
8577   // We produce the following control flow:
8578   //     HeadMBB
8579   //     |  \
8580   //     |  IfFalseMBB
8581   //     | /
8582   //    TailMBB
8583   //
8584   // When we find a sequence of selects we attempt to optimize their emission
8585   // by sharing the control flow. Currently we only handle cases where we have
8586   // multiple selects with the exact same condition (same LHS, RHS and CC).
8587   // The selects may be interleaved with other instructions if the other
8588   // instructions meet some requirements we deem safe:
8589   // - They are debug instructions. Otherwise,
8590   // - They do not have side-effects, do not access memory and their inputs do
8591   //   not depend on the results of the select pseudo-instructions.
8592   // The TrueV/FalseV operands of the selects cannot depend on the result of
8593   // previous selects in the sequence.
8594   // These conditions could be further relaxed. See the X86 target for a
8595   // related approach and more information.
8596   Register LHS = MI.getOperand(1).getReg();
8597   Register RHS = MI.getOperand(2).getReg();
8598   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
8599 
8600   SmallVector<MachineInstr *, 4> SelectDebugValues;
8601   SmallSet<Register, 4> SelectDests;
8602   SelectDests.insert(MI.getOperand(0).getReg());
8603 
8604   MachineInstr *LastSelectPseudo = &MI;
8605 
8606   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
8607        SequenceMBBI != E; ++SequenceMBBI) {
8608     if (SequenceMBBI->isDebugInstr())
8609       continue;
8610     else if (isSelectPseudo(*SequenceMBBI)) {
8611       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
8612           SequenceMBBI->getOperand(2).getReg() != RHS ||
8613           SequenceMBBI->getOperand(3).getImm() != CC ||
8614           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
8615           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
8616         break;
8617       LastSelectPseudo = &*SequenceMBBI;
8618       SequenceMBBI->collectDebugValues(SelectDebugValues);
8619       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
8620     } else {
8621       if (SequenceMBBI->hasUnmodeledSideEffects() ||
8622           SequenceMBBI->mayLoadOrStore())
8623         break;
8624       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
8625             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
8626           }))
8627         break;
8628     }
8629   }
8630 
8631   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
8632   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8633   DebugLoc DL = MI.getDebugLoc();
8634   MachineFunction::iterator I = ++BB->getIterator();
8635 
8636   MachineBasicBlock *HeadMBB = BB;
8637   MachineFunction *F = BB->getParent();
8638   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
8639   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
8640 
8641   F->insert(I, IfFalseMBB);
8642   F->insert(I, TailMBB);
8643 
8644   // Transfer debug instructions associated with the selects to TailMBB.
8645   for (MachineInstr *DebugInstr : SelectDebugValues) {
8646     TailMBB->push_back(DebugInstr->removeFromParent());
8647   }
8648 
8649   // Move all instructions after the sequence to TailMBB.
8650   TailMBB->splice(TailMBB->end(), HeadMBB,
8651                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
8652   // Update machine-CFG edges by transferring all successors of the current
8653   // block to the new block which will contain the Phi nodes for the selects.
8654   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
8655   // Set the successors for HeadMBB.
8656   HeadMBB->addSuccessor(IfFalseMBB);
8657   HeadMBB->addSuccessor(TailMBB);
8658 
8659   // Insert appropriate branch.
8660   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
8661     .addReg(LHS)
8662     .addReg(RHS)
8663     .addMBB(TailMBB);
8664 
8665   // IfFalseMBB just falls through to TailMBB.
8666   IfFalseMBB->addSuccessor(TailMBB);
8667 
8668   // Create PHIs for all of the select pseudo-instructions.
8669   auto SelectMBBI = MI.getIterator();
8670   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
8671   auto InsertionPoint = TailMBB->begin();
8672   while (SelectMBBI != SelectEnd) {
8673     auto Next = std::next(SelectMBBI);
8674     if (isSelectPseudo(*SelectMBBI)) {
8675       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
8676       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
8677               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
8678           .addReg(SelectMBBI->getOperand(4).getReg())
8679           .addMBB(HeadMBB)
8680           .addReg(SelectMBBI->getOperand(5).getReg())
8681           .addMBB(IfFalseMBB);
8682       SelectMBBI->eraseFromParent();
8683     }
8684     SelectMBBI = Next;
8685   }
8686 
8687   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
8688   return TailMBB;
8689 }
8690 
8691 MachineBasicBlock *
8692 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8693                                                  MachineBasicBlock *BB) const {
8694   switch (MI.getOpcode()) {
8695   default:
8696     llvm_unreachable("Unexpected instr type to insert");
8697   case RISCV::ReadCycleWide:
8698     assert(!Subtarget.is64Bit() &&
8699            "ReadCycleWrite is only to be used on riscv32");
8700     return emitReadCycleWidePseudo(MI, BB);
8701   case RISCV::Select_GPR_Using_CC_GPR:
8702   case RISCV::Select_FPR16_Using_CC_GPR:
8703   case RISCV::Select_FPR32_Using_CC_GPR:
8704   case RISCV::Select_FPR64_Using_CC_GPR:
8705     return emitSelectPseudo(MI, BB, Subtarget);
8706   case RISCV::BuildPairF64Pseudo:
8707     return emitBuildPairF64Pseudo(MI, BB);
8708   case RISCV::SplitF64Pseudo:
8709     return emitSplitF64Pseudo(MI, BB);
8710   case RISCV::PseudoQuietFLE_H:
8711     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
8712   case RISCV::PseudoQuietFLT_H:
8713     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
8714   case RISCV::PseudoQuietFLE_S:
8715     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
8716   case RISCV::PseudoQuietFLT_S:
8717     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
8718   case RISCV::PseudoQuietFLE_D:
8719     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
8720   case RISCV::PseudoQuietFLT_D:
8721     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
8722   }
8723 }
8724 
8725 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8726                                                         SDNode *Node) const {
8727   // Add FRM dependency to any instructions with dynamic rounding mode.
8728   unsigned Opc = MI.getOpcode();
8729   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
8730   if (Idx < 0)
8731     return;
8732   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
8733     return;
8734   // If the instruction already reads FRM, don't add another read.
8735   if (MI.readsRegister(RISCV::FRM))
8736     return;
8737   MI.addOperand(
8738       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
8739 }
8740 
8741 // Calling Convention Implementation.
8742 // The expectations for frontend ABI lowering vary from target to target.
8743 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
8744 // details, but this is a longer term goal. For now, we simply try to keep the
8745 // role of the frontend as simple and well-defined as possible. The rules can
8746 // be summarised as:
8747 // * Never split up large scalar arguments. We handle them here.
8748 // * If a hardfloat calling convention is being used, and the struct may be
8749 // passed in a pair of registers (fp+fp, int+fp), and both registers are
8750 // available, then pass as two separate arguments. If either the GPRs or FPRs
8751 // are exhausted, then pass according to the rule below.
8752 // * If a struct could never be passed in registers or directly in a stack
8753 // slot (as it is larger than 2*XLEN and the floating point rules don't
8754 // apply), then pass it using a pointer with the byval attribute.
8755 // * If a struct is less than 2*XLEN, then coerce to either a two-element
8756 // word-sized array or a 2*XLEN scalar (depending on alignment).
8757 // * The frontend can determine whether a struct is returned by reference or
8758 // not based on its size and fields. If it will be returned by reference, the
8759 // frontend must modify the prototype so a pointer with the sret annotation is
8760 // passed as the first argument. This is not necessary for large scalar
8761 // returns.
8762 // * Struct return values and varargs should be coerced to structs containing
8763 // register-size fields in the same situations they would be for fixed
8764 // arguments.
8765 
8766 static const MCPhysReg ArgGPRs[] = {
8767   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
8768   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
8769 };
8770 static const MCPhysReg ArgFPR16s[] = {
8771   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
8772   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
8773 };
8774 static const MCPhysReg ArgFPR32s[] = {
8775   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
8776   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
8777 };
8778 static const MCPhysReg ArgFPR64s[] = {
8779   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
8780   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
8781 };
8782 // This is an interim calling convention and it may be changed in the future.
8783 static const MCPhysReg ArgVRs[] = {
8784     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
8785     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
8786     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
8787 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
8788                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
8789                                      RISCV::V20M2, RISCV::V22M2};
8790 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
8791                                      RISCV::V20M4};
8792 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
8793 
8794 // Pass a 2*XLEN argument that has been split into two XLEN values through
8795 // registers or the stack as necessary.
8796 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
8797                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
8798                                 MVT ValVT2, MVT LocVT2,
8799                                 ISD::ArgFlagsTy ArgFlags2) {
8800   unsigned XLenInBytes = XLen / 8;
8801   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8802     // At least one half can be passed via register.
8803     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
8804                                      VA1.getLocVT(), CCValAssign::Full));
8805   } else {
8806     // Both halves must be passed on the stack, with proper alignment.
8807     Align StackAlign =
8808         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
8809     State.addLoc(
8810         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
8811                             State.AllocateStack(XLenInBytes, StackAlign),
8812                             VA1.getLocVT(), CCValAssign::Full));
8813     State.addLoc(CCValAssign::getMem(
8814         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8815         LocVT2, CCValAssign::Full));
8816     return false;
8817   }
8818 
8819   if (Register Reg = State.AllocateReg(ArgGPRs)) {
8820     // The second half can also be passed via register.
8821     State.addLoc(
8822         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
8823   } else {
8824     // The second half is passed via the stack, without additional alignment.
8825     State.addLoc(CCValAssign::getMem(
8826         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
8827         LocVT2, CCValAssign::Full));
8828   }
8829 
8830   return false;
8831 }
8832 
8833 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
8834                                Optional<unsigned> FirstMaskArgument,
8835                                CCState &State, const RISCVTargetLowering &TLI) {
8836   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
8837   if (RC == &RISCV::VRRegClass) {
8838     // Assign the first mask argument to V0.
8839     // This is an interim calling convention and it may be changed in the
8840     // future.
8841     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
8842       return State.AllocateReg(RISCV::V0);
8843     return State.AllocateReg(ArgVRs);
8844   }
8845   if (RC == &RISCV::VRM2RegClass)
8846     return State.AllocateReg(ArgVRM2s);
8847   if (RC == &RISCV::VRM4RegClass)
8848     return State.AllocateReg(ArgVRM4s);
8849   if (RC == &RISCV::VRM8RegClass)
8850     return State.AllocateReg(ArgVRM8s);
8851   llvm_unreachable("Unhandled register class for ValueType");
8852 }
8853 
8854 // Implements the RISC-V calling convention. Returns true upon failure.
8855 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
8856                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
8857                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
8858                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
8859                      Optional<unsigned> FirstMaskArgument) {
8860   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
8861   assert(XLen == 32 || XLen == 64);
8862   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
8863 
8864   // Any return value split in to more than two values can't be returned
8865   // directly. Vectors are returned via the available vector registers.
8866   if (!LocVT.isVector() && IsRet && ValNo > 1)
8867     return true;
8868 
8869   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
8870   // variadic argument, or if no F16/F32 argument registers are available.
8871   bool UseGPRForF16_F32 = true;
8872   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
8873   // variadic argument, or if no F64 argument registers are available.
8874   bool UseGPRForF64 = true;
8875 
8876   switch (ABI) {
8877   default:
8878     llvm_unreachable("Unexpected ABI");
8879   case RISCVABI::ABI_ILP32:
8880   case RISCVABI::ABI_LP64:
8881     break;
8882   case RISCVABI::ABI_ILP32F:
8883   case RISCVABI::ABI_LP64F:
8884     UseGPRForF16_F32 = !IsFixed;
8885     break;
8886   case RISCVABI::ABI_ILP32D:
8887   case RISCVABI::ABI_LP64D:
8888     UseGPRForF16_F32 = !IsFixed;
8889     UseGPRForF64 = !IsFixed;
8890     break;
8891   }
8892 
8893   // FPR16, FPR32, and FPR64 alias each other.
8894   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
8895     UseGPRForF16_F32 = true;
8896     UseGPRForF64 = true;
8897   }
8898 
8899   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
8900   // similar local variables rather than directly checking against the target
8901   // ABI.
8902 
8903   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
8904     LocVT = XLenVT;
8905     LocInfo = CCValAssign::BCvt;
8906   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
8907     LocVT = MVT::i64;
8908     LocInfo = CCValAssign::BCvt;
8909   }
8910 
8911   // If this is a variadic argument, the RISC-V calling convention requires
8912   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
8913   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
8914   // be used regardless of whether the original argument was split during
8915   // legalisation or not. The argument will not be passed by registers if the
8916   // original type is larger than 2*XLEN, so the register alignment rule does
8917   // not apply.
8918   unsigned TwoXLenInBytes = (2 * XLen) / 8;
8919   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
8920       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
8921     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
8922     // Skip 'odd' register if necessary.
8923     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
8924       State.AllocateReg(ArgGPRs);
8925   }
8926 
8927   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
8928   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
8929       State.getPendingArgFlags();
8930 
8931   assert(PendingLocs.size() == PendingArgFlags.size() &&
8932          "PendingLocs and PendingArgFlags out of sync");
8933 
8934   // Handle passing f64 on RV32D with a soft float ABI or when floating point
8935   // registers are exhausted.
8936   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
8937     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
8938            "Can't lower f64 if it is split");
8939     // Depending on available argument GPRS, f64 may be passed in a pair of
8940     // GPRs, split between a GPR and the stack, or passed completely on the
8941     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
8942     // cases.
8943     Register Reg = State.AllocateReg(ArgGPRs);
8944     LocVT = MVT::i32;
8945     if (!Reg) {
8946       unsigned StackOffset = State.AllocateStack(8, Align(8));
8947       State.addLoc(
8948           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
8949       return false;
8950     }
8951     if (!State.AllocateReg(ArgGPRs))
8952       State.AllocateStack(4, Align(4));
8953     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
8954     return false;
8955   }
8956 
8957   // Fixed-length vectors are located in the corresponding scalable-vector
8958   // container types.
8959   if (ValVT.isFixedLengthVector())
8960     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
8961 
8962   // Split arguments might be passed indirectly, so keep track of the pending
8963   // values. Split vectors are passed via a mix of registers and indirectly, so
8964   // treat them as we would any other argument.
8965   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
8966     LocVT = XLenVT;
8967     LocInfo = CCValAssign::Indirect;
8968     PendingLocs.push_back(
8969         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
8970     PendingArgFlags.push_back(ArgFlags);
8971     if (!ArgFlags.isSplitEnd()) {
8972       return false;
8973     }
8974   }
8975 
8976   // If the split argument only had two elements, it should be passed directly
8977   // in registers or on the stack.
8978   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
8979       PendingLocs.size() <= 2) {
8980     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
8981     // Apply the normal calling convention rules to the first half of the
8982     // split argument.
8983     CCValAssign VA = PendingLocs[0];
8984     ISD::ArgFlagsTy AF = PendingArgFlags[0];
8985     PendingLocs.clear();
8986     PendingArgFlags.clear();
8987     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
8988                                ArgFlags);
8989   }
8990 
8991   // Allocate to a register if possible, or else a stack slot.
8992   Register Reg;
8993   unsigned StoreSizeBytes = XLen / 8;
8994   Align StackAlign = Align(XLen / 8);
8995 
8996   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
8997     Reg = State.AllocateReg(ArgFPR16s);
8998   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
8999     Reg = State.AllocateReg(ArgFPR32s);
9000   else if (ValVT == MVT::f64 && !UseGPRForF64)
9001     Reg = State.AllocateReg(ArgFPR64s);
9002   else if (ValVT.isVector()) {
9003     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9004     if (!Reg) {
9005       // For return values, the vector must be passed fully via registers or
9006       // via the stack.
9007       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9008       // but we're using all of them.
9009       if (IsRet)
9010         return true;
9011       // Try using a GPR to pass the address
9012       if ((Reg = State.AllocateReg(ArgGPRs))) {
9013         LocVT = XLenVT;
9014         LocInfo = CCValAssign::Indirect;
9015       } else if (ValVT.isScalableVector()) {
9016         LocVT = XLenVT;
9017         LocInfo = CCValAssign::Indirect;
9018       } else {
9019         // Pass fixed-length vectors on the stack.
9020         LocVT = ValVT;
9021         StoreSizeBytes = ValVT.getStoreSize();
9022         // Align vectors to their element sizes, being careful for vXi1
9023         // vectors.
9024         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9025       }
9026     }
9027   } else {
9028     Reg = State.AllocateReg(ArgGPRs);
9029   }
9030 
9031   unsigned StackOffset =
9032       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9033 
9034   // If we reach this point and PendingLocs is non-empty, we must be at the
9035   // end of a split argument that must be passed indirectly.
9036   if (!PendingLocs.empty()) {
9037     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9038     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9039 
9040     for (auto &It : PendingLocs) {
9041       if (Reg)
9042         It.convertToReg(Reg);
9043       else
9044         It.convertToMem(StackOffset);
9045       State.addLoc(It);
9046     }
9047     PendingLocs.clear();
9048     PendingArgFlags.clear();
9049     return false;
9050   }
9051 
9052   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9053           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9054          "Expected an XLenVT or vector types at this stage");
9055 
9056   if (Reg) {
9057     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9058     return false;
9059   }
9060 
9061   // When a floating-point value is passed on the stack, no bit-conversion is
9062   // needed.
9063   if (ValVT.isFloatingPoint()) {
9064     LocVT = ValVT;
9065     LocInfo = CCValAssign::Full;
9066   }
9067   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9068   return false;
9069 }
9070 
9071 template <typename ArgTy>
9072 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9073   for (const auto &ArgIdx : enumerate(Args)) {
9074     MVT ArgVT = ArgIdx.value().VT;
9075     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9076       return ArgIdx.index();
9077   }
9078   return None;
9079 }
9080 
9081 void RISCVTargetLowering::analyzeInputArgs(
9082     MachineFunction &MF, CCState &CCInfo,
9083     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9084     RISCVCCAssignFn Fn) const {
9085   unsigned NumArgs = Ins.size();
9086   FunctionType *FType = MF.getFunction().getFunctionType();
9087 
9088   Optional<unsigned> FirstMaskArgument;
9089   if (Subtarget.hasVInstructions())
9090     FirstMaskArgument = preAssignMask(Ins);
9091 
9092   for (unsigned i = 0; i != NumArgs; ++i) {
9093     MVT ArgVT = Ins[i].VT;
9094     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9095 
9096     Type *ArgTy = nullptr;
9097     if (IsRet)
9098       ArgTy = FType->getReturnType();
9099     else if (Ins[i].isOrigArg())
9100       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9101 
9102     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9103     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9104            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9105            FirstMaskArgument)) {
9106       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9107                         << EVT(ArgVT).getEVTString() << '\n');
9108       llvm_unreachable(nullptr);
9109     }
9110   }
9111 }
9112 
9113 void RISCVTargetLowering::analyzeOutputArgs(
9114     MachineFunction &MF, CCState &CCInfo,
9115     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9116     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9117   unsigned NumArgs = Outs.size();
9118 
9119   Optional<unsigned> FirstMaskArgument;
9120   if (Subtarget.hasVInstructions())
9121     FirstMaskArgument = preAssignMask(Outs);
9122 
9123   for (unsigned i = 0; i != NumArgs; i++) {
9124     MVT ArgVT = Outs[i].VT;
9125     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9126     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9127 
9128     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9129     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9130            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9131            FirstMaskArgument)) {
9132       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9133                         << EVT(ArgVT).getEVTString() << "\n");
9134       llvm_unreachable(nullptr);
9135     }
9136   }
9137 }
9138 
9139 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9140 // values.
9141 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9142                                    const CCValAssign &VA, const SDLoc &DL,
9143                                    const RISCVSubtarget &Subtarget) {
9144   switch (VA.getLocInfo()) {
9145   default:
9146     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9147   case CCValAssign::Full:
9148     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9149       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9150     break;
9151   case CCValAssign::BCvt:
9152     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9153       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9154     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9155       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9156     else
9157       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9158     break;
9159   }
9160   return Val;
9161 }
9162 
9163 // The caller is responsible for loading the full value if the argument is
9164 // passed with CCValAssign::Indirect.
9165 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9166                                 const CCValAssign &VA, const SDLoc &DL,
9167                                 const RISCVTargetLowering &TLI) {
9168   MachineFunction &MF = DAG.getMachineFunction();
9169   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9170   EVT LocVT = VA.getLocVT();
9171   SDValue Val;
9172   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9173   Register VReg = RegInfo.createVirtualRegister(RC);
9174   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9175   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9176 
9177   if (VA.getLocInfo() == CCValAssign::Indirect)
9178     return Val;
9179 
9180   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9181 }
9182 
9183 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9184                                    const CCValAssign &VA, const SDLoc &DL,
9185                                    const RISCVSubtarget &Subtarget) {
9186   EVT LocVT = VA.getLocVT();
9187 
9188   switch (VA.getLocInfo()) {
9189   default:
9190     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9191   case CCValAssign::Full:
9192     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9193       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9194     break;
9195   case CCValAssign::BCvt:
9196     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9197       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
9198     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9199       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
9200     else
9201       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
9202     break;
9203   }
9204   return Val;
9205 }
9206 
9207 // The caller is responsible for loading the full value if the argument is
9208 // passed with CCValAssign::Indirect.
9209 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
9210                                 const CCValAssign &VA, const SDLoc &DL) {
9211   MachineFunction &MF = DAG.getMachineFunction();
9212   MachineFrameInfo &MFI = MF.getFrameInfo();
9213   EVT LocVT = VA.getLocVT();
9214   EVT ValVT = VA.getValVT();
9215   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
9216   if (ValVT.isScalableVector()) {
9217     // When the value is a scalable vector, we save the pointer which points to
9218     // the scalable vector value in the stack. The ValVT will be the pointer
9219     // type, instead of the scalable vector type.
9220     ValVT = LocVT;
9221   }
9222   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
9223                                  /*IsImmutable=*/true);
9224   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
9225   SDValue Val;
9226 
9227   ISD::LoadExtType ExtType;
9228   switch (VA.getLocInfo()) {
9229   default:
9230     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9231   case CCValAssign::Full:
9232   case CCValAssign::Indirect:
9233   case CCValAssign::BCvt:
9234     ExtType = ISD::NON_EXTLOAD;
9235     break;
9236   }
9237   Val = DAG.getExtLoad(
9238       ExtType, DL, LocVT, Chain, FIN,
9239       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
9240   return Val;
9241 }
9242 
9243 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
9244                                        const CCValAssign &VA, const SDLoc &DL) {
9245   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
9246          "Unexpected VA");
9247   MachineFunction &MF = DAG.getMachineFunction();
9248   MachineFrameInfo &MFI = MF.getFrameInfo();
9249   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9250 
9251   if (VA.isMemLoc()) {
9252     // f64 is passed on the stack.
9253     int FI =
9254         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
9255     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9256     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
9257                        MachinePointerInfo::getFixedStack(MF, FI));
9258   }
9259 
9260   assert(VA.isRegLoc() && "Expected register VA assignment");
9261 
9262   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9263   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
9264   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
9265   SDValue Hi;
9266   if (VA.getLocReg() == RISCV::X17) {
9267     // Second half of f64 is passed on the stack.
9268     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
9269     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9270     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
9271                      MachinePointerInfo::getFixedStack(MF, FI));
9272   } else {
9273     // Second half of f64 is passed in another GPR.
9274     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9275     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
9276     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
9277   }
9278   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
9279 }
9280 
9281 // FastCC has less than 1% performance improvement for some particular
9282 // benchmark. But theoretically, it may has benenfit for some cases.
9283 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
9284                             unsigned ValNo, MVT ValVT, MVT LocVT,
9285                             CCValAssign::LocInfo LocInfo,
9286                             ISD::ArgFlagsTy ArgFlags, CCState &State,
9287                             bool IsFixed, bool IsRet, Type *OrigTy,
9288                             const RISCVTargetLowering &TLI,
9289                             Optional<unsigned> FirstMaskArgument) {
9290 
9291   // X5 and X6 might be used for save-restore libcall.
9292   static const MCPhysReg GPRList[] = {
9293       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
9294       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
9295       RISCV::X29, RISCV::X30, RISCV::X31};
9296 
9297   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9298     if (unsigned Reg = State.AllocateReg(GPRList)) {
9299       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9300       return false;
9301     }
9302   }
9303 
9304   if (LocVT == MVT::f16) {
9305     static const MCPhysReg FPR16List[] = {
9306         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
9307         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
9308         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
9309         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
9310     if (unsigned Reg = State.AllocateReg(FPR16List)) {
9311       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9312       return false;
9313     }
9314   }
9315 
9316   if (LocVT == MVT::f32) {
9317     static const MCPhysReg FPR32List[] = {
9318         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
9319         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
9320         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
9321         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
9322     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9323       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9324       return false;
9325     }
9326   }
9327 
9328   if (LocVT == MVT::f64) {
9329     static const MCPhysReg FPR64List[] = {
9330         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
9331         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
9332         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
9333         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
9334     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9335       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9336       return false;
9337     }
9338   }
9339 
9340   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
9341     unsigned Offset4 = State.AllocateStack(4, Align(4));
9342     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
9343     return false;
9344   }
9345 
9346   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
9347     unsigned Offset5 = State.AllocateStack(8, Align(8));
9348     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
9349     return false;
9350   }
9351 
9352   if (LocVT.isVector()) {
9353     if (unsigned Reg =
9354             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
9355       // Fixed-length vectors are located in the corresponding scalable-vector
9356       // container types.
9357       if (ValVT.isFixedLengthVector())
9358         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9359       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9360     } else {
9361       // Try and pass the address via a "fast" GPR.
9362       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
9363         LocInfo = CCValAssign::Indirect;
9364         LocVT = TLI.getSubtarget().getXLenVT();
9365         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
9366       } else if (ValVT.isFixedLengthVector()) {
9367         auto StackAlign =
9368             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9369         unsigned StackOffset =
9370             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
9371         State.addLoc(
9372             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9373       } else {
9374         // Can't pass scalable vectors on the stack.
9375         return true;
9376       }
9377     }
9378 
9379     return false;
9380   }
9381 
9382   return true; // CC didn't match.
9383 }
9384 
9385 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
9386                          CCValAssign::LocInfo LocInfo,
9387                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
9388 
9389   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9390     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
9391     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
9392     static const MCPhysReg GPRList[] = {
9393         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
9394         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
9395     if (unsigned Reg = State.AllocateReg(GPRList)) {
9396       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9397       return false;
9398     }
9399   }
9400 
9401   if (LocVT == MVT::f32) {
9402     // Pass in STG registers: F1, ..., F6
9403     //                        fs0 ... fs5
9404     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
9405                                           RISCV::F18_F, RISCV::F19_F,
9406                                           RISCV::F20_F, RISCV::F21_F};
9407     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9408       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9409       return false;
9410     }
9411   }
9412 
9413   if (LocVT == MVT::f64) {
9414     // Pass in STG registers: D1, ..., D6
9415     //                        fs6 ... fs11
9416     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
9417                                           RISCV::F24_D, RISCV::F25_D,
9418                                           RISCV::F26_D, RISCV::F27_D};
9419     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9420       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9421       return false;
9422     }
9423   }
9424 
9425   report_fatal_error("No registers left in GHC calling convention");
9426   return true;
9427 }
9428 
9429 // Transform physical registers into virtual registers.
9430 SDValue RISCVTargetLowering::LowerFormalArguments(
9431     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
9432     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
9433     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
9434 
9435   MachineFunction &MF = DAG.getMachineFunction();
9436 
9437   switch (CallConv) {
9438   default:
9439     report_fatal_error("Unsupported calling convention");
9440   case CallingConv::C:
9441   case CallingConv::Fast:
9442     break;
9443   case CallingConv::GHC:
9444     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
9445         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
9446       report_fatal_error(
9447         "GHC calling convention requires the F and D instruction set extensions");
9448   }
9449 
9450   const Function &Func = MF.getFunction();
9451   if (Func.hasFnAttribute("interrupt")) {
9452     if (!Func.arg_empty())
9453       report_fatal_error(
9454         "Functions with the interrupt attribute cannot have arguments!");
9455 
9456     StringRef Kind =
9457       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
9458 
9459     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
9460       report_fatal_error(
9461         "Function interrupt attribute argument not supported!");
9462   }
9463 
9464   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9465   MVT XLenVT = Subtarget.getXLenVT();
9466   unsigned XLenInBytes = Subtarget.getXLen() / 8;
9467   // Used with vargs to acumulate store chains.
9468   std::vector<SDValue> OutChains;
9469 
9470   // Assign locations to all of the incoming arguments.
9471   SmallVector<CCValAssign, 16> ArgLocs;
9472   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9473 
9474   if (CallConv == CallingConv::GHC)
9475     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
9476   else
9477     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
9478                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9479                                                    : CC_RISCV);
9480 
9481   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
9482     CCValAssign &VA = ArgLocs[i];
9483     SDValue ArgValue;
9484     // Passing f64 on RV32D with a soft float ABI must be handled as a special
9485     // case.
9486     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
9487       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
9488     else if (VA.isRegLoc())
9489       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
9490     else
9491       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
9492 
9493     if (VA.getLocInfo() == CCValAssign::Indirect) {
9494       // If the original argument was split and passed by reference (e.g. i128
9495       // on RV32), we need to load all parts of it here (using the same
9496       // address). Vectors may be partly split to registers and partly to the
9497       // stack, in which case the base address is partly offset and subsequent
9498       // stores are relative to that.
9499       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
9500                                    MachinePointerInfo()));
9501       unsigned ArgIndex = Ins[i].OrigArgIndex;
9502       unsigned ArgPartOffset = Ins[i].PartOffset;
9503       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9504       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
9505         CCValAssign &PartVA = ArgLocs[i + 1];
9506         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
9507         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9508         if (PartVA.getValVT().isScalableVector())
9509           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9510         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
9511         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
9512                                      MachinePointerInfo()));
9513         ++i;
9514       }
9515       continue;
9516     }
9517     InVals.push_back(ArgValue);
9518   }
9519 
9520   if (IsVarArg) {
9521     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
9522     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
9523     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
9524     MachineFrameInfo &MFI = MF.getFrameInfo();
9525     MachineRegisterInfo &RegInfo = MF.getRegInfo();
9526     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
9527 
9528     // Offset of the first variable argument from stack pointer, and size of
9529     // the vararg save area. For now, the varargs save area is either zero or
9530     // large enough to hold a0-a7.
9531     int VaArgOffset, VarArgsSaveSize;
9532 
9533     // If all registers are allocated, then all varargs must be passed on the
9534     // stack and we don't need to save any argregs.
9535     if (ArgRegs.size() == Idx) {
9536       VaArgOffset = CCInfo.getNextStackOffset();
9537       VarArgsSaveSize = 0;
9538     } else {
9539       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
9540       VaArgOffset = -VarArgsSaveSize;
9541     }
9542 
9543     // Record the frame index of the first variable argument
9544     // which is a value necessary to VASTART.
9545     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9546     RVFI->setVarArgsFrameIndex(FI);
9547 
9548     // If saving an odd number of registers then create an extra stack slot to
9549     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
9550     // offsets to even-numbered registered remain 2*XLEN-aligned.
9551     if (Idx % 2) {
9552       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
9553       VarArgsSaveSize += XLenInBytes;
9554     }
9555 
9556     // Copy the integer registers that may have been used for passing varargs
9557     // to the vararg save area.
9558     for (unsigned I = Idx; I < ArgRegs.size();
9559          ++I, VaArgOffset += XLenInBytes) {
9560       const Register Reg = RegInfo.createVirtualRegister(RC);
9561       RegInfo.addLiveIn(ArgRegs[I], Reg);
9562       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
9563       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
9564       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9565       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
9566                                    MachinePointerInfo::getFixedStack(MF, FI));
9567       cast<StoreSDNode>(Store.getNode())
9568           ->getMemOperand()
9569           ->setValue((Value *)nullptr);
9570       OutChains.push_back(Store);
9571     }
9572     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
9573   }
9574 
9575   // All stores are grouped in one node to allow the matching between
9576   // the size of Ins and InVals. This only happens for vararg functions.
9577   if (!OutChains.empty()) {
9578     OutChains.push_back(Chain);
9579     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
9580   }
9581 
9582   return Chain;
9583 }
9584 
9585 /// isEligibleForTailCallOptimization - Check whether the call is eligible
9586 /// for tail call optimization.
9587 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
9588 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
9589     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
9590     const SmallVector<CCValAssign, 16> &ArgLocs) const {
9591 
9592   auto &Callee = CLI.Callee;
9593   auto CalleeCC = CLI.CallConv;
9594   auto &Outs = CLI.Outs;
9595   auto &Caller = MF.getFunction();
9596   auto CallerCC = Caller.getCallingConv();
9597 
9598   // Exception-handling functions need a special set of instructions to
9599   // indicate a return to the hardware. Tail-calling another function would
9600   // probably break this.
9601   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
9602   // should be expanded as new function attributes are introduced.
9603   if (Caller.hasFnAttribute("interrupt"))
9604     return false;
9605 
9606   // Do not tail call opt if the stack is used to pass parameters.
9607   if (CCInfo.getNextStackOffset() != 0)
9608     return false;
9609 
9610   // Do not tail call opt if any parameters need to be passed indirectly.
9611   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
9612   // passed indirectly. So the address of the value will be passed in a
9613   // register, or if not available, then the address is put on the stack. In
9614   // order to pass indirectly, space on the stack often needs to be allocated
9615   // in order to store the value. In this case the CCInfo.getNextStackOffset()
9616   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
9617   // are passed CCValAssign::Indirect.
9618   for (auto &VA : ArgLocs)
9619     if (VA.getLocInfo() == CCValAssign::Indirect)
9620       return false;
9621 
9622   // Do not tail call opt if either caller or callee uses struct return
9623   // semantics.
9624   auto IsCallerStructRet = Caller.hasStructRetAttr();
9625   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
9626   if (IsCallerStructRet || IsCalleeStructRet)
9627     return false;
9628 
9629   // Externally-defined functions with weak linkage should not be
9630   // tail-called. The behaviour of branch instructions in this situation (as
9631   // used for tail calls) is implementation-defined, so we cannot rely on the
9632   // linker replacing the tail call with a return.
9633   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
9634     const GlobalValue *GV = G->getGlobal();
9635     if (GV->hasExternalWeakLinkage())
9636       return false;
9637   }
9638 
9639   // The callee has to preserve all registers the caller needs to preserve.
9640   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
9641   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
9642   if (CalleeCC != CallerCC) {
9643     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
9644     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
9645       return false;
9646   }
9647 
9648   // Byval parameters hand the function a pointer directly into the stack area
9649   // we want to reuse during a tail call. Working around this *is* possible
9650   // but less efficient and uglier in LowerCall.
9651   for (auto &Arg : Outs)
9652     if (Arg.Flags.isByVal())
9653       return false;
9654 
9655   return true;
9656 }
9657 
9658 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
9659   return DAG.getDataLayout().getPrefTypeAlign(
9660       VT.getTypeForEVT(*DAG.getContext()));
9661 }
9662 
9663 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
9664 // and output parameter nodes.
9665 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
9666                                        SmallVectorImpl<SDValue> &InVals) const {
9667   SelectionDAG &DAG = CLI.DAG;
9668   SDLoc &DL = CLI.DL;
9669   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
9670   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
9671   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
9672   SDValue Chain = CLI.Chain;
9673   SDValue Callee = CLI.Callee;
9674   bool &IsTailCall = CLI.IsTailCall;
9675   CallingConv::ID CallConv = CLI.CallConv;
9676   bool IsVarArg = CLI.IsVarArg;
9677   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9678   MVT XLenVT = Subtarget.getXLenVT();
9679 
9680   MachineFunction &MF = DAG.getMachineFunction();
9681 
9682   // Analyze the operands of the call, assigning locations to each operand.
9683   SmallVector<CCValAssign, 16> ArgLocs;
9684   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
9685 
9686   if (CallConv == CallingConv::GHC)
9687     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
9688   else
9689     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
9690                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
9691                                                     : CC_RISCV);
9692 
9693   // Check if it's really possible to do a tail call.
9694   if (IsTailCall)
9695     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
9696 
9697   if (IsTailCall)
9698     ++NumTailCalls;
9699   else if (CLI.CB && CLI.CB->isMustTailCall())
9700     report_fatal_error("failed to perform tail call elimination on a call "
9701                        "site marked musttail");
9702 
9703   // Get a count of how many bytes are to be pushed on the stack.
9704   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
9705 
9706   // Create local copies for byval args
9707   SmallVector<SDValue, 8> ByValArgs;
9708   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9709     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9710     if (!Flags.isByVal())
9711       continue;
9712 
9713     SDValue Arg = OutVals[i];
9714     unsigned Size = Flags.getByValSize();
9715     Align Alignment = Flags.getNonZeroByValAlign();
9716 
9717     int FI =
9718         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
9719     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
9720     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
9721 
9722     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
9723                           /*IsVolatile=*/false,
9724                           /*AlwaysInline=*/false, IsTailCall,
9725                           MachinePointerInfo(), MachinePointerInfo());
9726     ByValArgs.push_back(FIPtr);
9727   }
9728 
9729   if (!IsTailCall)
9730     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
9731 
9732   // Copy argument values to their designated locations.
9733   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
9734   SmallVector<SDValue, 8> MemOpChains;
9735   SDValue StackPtr;
9736   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
9737     CCValAssign &VA = ArgLocs[i];
9738     SDValue ArgValue = OutVals[i];
9739     ISD::ArgFlagsTy Flags = Outs[i].Flags;
9740 
9741     // Handle passing f64 on RV32D with a soft float ABI as a special case.
9742     bool IsF64OnRV32DSoftABI =
9743         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
9744     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
9745       SDValue SplitF64 = DAG.getNode(
9746           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
9747       SDValue Lo = SplitF64.getValue(0);
9748       SDValue Hi = SplitF64.getValue(1);
9749 
9750       Register RegLo = VA.getLocReg();
9751       RegsToPass.push_back(std::make_pair(RegLo, Lo));
9752 
9753       if (RegLo == RISCV::X17) {
9754         // Second half of f64 is passed on the stack.
9755         // Work out the address of the stack slot.
9756         if (!StackPtr.getNode())
9757           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9758         // Emit the store.
9759         MemOpChains.push_back(
9760             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
9761       } else {
9762         // Second half of f64 is passed in another GPR.
9763         assert(RegLo < RISCV::X31 && "Invalid register pair");
9764         Register RegHigh = RegLo + 1;
9765         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
9766       }
9767       continue;
9768     }
9769 
9770     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
9771     // as any other MemLoc.
9772 
9773     // Promote the value if needed.
9774     // For now, only handle fully promoted and indirect arguments.
9775     if (VA.getLocInfo() == CCValAssign::Indirect) {
9776       // Store the argument in a stack slot and pass its address.
9777       Align StackAlign =
9778           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
9779                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
9780       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
9781       // If the original argument was split (e.g. i128), we need
9782       // to store the required parts of it here (and pass just one address).
9783       // Vectors may be partly split to registers and partly to the stack, in
9784       // which case the base address is partly offset and subsequent stores are
9785       // relative to that.
9786       unsigned ArgIndex = Outs[i].OrigArgIndex;
9787       unsigned ArgPartOffset = Outs[i].PartOffset;
9788       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
9789       // Calculate the total size to store. We don't have access to what we're
9790       // actually storing other than performing the loop and collecting the
9791       // info.
9792       SmallVector<std::pair<SDValue, SDValue>> Parts;
9793       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
9794         SDValue PartValue = OutVals[i + 1];
9795         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
9796         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
9797         EVT PartVT = PartValue.getValueType();
9798         if (PartVT.isScalableVector())
9799           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
9800         StoredSize += PartVT.getStoreSize();
9801         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
9802         Parts.push_back(std::make_pair(PartValue, Offset));
9803         ++i;
9804       }
9805       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
9806       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
9807       MemOpChains.push_back(
9808           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
9809                        MachinePointerInfo::getFixedStack(MF, FI)));
9810       for (const auto &Part : Parts) {
9811         SDValue PartValue = Part.first;
9812         SDValue PartOffset = Part.second;
9813         SDValue Address =
9814             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
9815         MemOpChains.push_back(
9816             DAG.getStore(Chain, DL, PartValue, Address,
9817                          MachinePointerInfo::getFixedStack(MF, FI)));
9818       }
9819       ArgValue = SpillSlot;
9820     } else {
9821       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
9822     }
9823 
9824     // Use local copy if it is a byval arg.
9825     if (Flags.isByVal())
9826       ArgValue = ByValArgs[j++];
9827 
9828     if (VA.isRegLoc()) {
9829       // Queue up the argument copies and emit them at the end.
9830       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
9831     } else {
9832       assert(VA.isMemLoc() && "Argument not register or memory");
9833       assert(!IsTailCall && "Tail call not allowed if stack is used "
9834                             "for passing parameters");
9835 
9836       // Work out the address of the stack slot.
9837       if (!StackPtr.getNode())
9838         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
9839       SDValue Address =
9840           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
9841                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
9842 
9843       // Emit the store.
9844       MemOpChains.push_back(
9845           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
9846     }
9847   }
9848 
9849   // Join the stores, which are independent of one another.
9850   if (!MemOpChains.empty())
9851     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
9852 
9853   SDValue Glue;
9854 
9855   // Build a sequence of copy-to-reg nodes, chained and glued together.
9856   for (auto &Reg : RegsToPass) {
9857     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
9858     Glue = Chain.getValue(1);
9859   }
9860 
9861   // Validate that none of the argument registers have been marked as
9862   // reserved, if so report an error. Do the same for the return address if this
9863   // is not a tailcall.
9864   validateCCReservedRegs(RegsToPass, MF);
9865   if (!IsTailCall &&
9866       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
9867     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
9868         MF.getFunction(),
9869         "Return address register required, but has been reserved."});
9870 
9871   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
9872   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
9873   // split it and then direct call can be matched by PseudoCALL.
9874   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
9875     const GlobalValue *GV = S->getGlobal();
9876 
9877     unsigned OpFlags = RISCVII::MO_CALL;
9878     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
9879       OpFlags = RISCVII::MO_PLT;
9880 
9881     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
9882   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
9883     unsigned OpFlags = RISCVII::MO_CALL;
9884 
9885     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
9886                                                  nullptr))
9887       OpFlags = RISCVII::MO_PLT;
9888 
9889     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
9890   }
9891 
9892   // The first call operand is the chain and the second is the target address.
9893   SmallVector<SDValue, 8> Ops;
9894   Ops.push_back(Chain);
9895   Ops.push_back(Callee);
9896 
9897   // Add argument registers to the end of the list so that they are
9898   // known live into the call.
9899   for (auto &Reg : RegsToPass)
9900     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
9901 
9902   if (!IsTailCall) {
9903     // Add a register mask operand representing the call-preserved registers.
9904     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
9905     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
9906     assert(Mask && "Missing call preserved mask for calling convention");
9907     Ops.push_back(DAG.getRegisterMask(Mask));
9908   }
9909 
9910   // Glue the call to the argument copies, if any.
9911   if (Glue.getNode())
9912     Ops.push_back(Glue);
9913 
9914   // Emit the call.
9915   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9916 
9917   if (IsTailCall) {
9918     MF.getFrameInfo().setHasTailCall();
9919     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
9920   }
9921 
9922   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
9923   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
9924   Glue = Chain.getValue(1);
9925 
9926   // Mark the end of the call, which is glued to the call itself.
9927   Chain = DAG.getCALLSEQ_END(Chain,
9928                              DAG.getConstant(NumBytes, DL, PtrVT, true),
9929                              DAG.getConstant(0, DL, PtrVT, true),
9930                              Glue, DL);
9931   Glue = Chain.getValue(1);
9932 
9933   // Assign locations to each value returned by this call.
9934   SmallVector<CCValAssign, 16> RVLocs;
9935   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
9936   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
9937 
9938   // Copy all of the result registers out of their specified physreg.
9939   for (auto &VA : RVLocs) {
9940     // Copy the value out
9941     SDValue RetValue =
9942         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
9943     // Glue the RetValue to the end of the call sequence
9944     Chain = RetValue.getValue(1);
9945     Glue = RetValue.getValue(2);
9946 
9947     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
9948       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
9949       SDValue RetValue2 =
9950           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
9951       Chain = RetValue2.getValue(1);
9952       Glue = RetValue2.getValue(2);
9953       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
9954                              RetValue2);
9955     }
9956 
9957     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
9958 
9959     InVals.push_back(RetValue);
9960   }
9961 
9962   return Chain;
9963 }
9964 
9965 bool RISCVTargetLowering::CanLowerReturn(
9966     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
9967     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
9968   SmallVector<CCValAssign, 16> RVLocs;
9969   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
9970 
9971   Optional<unsigned> FirstMaskArgument;
9972   if (Subtarget.hasVInstructions())
9973     FirstMaskArgument = preAssignMask(Outs);
9974 
9975   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
9976     MVT VT = Outs[i].VT;
9977     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9978     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9979     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
9980                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
9981                  *this, FirstMaskArgument))
9982       return false;
9983   }
9984   return true;
9985 }
9986 
9987 SDValue
9988 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
9989                                  bool IsVarArg,
9990                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
9991                                  const SmallVectorImpl<SDValue> &OutVals,
9992                                  const SDLoc &DL, SelectionDAG &DAG) const {
9993   const MachineFunction &MF = DAG.getMachineFunction();
9994   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
9995 
9996   // Stores the assignment of the return value to a location.
9997   SmallVector<CCValAssign, 16> RVLocs;
9998 
9999   // Info about the registers and stack slot.
10000   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10001                  *DAG.getContext());
10002 
10003   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10004                     nullptr, CC_RISCV);
10005 
10006   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10007     report_fatal_error("GHC functions return void only");
10008 
10009   SDValue Glue;
10010   SmallVector<SDValue, 4> RetOps(1, Chain);
10011 
10012   // Copy the result values into the output registers.
10013   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10014     SDValue Val = OutVals[i];
10015     CCValAssign &VA = RVLocs[i];
10016     assert(VA.isRegLoc() && "Can only return in registers!");
10017 
10018     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10019       // Handle returning f64 on RV32D with a soft float ABI.
10020       assert(VA.isRegLoc() && "Expected return via registers");
10021       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10022                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10023       SDValue Lo = SplitF64.getValue(0);
10024       SDValue Hi = SplitF64.getValue(1);
10025       Register RegLo = VA.getLocReg();
10026       assert(RegLo < RISCV::X31 && "Invalid register pair");
10027       Register RegHi = RegLo + 1;
10028 
10029       if (STI.isRegisterReservedByUser(RegLo) ||
10030           STI.isRegisterReservedByUser(RegHi))
10031         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10032             MF.getFunction(),
10033             "Return value register required, but has been reserved."});
10034 
10035       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10036       Glue = Chain.getValue(1);
10037       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10038       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10039       Glue = Chain.getValue(1);
10040       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10041     } else {
10042       // Handle a 'normal' return.
10043       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10044       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10045 
10046       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10047         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10048             MF.getFunction(),
10049             "Return value register required, but has been reserved."});
10050 
10051       // Guarantee that all emitted copies are stuck together.
10052       Glue = Chain.getValue(1);
10053       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10054     }
10055   }
10056 
10057   RetOps[0] = Chain; // Update chain.
10058 
10059   // Add the glue node if we have it.
10060   if (Glue.getNode()) {
10061     RetOps.push_back(Glue);
10062   }
10063 
10064   unsigned RetOpc = RISCVISD::RET_FLAG;
10065   // Interrupt service routines use different return instructions.
10066   const Function &Func = DAG.getMachineFunction().getFunction();
10067   if (Func.hasFnAttribute("interrupt")) {
10068     if (!Func.getReturnType()->isVoidTy())
10069       report_fatal_error(
10070           "Functions with the interrupt attribute must have void return type!");
10071 
10072     MachineFunction &MF = DAG.getMachineFunction();
10073     StringRef Kind =
10074       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10075 
10076     if (Kind == "user")
10077       RetOpc = RISCVISD::URET_FLAG;
10078     else if (Kind == "supervisor")
10079       RetOpc = RISCVISD::SRET_FLAG;
10080     else
10081       RetOpc = RISCVISD::MRET_FLAG;
10082   }
10083 
10084   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10085 }
10086 
10087 void RISCVTargetLowering::validateCCReservedRegs(
10088     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10089     MachineFunction &MF) const {
10090   const Function &F = MF.getFunction();
10091   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10092 
10093   if (llvm::any_of(Regs, [&STI](auto Reg) {
10094         return STI.isRegisterReservedByUser(Reg.first);
10095       }))
10096     F.getContext().diagnose(DiagnosticInfoUnsupported{
10097         F, "Argument register required, but has been reserved."});
10098 }
10099 
10100 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10101   return CI->isTailCall();
10102 }
10103 
10104 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10105 #define NODE_NAME_CASE(NODE)                                                   \
10106   case RISCVISD::NODE:                                                         \
10107     return "RISCVISD::" #NODE;
10108   // clang-format off
10109   switch ((RISCVISD::NodeType)Opcode) {
10110   case RISCVISD::FIRST_NUMBER:
10111     break;
10112   NODE_NAME_CASE(RET_FLAG)
10113   NODE_NAME_CASE(URET_FLAG)
10114   NODE_NAME_CASE(SRET_FLAG)
10115   NODE_NAME_CASE(MRET_FLAG)
10116   NODE_NAME_CASE(CALL)
10117   NODE_NAME_CASE(SELECT_CC)
10118   NODE_NAME_CASE(BR_CC)
10119   NODE_NAME_CASE(BuildPairF64)
10120   NODE_NAME_CASE(SplitF64)
10121   NODE_NAME_CASE(TAIL)
10122   NODE_NAME_CASE(MULHSU)
10123   NODE_NAME_CASE(SLLW)
10124   NODE_NAME_CASE(SRAW)
10125   NODE_NAME_CASE(SRLW)
10126   NODE_NAME_CASE(DIVW)
10127   NODE_NAME_CASE(DIVUW)
10128   NODE_NAME_CASE(REMUW)
10129   NODE_NAME_CASE(ROLW)
10130   NODE_NAME_CASE(RORW)
10131   NODE_NAME_CASE(CLZW)
10132   NODE_NAME_CASE(CTZW)
10133   NODE_NAME_CASE(FSLW)
10134   NODE_NAME_CASE(FSRW)
10135   NODE_NAME_CASE(FSL)
10136   NODE_NAME_CASE(FSR)
10137   NODE_NAME_CASE(FMV_H_X)
10138   NODE_NAME_CASE(FMV_X_ANYEXTH)
10139   NODE_NAME_CASE(FMV_W_X_RV64)
10140   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10141   NODE_NAME_CASE(FCVT_X)
10142   NODE_NAME_CASE(FCVT_XU)
10143   NODE_NAME_CASE(FCVT_W_RV64)
10144   NODE_NAME_CASE(FCVT_WU_RV64)
10145   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10146   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10147   NODE_NAME_CASE(READ_CYCLE_WIDE)
10148   NODE_NAME_CASE(GREV)
10149   NODE_NAME_CASE(GREVW)
10150   NODE_NAME_CASE(GORC)
10151   NODE_NAME_CASE(GORCW)
10152   NODE_NAME_CASE(SHFL)
10153   NODE_NAME_CASE(SHFLW)
10154   NODE_NAME_CASE(UNSHFL)
10155   NODE_NAME_CASE(UNSHFLW)
10156   NODE_NAME_CASE(BFP)
10157   NODE_NAME_CASE(BFPW)
10158   NODE_NAME_CASE(BCOMPRESS)
10159   NODE_NAME_CASE(BCOMPRESSW)
10160   NODE_NAME_CASE(BDECOMPRESS)
10161   NODE_NAME_CASE(BDECOMPRESSW)
10162   NODE_NAME_CASE(VMV_V_X_VL)
10163   NODE_NAME_CASE(VFMV_V_F_VL)
10164   NODE_NAME_CASE(VMV_X_S)
10165   NODE_NAME_CASE(VMV_S_X_VL)
10166   NODE_NAME_CASE(VFMV_S_F_VL)
10167   NODE_NAME_CASE(SPLAT_VECTOR_I64)
10168   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10169   NODE_NAME_CASE(READ_VLENB)
10170   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10171   NODE_NAME_CASE(VSLIDEUP_VL)
10172   NODE_NAME_CASE(VSLIDE1UP_VL)
10173   NODE_NAME_CASE(VSLIDEDOWN_VL)
10174   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10175   NODE_NAME_CASE(VID_VL)
10176   NODE_NAME_CASE(VFNCVT_ROD_VL)
10177   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10178   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10179   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10180   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10181   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10182   NODE_NAME_CASE(VECREDUCE_AND_VL)
10183   NODE_NAME_CASE(VECREDUCE_OR_VL)
10184   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10185   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10186   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10187   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10188   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10189   NODE_NAME_CASE(ADD_VL)
10190   NODE_NAME_CASE(AND_VL)
10191   NODE_NAME_CASE(MUL_VL)
10192   NODE_NAME_CASE(OR_VL)
10193   NODE_NAME_CASE(SDIV_VL)
10194   NODE_NAME_CASE(SHL_VL)
10195   NODE_NAME_CASE(SREM_VL)
10196   NODE_NAME_CASE(SRA_VL)
10197   NODE_NAME_CASE(SRL_VL)
10198   NODE_NAME_CASE(SUB_VL)
10199   NODE_NAME_CASE(UDIV_VL)
10200   NODE_NAME_CASE(UREM_VL)
10201   NODE_NAME_CASE(XOR_VL)
10202   NODE_NAME_CASE(SADDSAT_VL)
10203   NODE_NAME_CASE(UADDSAT_VL)
10204   NODE_NAME_CASE(SSUBSAT_VL)
10205   NODE_NAME_CASE(USUBSAT_VL)
10206   NODE_NAME_CASE(FADD_VL)
10207   NODE_NAME_CASE(FSUB_VL)
10208   NODE_NAME_CASE(FMUL_VL)
10209   NODE_NAME_CASE(FDIV_VL)
10210   NODE_NAME_CASE(FNEG_VL)
10211   NODE_NAME_CASE(FABS_VL)
10212   NODE_NAME_CASE(FSQRT_VL)
10213   NODE_NAME_CASE(FMA_VL)
10214   NODE_NAME_CASE(FCOPYSIGN_VL)
10215   NODE_NAME_CASE(SMIN_VL)
10216   NODE_NAME_CASE(SMAX_VL)
10217   NODE_NAME_CASE(UMIN_VL)
10218   NODE_NAME_CASE(UMAX_VL)
10219   NODE_NAME_CASE(FMINNUM_VL)
10220   NODE_NAME_CASE(FMAXNUM_VL)
10221   NODE_NAME_CASE(MULHS_VL)
10222   NODE_NAME_CASE(MULHU_VL)
10223   NODE_NAME_CASE(FP_TO_SINT_VL)
10224   NODE_NAME_CASE(FP_TO_UINT_VL)
10225   NODE_NAME_CASE(SINT_TO_FP_VL)
10226   NODE_NAME_CASE(UINT_TO_FP_VL)
10227   NODE_NAME_CASE(FP_EXTEND_VL)
10228   NODE_NAME_CASE(FP_ROUND_VL)
10229   NODE_NAME_CASE(VWMUL_VL)
10230   NODE_NAME_CASE(VWMULU_VL)
10231   NODE_NAME_CASE(VWMULSU_VL)
10232   NODE_NAME_CASE(VWADDU_VL)
10233   NODE_NAME_CASE(SETCC_VL)
10234   NODE_NAME_CASE(VSELECT_VL)
10235   NODE_NAME_CASE(VP_MERGE_VL)
10236   NODE_NAME_CASE(VMAND_VL)
10237   NODE_NAME_CASE(VMOR_VL)
10238   NODE_NAME_CASE(VMXOR_VL)
10239   NODE_NAME_CASE(VMCLR_VL)
10240   NODE_NAME_CASE(VMSET_VL)
10241   NODE_NAME_CASE(VRGATHER_VX_VL)
10242   NODE_NAME_CASE(VRGATHER_VV_VL)
10243   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
10244   NODE_NAME_CASE(VSEXT_VL)
10245   NODE_NAME_CASE(VZEXT_VL)
10246   NODE_NAME_CASE(VCPOP_VL)
10247   NODE_NAME_CASE(VLE_VL)
10248   NODE_NAME_CASE(VSE_VL)
10249   NODE_NAME_CASE(READ_CSR)
10250   NODE_NAME_CASE(WRITE_CSR)
10251   NODE_NAME_CASE(SWAP_CSR)
10252   }
10253   // clang-format on
10254   return nullptr;
10255 #undef NODE_NAME_CASE
10256 }
10257 
10258 /// getConstraintType - Given a constraint letter, return the type of
10259 /// constraint it is for this target.
10260 RISCVTargetLowering::ConstraintType
10261 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
10262   if (Constraint.size() == 1) {
10263     switch (Constraint[0]) {
10264     default:
10265       break;
10266     case 'f':
10267       return C_RegisterClass;
10268     case 'I':
10269     case 'J':
10270     case 'K':
10271       return C_Immediate;
10272     case 'A':
10273       return C_Memory;
10274     case 'S': // A symbolic address
10275       return C_Other;
10276     }
10277   } else {
10278     if (Constraint == "vr" || Constraint == "vm")
10279       return C_RegisterClass;
10280   }
10281   return TargetLowering::getConstraintType(Constraint);
10282 }
10283 
10284 std::pair<unsigned, const TargetRegisterClass *>
10285 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10286                                                   StringRef Constraint,
10287                                                   MVT VT) const {
10288   // First, see if this is a constraint that directly corresponds to a
10289   // RISCV register class.
10290   if (Constraint.size() == 1) {
10291     switch (Constraint[0]) {
10292     case 'r':
10293       // TODO: Support fixed vectors up to XLen for P extension?
10294       if (VT.isVector())
10295         break;
10296       return std::make_pair(0U, &RISCV::GPRRegClass);
10297     case 'f':
10298       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
10299         return std::make_pair(0U, &RISCV::FPR16RegClass);
10300       if (Subtarget.hasStdExtF() && VT == MVT::f32)
10301         return std::make_pair(0U, &RISCV::FPR32RegClass);
10302       if (Subtarget.hasStdExtD() && VT == MVT::f64)
10303         return std::make_pair(0U, &RISCV::FPR64RegClass);
10304       break;
10305     default:
10306       break;
10307     }
10308   } else if (Constraint == "vr") {
10309     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
10310                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10311       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
10312         return std::make_pair(0U, RC);
10313     }
10314   } else if (Constraint == "vm") {
10315     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
10316       return std::make_pair(0U, &RISCV::VMV0RegClass);
10317   }
10318 
10319   // Clang will correctly decode the usage of register name aliases into their
10320   // official names. However, other frontends like `rustc` do not. This allows
10321   // users of these frontends to use the ABI names for registers in LLVM-style
10322   // register constraints.
10323   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
10324                                .Case("{zero}", RISCV::X0)
10325                                .Case("{ra}", RISCV::X1)
10326                                .Case("{sp}", RISCV::X2)
10327                                .Case("{gp}", RISCV::X3)
10328                                .Case("{tp}", RISCV::X4)
10329                                .Case("{t0}", RISCV::X5)
10330                                .Case("{t1}", RISCV::X6)
10331                                .Case("{t2}", RISCV::X7)
10332                                .Cases("{s0}", "{fp}", RISCV::X8)
10333                                .Case("{s1}", RISCV::X9)
10334                                .Case("{a0}", RISCV::X10)
10335                                .Case("{a1}", RISCV::X11)
10336                                .Case("{a2}", RISCV::X12)
10337                                .Case("{a3}", RISCV::X13)
10338                                .Case("{a4}", RISCV::X14)
10339                                .Case("{a5}", RISCV::X15)
10340                                .Case("{a6}", RISCV::X16)
10341                                .Case("{a7}", RISCV::X17)
10342                                .Case("{s2}", RISCV::X18)
10343                                .Case("{s3}", RISCV::X19)
10344                                .Case("{s4}", RISCV::X20)
10345                                .Case("{s5}", RISCV::X21)
10346                                .Case("{s6}", RISCV::X22)
10347                                .Case("{s7}", RISCV::X23)
10348                                .Case("{s8}", RISCV::X24)
10349                                .Case("{s9}", RISCV::X25)
10350                                .Case("{s10}", RISCV::X26)
10351                                .Case("{s11}", RISCV::X27)
10352                                .Case("{t3}", RISCV::X28)
10353                                .Case("{t4}", RISCV::X29)
10354                                .Case("{t5}", RISCV::X30)
10355                                .Case("{t6}", RISCV::X31)
10356                                .Default(RISCV::NoRegister);
10357   if (XRegFromAlias != RISCV::NoRegister)
10358     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
10359 
10360   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
10361   // TableGen record rather than the AsmName to choose registers for InlineAsm
10362   // constraints, plus we want to match those names to the widest floating point
10363   // register type available, manually select floating point registers here.
10364   //
10365   // The second case is the ABI name of the register, so that frontends can also
10366   // use the ABI names in register constraint lists.
10367   if (Subtarget.hasStdExtF()) {
10368     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
10369                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
10370                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
10371                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
10372                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
10373                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
10374                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
10375                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
10376                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
10377                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
10378                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
10379                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
10380                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
10381                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
10382                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
10383                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
10384                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
10385                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
10386                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
10387                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
10388                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
10389                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
10390                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
10391                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
10392                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
10393                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
10394                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
10395                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
10396                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
10397                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
10398                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
10399                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
10400                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
10401                         .Default(RISCV::NoRegister);
10402     if (FReg != RISCV::NoRegister) {
10403       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
10404       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
10405         unsigned RegNo = FReg - RISCV::F0_F;
10406         unsigned DReg = RISCV::F0_D + RegNo;
10407         return std::make_pair(DReg, &RISCV::FPR64RegClass);
10408       }
10409       if (VT == MVT::f32 || VT == MVT::Other)
10410         return std::make_pair(FReg, &RISCV::FPR32RegClass);
10411       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
10412         unsigned RegNo = FReg - RISCV::F0_F;
10413         unsigned HReg = RISCV::F0_H + RegNo;
10414         return std::make_pair(HReg, &RISCV::FPR16RegClass);
10415       }
10416     }
10417   }
10418 
10419   if (Subtarget.hasVInstructions()) {
10420     Register VReg = StringSwitch<Register>(Constraint.lower())
10421                         .Case("{v0}", RISCV::V0)
10422                         .Case("{v1}", RISCV::V1)
10423                         .Case("{v2}", RISCV::V2)
10424                         .Case("{v3}", RISCV::V3)
10425                         .Case("{v4}", RISCV::V4)
10426                         .Case("{v5}", RISCV::V5)
10427                         .Case("{v6}", RISCV::V6)
10428                         .Case("{v7}", RISCV::V7)
10429                         .Case("{v8}", RISCV::V8)
10430                         .Case("{v9}", RISCV::V9)
10431                         .Case("{v10}", RISCV::V10)
10432                         .Case("{v11}", RISCV::V11)
10433                         .Case("{v12}", RISCV::V12)
10434                         .Case("{v13}", RISCV::V13)
10435                         .Case("{v14}", RISCV::V14)
10436                         .Case("{v15}", RISCV::V15)
10437                         .Case("{v16}", RISCV::V16)
10438                         .Case("{v17}", RISCV::V17)
10439                         .Case("{v18}", RISCV::V18)
10440                         .Case("{v19}", RISCV::V19)
10441                         .Case("{v20}", RISCV::V20)
10442                         .Case("{v21}", RISCV::V21)
10443                         .Case("{v22}", RISCV::V22)
10444                         .Case("{v23}", RISCV::V23)
10445                         .Case("{v24}", RISCV::V24)
10446                         .Case("{v25}", RISCV::V25)
10447                         .Case("{v26}", RISCV::V26)
10448                         .Case("{v27}", RISCV::V27)
10449                         .Case("{v28}", RISCV::V28)
10450                         .Case("{v29}", RISCV::V29)
10451                         .Case("{v30}", RISCV::V30)
10452                         .Case("{v31}", RISCV::V31)
10453                         .Default(RISCV::NoRegister);
10454     if (VReg != RISCV::NoRegister) {
10455       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
10456         return std::make_pair(VReg, &RISCV::VMRegClass);
10457       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
10458         return std::make_pair(VReg, &RISCV::VRRegClass);
10459       for (const auto *RC :
10460            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10461         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
10462           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
10463           return std::make_pair(VReg, RC);
10464         }
10465       }
10466     }
10467   }
10468 
10469   std::pair<Register, const TargetRegisterClass *> Res =
10470       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10471 
10472   // If we picked one of the Zfinx register classes, remap it to the GPR class.
10473   // FIXME: When Zfinx is supported in CodeGen this will need to take the
10474   // Subtarget into account.
10475   if (Res.second == &RISCV::GPRF16RegClass ||
10476       Res.second == &RISCV::GPRF32RegClass ||
10477       Res.second == &RISCV::GPRF64RegClass)
10478     return std::make_pair(Res.first, &RISCV::GPRRegClass);
10479 
10480   return Res;
10481 }
10482 
10483 unsigned
10484 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
10485   // Currently only support length 1 constraints.
10486   if (ConstraintCode.size() == 1) {
10487     switch (ConstraintCode[0]) {
10488     case 'A':
10489       return InlineAsm::Constraint_A;
10490     default:
10491       break;
10492     }
10493   }
10494 
10495   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
10496 }
10497 
10498 void RISCVTargetLowering::LowerAsmOperandForConstraint(
10499     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
10500     SelectionDAG &DAG) const {
10501   // Currently only support length 1 constraints.
10502   if (Constraint.length() == 1) {
10503     switch (Constraint[0]) {
10504     case 'I':
10505       // Validate & create a 12-bit signed immediate operand.
10506       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10507         uint64_t CVal = C->getSExtValue();
10508         if (isInt<12>(CVal))
10509           Ops.push_back(
10510               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10511       }
10512       return;
10513     case 'J':
10514       // Validate & create an integer zero operand.
10515       if (auto *C = dyn_cast<ConstantSDNode>(Op))
10516         if (C->getZExtValue() == 0)
10517           Ops.push_back(
10518               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
10519       return;
10520     case 'K':
10521       // Validate & create a 5-bit unsigned immediate operand.
10522       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
10523         uint64_t CVal = C->getZExtValue();
10524         if (isUInt<5>(CVal))
10525           Ops.push_back(
10526               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
10527       }
10528       return;
10529     case 'S':
10530       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
10531         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
10532                                                  GA->getValueType(0)));
10533       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
10534         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
10535                                                 BA->getValueType(0)));
10536       }
10537       return;
10538     default:
10539       break;
10540     }
10541   }
10542   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10543 }
10544 
10545 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
10546                                                    Instruction *Inst,
10547                                                    AtomicOrdering Ord) const {
10548   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
10549     return Builder.CreateFence(Ord);
10550   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
10551     return Builder.CreateFence(AtomicOrdering::Release);
10552   return nullptr;
10553 }
10554 
10555 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
10556                                                     Instruction *Inst,
10557                                                     AtomicOrdering Ord) const {
10558   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
10559     return Builder.CreateFence(AtomicOrdering::Acquire);
10560   return nullptr;
10561 }
10562 
10563 TargetLowering::AtomicExpansionKind
10564 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10565   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
10566   // point operations can't be used in an lr/sc sequence without breaking the
10567   // forward-progress guarantee.
10568   if (AI->isFloatingPointOperation())
10569     return AtomicExpansionKind::CmpXChg;
10570 
10571   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10572   if (Size == 8 || Size == 16)
10573     return AtomicExpansionKind::MaskedIntrinsic;
10574   return AtomicExpansionKind::None;
10575 }
10576 
10577 static Intrinsic::ID
10578 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
10579   if (XLen == 32) {
10580     switch (BinOp) {
10581     default:
10582       llvm_unreachable("Unexpected AtomicRMW BinOp");
10583     case AtomicRMWInst::Xchg:
10584       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
10585     case AtomicRMWInst::Add:
10586       return Intrinsic::riscv_masked_atomicrmw_add_i32;
10587     case AtomicRMWInst::Sub:
10588       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
10589     case AtomicRMWInst::Nand:
10590       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
10591     case AtomicRMWInst::Max:
10592       return Intrinsic::riscv_masked_atomicrmw_max_i32;
10593     case AtomicRMWInst::Min:
10594       return Intrinsic::riscv_masked_atomicrmw_min_i32;
10595     case AtomicRMWInst::UMax:
10596       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
10597     case AtomicRMWInst::UMin:
10598       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
10599     }
10600   }
10601 
10602   if (XLen == 64) {
10603     switch (BinOp) {
10604     default:
10605       llvm_unreachable("Unexpected AtomicRMW BinOp");
10606     case AtomicRMWInst::Xchg:
10607       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
10608     case AtomicRMWInst::Add:
10609       return Intrinsic::riscv_masked_atomicrmw_add_i64;
10610     case AtomicRMWInst::Sub:
10611       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
10612     case AtomicRMWInst::Nand:
10613       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
10614     case AtomicRMWInst::Max:
10615       return Intrinsic::riscv_masked_atomicrmw_max_i64;
10616     case AtomicRMWInst::Min:
10617       return Intrinsic::riscv_masked_atomicrmw_min_i64;
10618     case AtomicRMWInst::UMax:
10619       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
10620     case AtomicRMWInst::UMin:
10621       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
10622     }
10623   }
10624 
10625   llvm_unreachable("Unexpected XLen\n");
10626 }
10627 
10628 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
10629     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
10630     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
10631   unsigned XLen = Subtarget.getXLen();
10632   Value *Ordering =
10633       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
10634   Type *Tys[] = {AlignedAddr->getType()};
10635   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
10636       AI->getModule(),
10637       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
10638 
10639   if (XLen == 64) {
10640     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
10641     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10642     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
10643   }
10644 
10645   Value *Result;
10646 
10647   // Must pass the shift amount needed to sign extend the loaded value prior
10648   // to performing a signed comparison for min/max. ShiftAmt is the number of
10649   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
10650   // is the number of bits to left+right shift the value in order to
10651   // sign-extend.
10652   if (AI->getOperation() == AtomicRMWInst::Min ||
10653       AI->getOperation() == AtomicRMWInst::Max) {
10654     const DataLayout &DL = AI->getModule()->getDataLayout();
10655     unsigned ValWidth =
10656         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
10657     Value *SextShamt =
10658         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
10659     Result = Builder.CreateCall(LrwOpScwLoop,
10660                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
10661   } else {
10662     Result =
10663         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
10664   }
10665 
10666   if (XLen == 64)
10667     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10668   return Result;
10669 }
10670 
10671 TargetLowering::AtomicExpansionKind
10672 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
10673     AtomicCmpXchgInst *CI) const {
10674   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
10675   if (Size == 8 || Size == 16)
10676     return AtomicExpansionKind::MaskedIntrinsic;
10677   return AtomicExpansionKind::None;
10678 }
10679 
10680 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
10681     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
10682     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
10683   unsigned XLen = Subtarget.getXLen();
10684   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
10685   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
10686   if (XLen == 64) {
10687     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
10688     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
10689     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
10690     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
10691   }
10692   Type *Tys[] = {AlignedAddr->getType()};
10693   Function *MaskedCmpXchg =
10694       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
10695   Value *Result = Builder.CreateCall(
10696       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
10697   if (XLen == 64)
10698     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
10699   return Result;
10700 }
10701 
10702 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
10703   return false;
10704 }
10705 
10706 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
10707                                                EVT VT) const {
10708   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
10709     return false;
10710 
10711   switch (FPVT.getSimpleVT().SimpleTy) {
10712   case MVT::f16:
10713     return Subtarget.hasStdExtZfh();
10714   case MVT::f32:
10715     return Subtarget.hasStdExtF();
10716   case MVT::f64:
10717     return Subtarget.hasStdExtD();
10718   default:
10719     return false;
10720   }
10721 }
10722 
10723 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
10724   // If we are using the small code model, we can reduce size of jump table
10725   // entry to 4 bytes.
10726   if (Subtarget.is64Bit() && !isPositionIndependent() &&
10727       getTargetMachine().getCodeModel() == CodeModel::Small) {
10728     return MachineJumpTableInfo::EK_Custom32;
10729   }
10730   return TargetLowering::getJumpTableEncoding();
10731 }
10732 
10733 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
10734     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
10735     unsigned uid, MCContext &Ctx) const {
10736   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
10737          getTargetMachine().getCodeModel() == CodeModel::Small);
10738   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
10739 }
10740 
10741 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
10742                                                      EVT VT) const {
10743   VT = VT.getScalarType();
10744 
10745   if (!VT.isSimple())
10746     return false;
10747 
10748   switch (VT.getSimpleVT().SimpleTy) {
10749   case MVT::f16:
10750     return Subtarget.hasStdExtZfh();
10751   case MVT::f32:
10752     return Subtarget.hasStdExtF();
10753   case MVT::f64:
10754     return Subtarget.hasStdExtD();
10755   default:
10756     break;
10757   }
10758 
10759   return false;
10760 }
10761 
10762 Register RISCVTargetLowering::getExceptionPointerRegister(
10763     const Constant *PersonalityFn) const {
10764   return RISCV::X10;
10765 }
10766 
10767 Register RISCVTargetLowering::getExceptionSelectorRegister(
10768     const Constant *PersonalityFn) const {
10769   return RISCV::X11;
10770 }
10771 
10772 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
10773   // Return false to suppress the unnecessary extensions if the LibCall
10774   // arguments or return value is f32 type for LP64 ABI.
10775   RISCVABI::ABI ABI = Subtarget.getTargetABI();
10776   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
10777     return false;
10778 
10779   return true;
10780 }
10781 
10782 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
10783   if (Subtarget.is64Bit() && Type == MVT::i32)
10784     return true;
10785 
10786   return IsSigned;
10787 }
10788 
10789 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
10790                                                  SDValue C) const {
10791   // Check integral scalar types.
10792   if (VT.isScalarInteger()) {
10793     // Omit the optimization if the sub target has the M extension and the data
10794     // size exceeds XLen.
10795     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
10796       return false;
10797     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
10798       // Break the MUL to a SLLI and an ADD/SUB.
10799       const APInt &Imm = ConstNode->getAPIntValue();
10800       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
10801           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
10802         return true;
10803       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
10804       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
10805           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
10806            (Imm - 8).isPowerOf2()))
10807         return true;
10808       // Omit the following optimization if the sub target has the M extension
10809       // and the data size >= XLen.
10810       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
10811         return false;
10812       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
10813       // a pair of LUI/ADDI.
10814       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
10815         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
10816         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
10817             (1 - ImmS).isPowerOf2())
10818         return true;
10819       }
10820     }
10821   }
10822 
10823   return false;
10824 }
10825 
10826 bool RISCVTargetLowering::isMulAddWithConstProfitable(
10827     const SDValue &AddNode, const SDValue &ConstNode) const {
10828   // Let the DAGCombiner decide for vectors.
10829   EVT VT = AddNode.getValueType();
10830   if (VT.isVector())
10831     return true;
10832 
10833   // Let the DAGCombiner decide for larger types.
10834   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
10835     return true;
10836 
10837   // It is worse if c1 is simm12 while c1*c2 is not.
10838   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
10839   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
10840   const APInt &C1 = C1Node->getAPIntValue();
10841   const APInt &C2 = C2Node->getAPIntValue();
10842   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
10843     return false;
10844 
10845   // Default to true and let the DAGCombiner decide.
10846   return true;
10847 }
10848 
10849 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
10850     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
10851     bool *Fast) const {
10852   if (!VT.isVector())
10853     return false;
10854 
10855   EVT ElemVT = VT.getVectorElementType();
10856   if (Alignment >= ElemVT.getStoreSize()) {
10857     if (Fast)
10858       *Fast = true;
10859     return true;
10860   }
10861 
10862   return false;
10863 }
10864 
10865 bool RISCVTargetLowering::splitValueIntoRegisterParts(
10866     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
10867     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
10868   bool IsABIRegCopy = CC.hasValue();
10869   EVT ValueVT = Val.getValueType();
10870   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10871     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
10872     // and cast to f32.
10873     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
10874     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
10875     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
10876                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
10877     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
10878     Parts[0] = Val;
10879     return true;
10880   }
10881 
10882   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10883     LLVMContext &Context = *DAG.getContext();
10884     EVT ValueEltVT = ValueVT.getVectorElementType();
10885     EVT PartEltVT = PartVT.getVectorElementType();
10886     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10887     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10888     if (PartVTBitSize % ValueVTBitSize == 0) {
10889       assert(PartVTBitSize >= ValueVTBitSize);
10890       // If the element types are different, bitcast to the same element type of
10891       // PartVT first.
10892       // Give an example here, we want copy a <vscale x 1 x i8> value to
10893       // <vscale x 4 x i16>.
10894       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
10895       // subvector, then we can bitcast to <vscale x 4 x i16>.
10896       if (ValueEltVT != PartEltVT) {
10897         if (PartVTBitSize > ValueVTBitSize) {
10898           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10899           assert(Count != 0 && "The number of element should not be zero.");
10900           EVT SameEltTypeVT =
10901               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10902           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
10903                             DAG.getUNDEF(SameEltTypeVT), Val,
10904                             DAG.getVectorIdxConstant(0, DL));
10905         }
10906         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
10907       } else {
10908         Val =
10909             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
10910                         Val, DAG.getVectorIdxConstant(0, DL));
10911       }
10912       Parts[0] = Val;
10913       return true;
10914     }
10915   }
10916   return false;
10917 }
10918 
10919 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
10920     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
10921     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
10922   bool IsABIRegCopy = CC.hasValue();
10923   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
10924     SDValue Val = Parts[0];
10925 
10926     // Cast the f32 to i32, truncate to i16, and cast back to f16.
10927     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
10928     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
10929     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
10930     return Val;
10931   }
10932 
10933   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
10934     LLVMContext &Context = *DAG.getContext();
10935     SDValue Val = Parts[0];
10936     EVT ValueEltVT = ValueVT.getVectorElementType();
10937     EVT PartEltVT = PartVT.getVectorElementType();
10938     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
10939     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
10940     if (PartVTBitSize % ValueVTBitSize == 0) {
10941       assert(PartVTBitSize >= ValueVTBitSize);
10942       EVT SameEltTypeVT = ValueVT;
10943       // If the element types are different, convert it to the same element type
10944       // of PartVT.
10945       // Give an example here, we want copy a <vscale x 1 x i8> value from
10946       // <vscale x 4 x i16>.
10947       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
10948       // then we can extract <vscale x 1 x i8>.
10949       if (ValueEltVT != PartEltVT) {
10950         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
10951         assert(Count != 0 && "The number of element should not be zero.");
10952         SameEltTypeVT =
10953             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
10954         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
10955       }
10956       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
10957                         DAG.getVectorIdxConstant(0, DL));
10958       return Val;
10959     }
10960   }
10961   return SDValue();
10962 }
10963 
10964 SDValue
10965 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
10966                                    SelectionDAG &DAG,
10967                                    SmallVectorImpl<SDNode *> &Created) const {
10968   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
10969   if (isIntDivCheap(N->getValueType(0), Attr))
10970     return SDValue(N, 0); // Lower SDIV as SDIV
10971 
10972   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
10973          "Unexpected divisor!");
10974 
10975   // Conditional move is needed, so do the transformation iff Zbt is enabled.
10976   if (!Subtarget.hasStdExtZbt())
10977     return SDValue();
10978 
10979   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
10980   // Besides, more critical path instructions will be generated when dividing
10981   // by 2. So we keep using the original DAGs for these cases.
10982   unsigned Lg2 = Divisor.countTrailingZeros();
10983   if (Lg2 == 1 || Lg2 >= 12)
10984     return SDValue();
10985 
10986   // fold (sdiv X, pow2)
10987   EVT VT = N->getValueType(0);
10988   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
10989     return SDValue();
10990 
10991   SDLoc DL(N);
10992   SDValue N0 = N->getOperand(0);
10993   SDValue Zero = DAG.getConstant(0, DL, VT);
10994   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
10995 
10996   // Add (N0 < 0) ? Pow2 - 1 : 0;
10997   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
10998   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
10999   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11000 
11001   Created.push_back(Cmp.getNode());
11002   Created.push_back(Add.getNode());
11003   Created.push_back(Sel.getNode());
11004 
11005   // Divide by pow2.
11006   SDValue SRA =
11007       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11008 
11009   // If we're dividing by a positive value, we're done.  Otherwise, we must
11010   // negate the result.
11011   if (Divisor.isNonNegative())
11012     return SRA;
11013 
11014   Created.push_back(SRA.getNode());
11015   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11016 }
11017 
11018 #define GET_REGISTER_MATCHER
11019 #include "RISCVGenAsmMatcher.inc"
11020 
11021 Register
11022 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11023                                        const MachineFunction &MF) const {
11024   Register Reg = MatchRegisterAltName(RegName);
11025   if (Reg == RISCV::NoRegister)
11026     Reg = MatchRegisterName(RegName);
11027   if (Reg == RISCV::NoRegister)
11028     report_fatal_error(
11029         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11030   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11031   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11032     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11033                              StringRef(RegName) + "\"."));
11034   return Reg;
11035 }
11036 
11037 namespace llvm {
11038 namespace RISCVVIntrinsicsTable {
11039 
11040 #define GET_RISCVVIntrinsicsTable_IMPL
11041 #include "RISCVGenSearchableTables.inc"
11042 
11043 } // namespace RISCVVIntrinsicsTable
11044 
11045 } // namespace llvm
11046