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     if (Subtarget.is64Bit())
308       setOperationAction(ISD::ABS, MVT::i32, Custom);
309   }
310 
311   if (Subtarget.hasStdExtZbt()) {
312     setOperationAction(ISD::FSHL, XLenVT, Custom);
313     setOperationAction(ISD::FSHR, XLenVT, Custom);
314     setOperationAction(ISD::SELECT, XLenVT, Legal);
315 
316     if (Subtarget.is64Bit()) {
317       setOperationAction(ISD::FSHL, MVT::i32, Custom);
318       setOperationAction(ISD::FSHR, MVT::i32, Custom);
319     }
320   } else {
321     setOperationAction(ISD::SELECT, XLenVT, Custom);
322   }
323 
324   static constexpr ISD::NodeType FPLegalNodeTypes[] = {
325       ISD::FMINNUM,        ISD::FMAXNUM,       ISD::LRINT,
326       ISD::LLRINT,         ISD::LROUND,        ISD::LLROUND,
327       ISD::STRICT_LRINT,   ISD::STRICT_LLRINT, ISD::STRICT_LROUND,
328       ISD::STRICT_LLROUND, ISD::STRICT_FMA,    ISD::STRICT_FADD,
329       ISD::STRICT_FSUB,    ISD::STRICT_FMUL,   ISD::STRICT_FDIV,
330       ISD::STRICT_FSQRT,   ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS};
331 
332   static const ISD::CondCode FPCCToExpand[] = {
333       ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
334       ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
335       ISD::SETGE,  ISD::SETNE,  ISD::SETO,   ISD::SETUO};
336 
337   static const ISD::NodeType FPOpToExpand[] = {
338       ISD::FSIN, ISD::FCOS,       ISD::FSINCOS,   ISD::FPOW,
339       ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
340 
341   if (Subtarget.hasStdExtZfh())
342     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
343 
344   if (Subtarget.hasStdExtZfh()) {
345     for (auto NT : FPLegalNodeTypes)
346       setOperationAction(NT, MVT::f16, Legal);
347     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
348     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
349     for (auto CC : FPCCToExpand)
350       setCondCodeAction(CC, MVT::f16, Expand);
351     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
352     setOperationAction(ISD::SELECT, MVT::f16, Custom);
353     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
354 
355     setOperationAction(ISD::FREM,       MVT::f16, Promote);
356     setOperationAction(ISD::FCEIL,      MVT::f16, Promote);
357     setOperationAction(ISD::FFLOOR,     MVT::f16, Promote);
358     setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
359     setOperationAction(ISD::FRINT,      MVT::f16, Promote);
360     setOperationAction(ISD::FROUND,     MVT::f16, Promote);
361     setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote);
362     setOperationAction(ISD::FTRUNC,     MVT::f16, Promote);
363     setOperationAction(ISD::FPOW,       MVT::f16, Promote);
364     setOperationAction(ISD::FPOWI,      MVT::f16, Promote);
365     setOperationAction(ISD::FCOS,       MVT::f16, Promote);
366     setOperationAction(ISD::FSIN,       MVT::f16, Promote);
367     setOperationAction(ISD::FSINCOS,    MVT::f16, Promote);
368     setOperationAction(ISD::FEXP,       MVT::f16, Promote);
369     setOperationAction(ISD::FEXP2,      MVT::f16, Promote);
370     setOperationAction(ISD::FLOG,       MVT::f16, Promote);
371     setOperationAction(ISD::FLOG2,      MVT::f16, Promote);
372     setOperationAction(ISD::FLOG10,     MVT::f16, Promote);
373 
374     // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
375     // complete support for all operations in LegalizeDAG.
376 
377     // We need to custom promote this.
378     if (Subtarget.is64Bit())
379       setOperationAction(ISD::FPOWI, MVT::i32, Custom);
380   }
381 
382   if (Subtarget.hasStdExtF()) {
383     for (auto NT : FPLegalNodeTypes)
384       setOperationAction(NT, MVT::f32, Legal);
385     for (auto CC : FPCCToExpand)
386       setCondCodeAction(CC, MVT::f32, Expand);
387     setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
388     setOperationAction(ISD::SELECT, MVT::f32, Custom);
389     setOperationAction(ISD::BR_CC, MVT::f32, Expand);
390     for (auto Op : FPOpToExpand)
391       setOperationAction(Op, MVT::f32, Expand);
392     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
393     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
394   }
395 
396   if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
397     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
398 
399   if (Subtarget.hasStdExtD()) {
400     for (auto NT : FPLegalNodeTypes)
401       setOperationAction(NT, MVT::f64, Legal);
402     setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
403     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
404     for (auto CC : FPCCToExpand)
405       setCondCodeAction(CC, MVT::f64, Expand);
406     setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
407     setOperationAction(ISD::SELECT, MVT::f64, Custom);
408     setOperationAction(ISD::BR_CC, MVT::f64, Expand);
409     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
410     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
411     for (auto Op : FPOpToExpand)
412       setOperationAction(Op, MVT::f64, Expand);
413     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
414     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
415   }
416 
417   if (Subtarget.is64Bit()) {
418     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
419     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
420     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
421     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
422   }
423 
424   if (Subtarget.hasStdExtF()) {
425     setOperationAction(ISD::FP_TO_UINT_SAT, XLenVT, Custom);
426     setOperationAction(ISD::FP_TO_SINT_SAT, XLenVT, Custom);
427 
428     setOperationAction(ISD::STRICT_FP_TO_UINT, XLenVT, Legal);
429     setOperationAction(ISD::STRICT_FP_TO_SINT, XLenVT, Legal);
430     setOperationAction(ISD::STRICT_UINT_TO_FP, XLenVT, Legal);
431     setOperationAction(ISD::STRICT_SINT_TO_FP, XLenVT, Legal);
432 
433     setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom);
434     setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
435   }
436 
437   setOperationAction(ISD::GlobalAddress, XLenVT, Custom);
438   setOperationAction(ISD::BlockAddress, XLenVT, Custom);
439   setOperationAction(ISD::ConstantPool, XLenVT, Custom);
440   setOperationAction(ISD::JumpTable, XLenVT, Custom);
441 
442   setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
443 
444   // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
445   // Unfortunately this can't be determined just from the ISA naming string.
446   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
447                      Subtarget.is64Bit() ? Legal : Custom);
448 
449   setOperationAction(ISD::TRAP, MVT::Other, Legal);
450   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
451   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
452   if (Subtarget.is64Bit())
453     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
454 
455   if (Subtarget.hasStdExtA()) {
456     setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
457     setMinCmpXchgSizeInBits(32);
458   } else {
459     setMaxAtomicSizeInBitsSupported(0);
460   }
461 
462   setBooleanContents(ZeroOrOneBooleanContent);
463 
464   if (Subtarget.hasVInstructions()) {
465     setBooleanVectorContents(ZeroOrOneBooleanContent);
466 
467     setOperationAction(ISD::VSCALE, XLenVT, Custom);
468 
469     // RVV intrinsics may have illegal operands.
470     // We also need to custom legalize vmv.x.s.
471     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
472     setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
473     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
474     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
475     if (Subtarget.is64Bit()) {
476       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
477     } else {
478       setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
479       setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
480     }
481 
482     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
483     setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
484 
485     static const unsigned IntegerVPOps[] = {
486         ISD::VP_ADD,         ISD::VP_SUB,         ISD::VP_MUL,
487         ISD::VP_SDIV,        ISD::VP_UDIV,        ISD::VP_SREM,
488         ISD::VP_UREM,        ISD::VP_AND,         ISD::VP_OR,
489         ISD::VP_XOR,         ISD::VP_ASHR,        ISD::VP_LSHR,
490         ISD::VP_SHL,         ISD::VP_REDUCE_ADD,  ISD::VP_REDUCE_AND,
491         ISD::VP_REDUCE_OR,   ISD::VP_REDUCE_XOR,  ISD::VP_REDUCE_SMAX,
492         ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
493         ISD::VP_MERGE,       ISD::VP_SELECT,      ISD::VP_FPTOSI,
494         ISD::VP_FPTOUI,      ISD::VP_SETCC,       ISD::VP_SEXT,
495         ISD::VP_ZEXT,        ISD::VP_TRUNC};
496 
497     static const unsigned FloatingPointVPOps[] = {
498         ISD::VP_FADD,        ISD::VP_FSUB,
499         ISD::VP_FMUL,        ISD::VP_FDIV,
500         ISD::VP_FNEG,        ISD::VP_FMA,
501         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
502         ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX,
503         ISD::VP_MERGE,       ISD::VP_SELECT,
504         ISD::VP_SITOFP,      ISD::VP_UITOFP,
505         ISD::VP_SETCC,       ISD::VP_FP_ROUND};
506 
507     if (!Subtarget.is64Bit()) {
508       // We must custom-lower certain vXi64 operations on RV32 due to the vector
509       // element type being illegal.
510       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
511       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
512 
513       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
514       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
515       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
516       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
517       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
518       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
519       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
520       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
521 
522       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
523       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
524       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
525       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
526       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
527       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
528       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
529       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
530     }
531 
532     for (MVT VT : BoolVecVTs) {
533       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
534 
535       // Mask VTs are custom-expanded into a series of standard nodes
536       setOperationAction(ISD::TRUNCATE, VT, Custom);
537       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
538       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
539       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
540 
541       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
542       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
543 
544       setOperationAction(ISD::SELECT, VT, Custom);
545       setOperationAction(ISD::SELECT_CC, VT, Expand);
546       setOperationAction(ISD::VSELECT, VT, Expand);
547       setOperationAction(ISD::VP_MERGE, VT, Expand);
548       setOperationAction(ISD::VP_SELECT, VT, Expand);
549 
550       setOperationAction(ISD::VP_AND, VT, Custom);
551       setOperationAction(ISD::VP_OR, VT, Custom);
552       setOperationAction(ISD::VP_XOR, VT, Custom);
553 
554       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
555       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
556       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
557 
558       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
559       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
560       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
561 
562       // RVV has native int->float & float->int conversions where the
563       // element type sizes are within one power-of-two of each other. Any
564       // wider distances between type sizes have to be lowered as sequences
565       // which progressively narrow the gap in stages.
566       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
567       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
568       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
569       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
570 
571       // Expand all extending loads to types larger than this, and truncating
572       // stores from types larger than this.
573       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
574         setTruncStoreAction(OtherVT, VT, Expand);
575         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
576         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
577         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
578       }
579 
580       setOperationAction(ISD::VP_FPTOSI, VT, Custom);
581       setOperationAction(ISD::VP_FPTOUI, VT, Custom);
582       setOperationAction(ISD::VP_TRUNC, VT, Custom);
583     }
584 
585     for (MVT VT : IntVecVTs) {
586       if (VT.getVectorElementType() == MVT::i64 &&
587           !Subtarget.hasVInstructionsI64())
588         continue;
589 
590       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
591       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
592 
593       // Vectors implement MULHS/MULHU.
594       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
595       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
596 
597       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
598       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) {
599         setOperationAction(ISD::MULHU, VT, Expand);
600         setOperationAction(ISD::MULHS, VT, Expand);
601       }
602 
603       setOperationAction(ISD::SMIN, VT, Legal);
604       setOperationAction(ISD::SMAX, VT, Legal);
605       setOperationAction(ISD::UMIN, VT, Legal);
606       setOperationAction(ISD::UMAX, VT, Legal);
607 
608       setOperationAction(ISD::ROTL, VT, Expand);
609       setOperationAction(ISD::ROTR, VT, Expand);
610 
611       setOperationAction(ISD::CTTZ, VT, Expand);
612       setOperationAction(ISD::CTLZ, VT, Expand);
613       setOperationAction(ISD::CTPOP, VT, Expand);
614 
615       setOperationAction(ISD::BSWAP, VT, Expand);
616 
617       // Custom-lower extensions and truncations from/to mask types.
618       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
619       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
620       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
621 
622       // RVV has native int->float & float->int conversions where the
623       // element type sizes are within one power-of-two of each other. Any
624       // wider distances between type sizes have to be lowered as sequences
625       // which progressively narrow the gap in stages.
626       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
627       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
628       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
629       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
630 
631       setOperationAction(ISD::SADDSAT, VT, Legal);
632       setOperationAction(ISD::UADDSAT, VT, Legal);
633       setOperationAction(ISD::SSUBSAT, VT, Legal);
634       setOperationAction(ISD::USUBSAT, VT, Legal);
635 
636       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
637       // nodes which truncate by one power of two at a time.
638       setOperationAction(ISD::TRUNCATE, VT, Custom);
639 
640       // Custom-lower insert/extract operations to simplify patterns.
641       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
642       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
643 
644       // Custom-lower reduction operations to set up the corresponding custom
645       // nodes' operands.
646       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
647       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
648       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
649       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
650       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
651       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
652       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
653       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
654 
655       for (unsigned VPOpc : IntegerVPOps)
656         setOperationAction(VPOpc, VT, Custom);
657 
658       setOperationAction(ISD::LOAD, VT, Custom);
659       setOperationAction(ISD::STORE, VT, Custom);
660 
661       setOperationAction(ISD::MLOAD, VT, Custom);
662       setOperationAction(ISD::MSTORE, VT, Custom);
663       setOperationAction(ISD::MGATHER, VT, Custom);
664       setOperationAction(ISD::MSCATTER, VT, Custom);
665 
666       setOperationAction(ISD::VP_LOAD, VT, Custom);
667       setOperationAction(ISD::VP_STORE, VT, Custom);
668       setOperationAction(ISD::VP_GATHER, VT, Custom);
669       setOperationAction(ISD::VP_SCATTER, VT, Custom);
670 
671       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
672       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
673       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
674 
675       setOperationAction(ISD::SELECT, VT, Custom);
676       setOperationAction(ISD::SELECT_CC, VT, Expand);
677 
678       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
679       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
680 
681       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
682         setTruncStoreAction(VT, OtherVT, Expand);
683         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
684         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
685         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
686       }
687 
688       // Splice
689       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
690 
691       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
692       // type that can represent the value exactly.
693       if (VT.getVectorElementType() != MVT::i64) {
694         MVT FloatEltVT =
695             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
696         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
697         if (isTypeLegal(FloatVT)) {
698           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
699           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
700         }
701       }
702     }
703 
704     // Expand various CCs to best match the RVV ISA, which natively supports UNE
705     // but no other unordered comparisons, and supports all ordered comparisons
706     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
707     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
708     // and we pattern-match those back to the "original", swapping operands once
709     // more. This way we catch both operations and both "vf" and "fv" forms with
710     // fewer patterns.
711     static const ISD::CondCode VFPCCToExpand[] = {
712         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
713         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
714         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
715     };
716 
717     // Sets common operation actions on RVV floating-point vector types.
718     const auto SetCommonVFPActions = [&](MVT VT) {
719       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
720       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
721       // sizes are within one power-of-two of each other. Therefore conversions
722       // between vXf16 and vXf64 must be lowered as sequences which convert via
723       // vXf32.
724       setOperationAction(ISD::FP_ROUND, VT, Custom);
725       setOperationAction(ISD::FP_EXTEND, VT, Custom);
726       // Custom-lower insert/extract operations to simplify patterns.
727       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
728       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
729       // Expand various condition codes (explained above).
730       for (auto CC : VFPCCToExpand)
731         setCondCodeAction(CC, VT, Expand);
732 
733       setOperationAction(ISD::FMINNUM, VT, Legal);
734       setOperationAction(ISD::FMAXNUM, VT, Legal);
735 
736       setOperationAction(ISD::FTRUNC, VT, Custom);
737       setOperationAction(ISD::FCEIL, VT, Custom);
738       setOperationAction(ISD::FFLOOR, VT, Custom);
739       setOperationAction(ISD::FROUND, VT, Custom);
740 
741       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
742       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
743       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
744       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
745 
746       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
747 
748       setOperationAction(ISD::LOAD, VT, Custom);
749       setOperationAction(ISD::STORE, VT, Custom);
750 
751       setOperationAction(ISD::MLOAD, VT, Custom);
752       setOperationAction(ISD::MSTORE, VT, Custom);
753       setOperationAction(ISD::MGATHER, VT, Custom);
754       setOperationAction(ISD::MSCATTER, VT, Custom);
755 
756       setOperationAction(ISD::VP_LOAD, VT, Custom);
757       setOperationAction(ISD::VP_STORE, VT, Custom);
758       setOperationAction(ISD::VP_GATHER, VT, Custom);
759       setOperationAction(ISD::VP_SCATTER, VT, Custom);
760 
761       setOperationAction(ISD::SELECT, VT, Custom);
762       setOperationAction(ISD::SELECT_CC, VT, Expand);
763 
764       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
765       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
766       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
767 
768       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
769       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
770 
771       for (unsigned VPOpc : FloatingPointVPOps)
772         setOperationAction(VPOpc, VT, Custom);
773     };
774 
775     // Sets common extload/truncstore actions on RVV floating-point vector
776     // types.
777     const auto SetCommonVFPExtLoadTruncStoreActions =
778         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
779           for (auto SmallVT : SmallerVTs) {
780             setTruncStoreAction(VT, SmallVT, Expand);
781             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
782           }
783         };
784 
785     if (Subtarget.hasVInstructionsF16())
786       for (MVT VT : F16VecVTs)
787         SetCommonVFPActions(VT);
788 
789     for (MVT VT : F32VecVTs) {
790       if (Subtarget.hasVInstructionsF32())
791         SetCommonVFPActions(VT);
792       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
793     }
794 
795     for (MVT VT : F64VecVTs) {
796       if (Subtarget.hasVInstructionsF64())
797         SetCommonVFPActions(VT);
798       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
799       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
800     }
801 
802     if (Subtarget.useRVVForFixedLengthVectors()) {
803       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
804         if (!useRVVForFixedLengthVectorVT(VT))
805           continue;
806 
807         // By default everything must be expanded.
808         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
809           setOperationAction(Op, VT, Expand);
810         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
811           setTruncStoreAction(VT, OtherVT, Expand);
812           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
813           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
814           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
815         }
816 
817         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
818         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
819         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
820 
821         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
822         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
823 
824         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
825         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
826 
827         setOperationAction(ISD::LOAD, VT, Custom);
828         setOperationAction(ISD::STORE, VT, Custom);
829 
830         setOperationAction(ISD::SETCC, VT, Custom);
831 
832         setOperationAction(ISD::SELECT, VT, Custom);
833 
834         setOperationAction(ISD::TRUNCATE, VT, Custom);
835 
836         setOperationAction(ISD::BITCAST, VT, Custom);
837 
838         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
839         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
840         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
841 
842         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
843         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
844         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
845 
846         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
847         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
848         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
849         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
850 
851         // Operations below are different for between masks and other vectors.
852         if (VT.getVectorElementType() == MVT::i1) {
853           setOperationAction(ISD::VP_AND, VT, Custom);
854           setOperationAction(ISD::VP_OR, VT, Custom);
855           setOperationAction(ISD::VP_XOR, VT, Custom);
856           setOperationAction(ISD::AND, VT, Custom);
857           setOperationAction(ISD::OR, VT, Custom);
858           setOperationAction(ISD::XOR, VT, Custom);
859 
860           setOperationAction(ISD::VP_FPTOSI, VT, Custom);
861           setOperationAction(ISD::VP_FPTOUI, VT, Custom);
862           setOperationAction(ISD::VP_SETCC, VT, Custom);
863           setOperationAction(ISD::VP_TRUNC, VT, Custom);
864           continue;
865         }
866 
867         // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
868         // it before type legalization for i64 vectors on RV32. It will then be
869         // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
870         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
871         // improvements first.
872         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
873           setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
874           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
875         }
876 
877         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
878         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
879 
880         setOperationAction(ISD::MLOAD, VT, Custom);
881         setOperationAction(ISD::MSTORE, VT, Custom);
882         setOperationAction(ISD::MGATHER, VT, Custom);
883         setOperationAction(ISD::MSCATTER, VT, Custom);
884 
885         setOperationAction(ISD::VP_LOAD, VT, Custom);
886         setOperationAction(ISD::VP_STORE, VT, Custom);
887         setOperationAction(ISD::VP_GATHER, VT, Custom);
888         setOperationAction(ISD::VP_SCATTER, VT, Custom);
889 
890         setOperationAction(ISD::ADD, VT, Custom);
891         setOperationAction(ISD::MUL, VT, Custom);
892         setOperationAction(ISD::SUB, VT, Custom);
893         setOperationAction(ISD::AND, VT, Custom);
894         setOperationAction(ISD::OR, VT, Custom);
895         setOperationAction(ISD::XOR, VT, Custom);
896         setOperationAction(ISD::SDIV, VT, Custom);
897         setOperationAction(ISD::SREM, VT, Custom);
898         setOperationAction(ISD::UDIV, VT, Custom);
899         setOperationAction(ISD::UREM, VT, Custom);
900         setOperationAction(ISD::SHL, VT, Custom);
901         setOperationAction(ISD::SRA, VT, Custom);
902         setOperationAction(ISD::SRL, VT, Custom);
903 
904         setOperationAction(ISD::SMIN, VT, Custom);
905         setOperationAction(ISD::SMAX, VT, Custom);
906         setOperationAction(ISD::UMIN, VT, Custom);
907         setOperationAction(ISD::UMAX, VT, Custom);
908         setOperationAction(ISD::ABS,  VT, Custom);
909 
910         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
911         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) {
912           setOperationAction(ISD::MULHS, VT, Custom);
913           setOperationAction(ISD::MULHU, VT, Custom);
914         }
915 
916         setOperationAction(ISD::SADDSAT, VT, Custom);
917         setOperationAction(ISD::UADDSAT, VT, Custom);
918         setOperationAction(ISD::SSUBSAT, VT, Custom);
919         setOperationAction(ISD::USUBSAT, VT, Custom);
920 
921         setOperationAction(ISD::VSELECT, VT, Custom);
922         setOperationAction(ISD::SELECT_CC, VT, Expand);
923 
924         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
925         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
926         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
927 
928         // Custom-lower reduction operations to set up the corresponding custom
929         // nodes' operands.
930         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
931         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
932         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
933         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
934         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
935 
936         for (unsigned VPOpc : IntegerVPOps)
937           setOperationAction(VPOpc, VT, Custom);
938 
939         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
940         // type that can represent the value exactly.
941         if (VT.getVectorElementType() != MVT::i64) {
942           MVT FloatEltVT =
943               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
944           EVT FloatVT =
945               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
946           if (isTypeLegal(FloatVT)) {
947             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
948             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
949           }
950         }
951       }
952 
953       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
954         if (!useRVVForFixedLengthVectorVT(VT))
955           continue;
956 
957         // By default everything must be expanded.
958         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
959           setOperationAction(Op, VT, Expand);
960         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
961           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
962           setTruncStoreAction(VT, OtherVT, Expand);
963         }
964 
965         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
966         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
967         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
968 
969         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
970         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
971         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
972         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
973         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
974 
975         setOperationAction(ISD::LOAD, VT, Custom);
976         setOperationAction(ISD::STORE, VT, Custom);
977         setOperationAction(ISD::MLOAD, VT, Custom);
978         setOperationAction(ISD::MSTORE, VT, Custom);
979         setOperationAction(ISD::MGATHER, VT, Custom);
980         setOperationAction(ISD::MSCATTER, VT, Custom);
981 
982         setOperationAction(ISD::VP_LOAD, VT, Custom);
983         setOperationAction(ISD::VP_STORE, VT, Custom);
984         setOperationAction(ISD::VP_GATHER, VT, Custom);
985         setOperationAction(ISD::VP_SCATTER, VT, Custom);
986 
987         setOperationAction(ISD::FADD, VT, Custom);
988         setOperationAction(ISD::FSUB, VT, Custom);
989         setOperationAction(ISD::FMUL, VT, Custom);
990         setOperationAction(ISD::FDIV, VT, Custom);
991         setOperationAction(ISD::FNEG, VT, Custom);
992         setOperationAction(ISD::FABS, VT, Custom);
993         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
994         setOperationAction(ISD::FSQRT, VT, Custom);
995         setOperationAction(ISD::FMA, VT, Custom);
996         setOperationAction(ISD::FMINNUM, VT, Custom);
997         setOperationAction(ISD::FMAXNUM, VT, Custom);
998 
999         setOperationAction(ISD::FP_ROUND, VT, Custom);
1000         setOperationAction(ISD::FP_EXTEND, VT, Custom);
1001 
1002         setOperationAction(ISD::FTRUNC, VT, Custom);
1003         setOperationAction(ISD::FCEIL, VT, Custom);
1004         setOperationAction(ISD::FFLOOR, VT, Custom);
1005         setOperationAction(ISD::FROUND, VT, Custom);
1006 
1007         for (auto CC : VFPCCToExpand)
1008           setCondCodeAction(CC, VT, Expand);
1009 
1010         setOperationAction(ISD::VSELECT, VT, Custom);
1011         setOperationAction(ISD::SELECT, VT, Custom);
1012         setOperationAction(ISD::SELECT_CC, VT, Expand);
1013 
1014         setOperationAction(ISD::BITCAST, VT, Custom);
1015 
1016         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1017         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1018         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1019         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1020 
1021         for (unsigned VPOpc : FloatingPointVPOps)
1022           setOperationAction(VPOpc, VT, Custom);
1023       }
1024 
1025       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1026       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1027       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1028       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
1029       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1030       if (Subtarget.hasStdExtZfh())
1031         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
1032       if (Subtarget.hasStdExtF())
1033         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
1034       if (Subtarget.hasStdExtD())
1035         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
1036     }
1037   }
1038 
1039   // Function alignments.
1040   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
1041   setMinFunctionAlignment(FunctionAlignment);
1042   setPrefFunctionAlignment(FunctionAlignment);
1043 
1044   setMinimumJumpTableEntries(5);
1045 
1046   // Jumps are expensive, compared to logic
1047   setJumpIsExpensive();
1048 
1049   setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND,
1050                        ISD::OR, ISD::XOR});
1051 
1052   if (Subtarget.hasStdExtZbp())
1053     setTargetDAGCombine({ISD::ROTL, ISD::ROTR});
1054   if (Subtarget.hasStdExtZbkb())
1055     setTargetDAGCombine(ISD::BITREVERSE);
1056   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
1057     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1058   if (Subtarget.hasStdExtF())
1059     setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
1060                          ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT});
1061   if (Subtarget.hasVInstructions())
1062     setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER,
1063                          ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL,
1064                          ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR});
1065 
1066   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
1067   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
1068 }
1069 
1070 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1071                                             LLVMContext &Context,
1072                                             EVT VT) const {
1073   if (!VT.isVector())
1074     return getPointerTy(DL);
1075   if (Subtarget.hasVInstructions() &&
1076       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1077     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1078   return VT.changeVectorElementTypeToInteger();
1079 }
1080 
1081 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1082   return Subtarget.getXLenVT();
1083 }
1084 
1085 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1086                                              const CallInst &I,
1087                                              MachineFunction &MF,
1088                                              unsigned Intrinsic) const {
1089   auto &DL = I.getModule()->getDataLayout();
1090   switch (Intrinsic) {
1091   default:
1092     return false;
1093   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1094   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1095   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1096   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1097   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1098   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1099   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1100   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1101   case Intrinsic::riscv_masked_cmpxchg_i32:
1102     Info.opc = ISD::INTRINSIC_W_CHAIN;
1103     Info.memVT = MVT::i32;
1104     Info.ptrVal = I.getArgOperand(0);
1105     Info.offset = 0;
1106     Info.align = Align(4);
1107     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1108                  MachineMemOperand::MOVolatile;
1109     return true;
1110   case Intrinsic::riscv_masked_strided_load:
1111     Info.opc = ISD::INTRINSIC_W_CHAIN;
1112     Info.ptrVal = I.getArgOperand(1);
1113     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1114     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1115     Info.size = MemoryLocation::UnknownSize;
1116     Info.flags |= MachineMemOperand::MOLoad;
1117     return true;
1118   case Intrinsic::riscv_masked_strided_store:
1119     Info.opc = ISD::INTRINSIC_VOID;
1120     Info.ptrVal = I.getArgOperand(1);
1121     Info.memVT =
1122         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1123     Info.align = Align(
1124         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1125         8);
1126     Info.size = MemoryLocation::UnknownSize;
1127     Info.flags |= MachineMemOperand::MOStore;
1128     return true;
1129   case Intrinsic::riscv_seg2_load:
1130   case Intrinsic::riscv_seg3_load:
1131   case Intrinsic::riscv_seg4_load:
1132   case Intrinsic::riscv_seg5_load:
1133   case Intrinsic::riscv_seg6_load:
1134   case Intrinsic::riscv_seg7_load:
1135   case Intrinsic::riscv_seg8_load:
1136     Info.opc = ISD::INTRINSIC_W_CHAIN;
1137     Info.ptrVal = I.getArgOperand(0);
1138     Info.memVT =
1139         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
1140     Info.align =
1141         Align(DL.getTypeSizeInBits(
1142                   I.getType()->getStructElementType(0)->getScalarType()) /
1143               8);
1144     Info.size = MemoryLocation::UnknownSize;
1145     Info.flags |= MachineMemOperand::MOLoad;
1146     return true;
1147   }
1148 }
1149 
1150 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1151                                                 const AddrMode &AM, Type *Ty,
1152                                                 unsigned AS,
1153                                                 Instruction *I) const {
1154   // No global is ever allowed as a base.
1155   if (AM.BaseGV)
1156     return false;
1157 
1158   // Require a 12-bit signed offset.
1159   if (!isInt<12>(AM.BaseOffs))
1160     return false;
1161 
1162   switch (AM.Scale) {
1163   case 0: // "r+i" or just "i", depending on HasBaseReg.
1164     break;
1165   case 1:
1166     if (!AM.HasBaseReg) // allow "r+i".
1167       break;
1168     return false; // disallow "r+r" or "r+r+i".
1169   default:
1170     return false;
1171   }
1172 
1173   return true;
1174 }
1175 
1176 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1177   return isInt<12>(Imm);
1178 }
1179 
1180 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1181   return isInt<12>(Imm);
1182 }
1183 
1184 // On RV32, 64-bit integers are split into their high and low parts and held
1185 // in two different registers, so the trunc is free since the low register can
1186 // just be used.
1187 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1188   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1189     return false;
1190   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1191   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1192   return (SrcBits == 64 && DestBits == 32);
1193 }
1194 
1195 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1196   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1197       !SrcVT.isInteger() || !DstVT.isInteger())
1198     return false;
1199   unsigned SrcBits = SrcVT.getSizeInBits();
1200   unsigned DestBits = DstVT.getSizeInBits();
1201   return (SrcBits == 64 && DestBits == 32);
1202 }
1203 
1204 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1205   // Zexts are free if they can be combined with a load.
1206   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1207   // poorly with type legalization of compares preferring sext.
1208   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1209     EVT MemVT = LD->getMemoryVT();
1210     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1211         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1212          LD->getExtensionType() == ISD::ZEXTLOAD))
1213       return true;
1214   }
1215 
1216   return TargetLowering::isZExtFree(Val, VT2);
1217 }
1218 
1219 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1220   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1221 }
1222 
1223 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const {
1224   return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
1225 }
1226 
1227 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1228   return Subtarget.hasStdExtZbb();
1229 }
1230 
1231 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1232   return Subtarget.hasStdExtZbb();
1233 }
1234 
1235 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1236   EVT VT = Y.getValueType();
1237 
1238   // FIXME: Support vectors once we have tests.
1239   if (VT.isVector())
1240     return false;
1241 
1242   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1243           Subtarget.hasStdExtZbkb()) &&
1244          !isa<ConstantSDNode>(Y);
1245 }
1246 
1247 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
1248   // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1249   auto *C = dyn_cast<ConstantSDNode>(Y);
1250   return C && C->getAPIntValue().ule(10);
1251 }
1252 
1253 /// Check if sinking \p I's operands to I's basic block is profitable, because
1254 /// the operands can be folded into a target instruction, e.g.
1255 /// splats of scalars can fold into vector instructions.
1256 bool RISCVTargetLowering::shouldSinkOperands(
1257     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1258   using namespace llvm::PatternMatch;
1259 
1260   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1261     return false;
1262 
1263   auto IsSinker = [&](Instruction *I, int Operand) {
1264     switch (I->getOpcode()) {
1265     case Instruction::Add:
1266     case Instruction::Sub:
1267     case Instruction::Mul:
1268     case Instruction::And:
1269     case Instruction::Or:
1270     case Instruction::Xor:
1271     case Instruction::FAdd:
1272     case Instruction::FSub:
1273     case Instruction::FMul:
1274     case Instruction::FDiv:
1275     case Instruction::ICmp:
1276     case Instruction::FCmp:
1277       return true;
1278     case Instruction::Shl:
1279     case Instruction::LShr:
1280     case Instruction::AShr:
1281     case Instruction::UDiv:
1282     case Instruction::SDiv:
1283     case Instruction::URem:
1284     case Instruction::SRem:
1285       return Operand == 1;
1286     case Instruction::Call:
1287       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1288         switch (II->getIntrinsicID()) {
1289         case Intrinsic::fma:
1290         case Intrinsic::vp_fma:
1291           return Operand == 0 || Operand == 1;
1292         // FIXME: Our patterns can only match vx/vf instructions when the splat
1293         // it on the RHS, because TableGen doesn't recognize our VP operations
1294         // as commutative.
1295         case Intrinsic::vp_add:
1296         case Intrinsic::vp_mul:
1297         case Intrinsic::vp_and:
1298         case Intrinsic::vp_or:
1299         case Intrinsic::vp_xor:
1300         case Intrinsic::vp_fadd:
1301         case Intrinsic::vp_fmul:
1302         case Intrinsic::vp_shl:
1303         case Intrinsic::vp_lshr:
1304         case Intrinsic::vp_ashr:
1305         case Intrinsic::vp_udiv:
1306         case Intrinsic::vp_sdiv:
1307         case Intrinsic::vp_urem:
1308         case Intrinsic::vp_srem:
1309           return Operand == 1;
1310         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1311         // explicit patterns for both LHS and RHS (as 'vr' versions).
1312         case Intrinsic::vp_sub:
1313         case Intrinsic::vp_fsub:
1314         case Intrinsic::vp_fdiv:
1315           return Operand == 0 || Operand == 1;
1316         default:
1317           return false;
1318         }
1319       }
1320       return false;
1321     default:
1322       return false;
1323     }
1324   };
1325 
1326   for (auto OpIdx : enumerate(I->operands())) {
1327     if (!IsSinker(I, OpIdx.index()))
1328       continue;
1329 
1330     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1331     // Make sure we are not already sinking this operand
1332     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1333       continue;
1334 
1335     // We are looking for a splat that can be sunk.
1336     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1337                              m_Undef(), m_ZeroMask())))
1338       continue;
1339 
1340     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1341     // and vector registers
1342     for (Use &U : Op->uses()) {
1343       Instruction *Insn = cast<Instruction>(U.getUser());
1344       if (!IsSinker(Insn, U.getOperandNo()))
1345         return false;
1346     }
1347 
1348     Ops.push_back(&Op->getOperandUse(0));
1349     Ops.push_back(&OpIdx.value());
1350   }
1351   return true;
1352 }
1353 
1354 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1355                                        bool ForCodeSize) const {
1356   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1357   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1358     return false;
1359   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1360     return false;
1361   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1362     return false;
1363   return Imm.isZero();
1364 }
1365 
1366 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1367   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1368          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1369          (VT == MVT::f64 && Subtarget.hasStdExtD());
1370 }
1371 
1372 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1373                                                       CallingConv::ID CC,
1374                                                       EVT VT) const {
1375   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1376   // We might still end up using a GPR but that will be decided based on ABI.
1377   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1378   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1379     return MVT::f32;
1380 
1381   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1382 }
1383 
1384 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1385                                                            CallingConv::ID CC,
1386                                                            EVT VT) const {
1387   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1388   // We might still end up using a GPR but that will be decided based on ABI.
1389   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1390   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1391     return 1;
1392 
1393   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1394 }
1395 
1396 // Changes the condition code and swaps operands if necessary, so the SetCC
1397 // operation matches one of the comparisons supported directly by branches
1398 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1399 // with 1/-1.
1400 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1401                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1402   // Convert X > -1 to X >= 0.
1403   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1404     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1405     CC = ISD::SETGE;
1406     return;
1407   }
1408   // Convert X < 1 to 0 >= X.
1409   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1410     RHS = LHS;
1411     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1412     CC = ISD::SETGE;
1413     return;
1414   }
1415 
1416   switch (CC) {
1417   default:
1418     break;
1419   case ISD::SETGT:
1420   case ISD::SETLE:
1421   case ISD::SETUGT:
1422   case ISD::SETULE:
1423     CC = ISD::getSetCCSwappedOperands(CC);
1424     std::swap(LHS, RHS);
1425     break;
1426   }
1427 }
1428 
1429 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1430   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1431   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1432   if (VT.getVectorElementType() == MVT::i1)
1433     KnownSize *= 8;
1434 
1435   switch (KnownSize) {
1436   default:
1437     llvm_unreachable("Invalid LMUL.");
1438   case 8:
1439     return RISCVII::VLMUL::LMUL_F8;
1440   case 16:
1441     return RISCVII::VLMUL::LMUL_F4;
1442   case 32:
1443     return RISCVII::VLMUL::LMUL_F2;
1444   case 64:
1445     return RISCVII::VLMUL::LMUL_1;
1446   case 128:
1447     return RISCVII::VLMUL::LMUL_2;
1448   case 256:
1449     return RISCVII::VLMUL::LMUL_4;
1450   case 512:
1451     return RISCVII::VLMUL::LMUL_8;
1452   }
1453 }
1454 
1455 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1456   switch (LMul) {
1457   default:
1458     llvm_unreachable("Invalid LMUL.");
1459   case RISCVII::VLMUL::LMUL_F8:
1460   case RISCVII::VLMUL::LMUL_F4:
1461   case RISCVII::VLMUL::LMUL_F2:
1462   case RISCVII::VLMUL::LMUL_1:
1463     return RISCV::VRRegClassID;
1464   case RISCVII::VLMUL::LMUL_2:
1465     return RISCV::VRM2RegClassID;
1466   case RISCVII::VLMUL::LMUL_4:
1467     return RISCV::VRM4RegClassID;
1468   case RISCVII::VLMUL::LMUL_8:
1469     return RISCV::VRM8RegClassID;
1470   }
1471 }
1472 
1473 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1474   RISCVII::VLMUL LMUL = getLMUL(VT);
1475   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1476       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1477       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1478       LMUL == RISCVII::VLMUL::LMUL_1) {
1479     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1480                   "Unexpected subreg numbering");
1481     return RISCV::sub_vrm1_0 + Index;
1482   }
1483   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1484     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1485                   "Unexpected subreg numbering");
1486     return RISCV::sub_vrm2_0 + Index;
1487   }
1488   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1489     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1490                   "Unexpected subreg numbering");
1491     return RISCV::sub_vrm4_0 + Index;
1492   }
1493   llvm_unreachable("Invalid vector type.");
1494 }
1495 
1496 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1497   if (VT.getVectorElementType() == MVT::i1)
1498     return RISCV::VRRegClassID;
1499   return getRegClassIDForLMUL(getLMUL(VT));
1500 }
1501 
1502 // Attempt to decompose a subvector insert/extract between VecVT and
1503 // SubVecVT via subregister indices. Returns the subregister index that
1504 // can perform the subvector insert/extract with the given element index, as
1505 // well as the index corresponding to any leftover subvectors that must be
1506 // further inserted/extracted within the register class for SubVecVT.
1507 std::pair<unsigned, unsigned>
1508 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1509     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1510     const RISCVRegisterInfo *TRI) {
1511   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1512                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1513                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1514                 "Register classes not ordered");
1515   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1516   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1517   // Try to compose a subregister index that takes us from the incoming
1518   // LMUL>1 register class down to the outgoing one. At each step we half
1519   // the LMUL:
1520   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1521   // Note that this is not guaranteed to find a subregister index, such as
1522   // when we are extracting from one VR type to another.
1523   unsigned SubRegIdx = RISCV::NoSubRegister;
1524   for (const unsigned RCID :
1525        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1526     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1527       VecVT = VecVT.getHalfNumVectorElementsVT();
1528       bool IsHi =
1529           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1530       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1531                                             getSubregIndexByMVT(VecVT, IsHi));
1532       if (IsHi)
1533         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1534     }
1535   return {SubRegIdx, InsertExtractIdx};
1536 }
1537 
1538 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1539 // stores for those types.
1540 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1541   return !Subtarget.useRVVForFixedLengthVectors() ||
1542          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1543 }
1544 
1545 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1546   if (ScalarTy->isPointerTy())
1547     return true;
1548 
1549   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1550       ScalarTy->isIntegerTy(32))
1551     return true;
1552 
1553   if (ScalarTy->isIntegerTy(64))
1554     return Subtarget.hasVInstructionsI64();
1555 
1556   if (ScalarTy->isHalfTy())
1557     return Subtarget.hasVInstructionsF16();
1558   if (ScalarTy->isFloatTy())
1559     return Subtarget.hasVInstructionsF32();
1560   if (ScalarTy->isDoubleTy())
1561     return Subtarget.hasVInstructionsF64();
1562 
1563   return false;
1564 }
1565 
1566 static SDValue getVLOperand(SDValue Op) {
1567   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1568           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1569          "Unexpected opcode");
1570   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1571   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1572   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1573       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1574   if (!II)
1575     return SDValue();
1576   return Op.getOperand(II->VLOperand + 1 + HasChain);
1577 }
1578 
1579 static bool useRVVForFixedLengthVectorVT(MVT VT,
1580                                          const RISCVSubtarget &Subtarget) {
1581   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1582   if (!Subtarget.useRVVForFixedLengthVectors())
1583     return false;
1584 
1585   // We only support a set of vector types with a consistent maximum fixed size
1586   // across all supported vector element types to avoid legalization issues.
1587   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1588   // fixed-length vector type we support is 1024 bytes.
1589   if (VT.getFixedSizeInBits() > 1024 * 8)
1590     return false;
1591 
1592   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1593 
1594   MVT EltVT = VT.getVectorElementType();
1595 
1596   // Don't use RVV for vectors we cannot scalarize if required.
1597   switch (EltVT.SimpleTy) {
1598   // i1 is supported but has different rules.
1599   default:
1600     return false;
1601   case MVT::i1:
1602     // Masks can only use a single register.
1603     if (VT.getVectorNumElements() > MinVLen)
1604       return false;
1605     MinVLen /= 8;
1606     break;
1607   case MVT::i8:
1608   case MVT::i16:
1609   case MVT::i32:
1610     break;
1611   case MVT::i64:
1612     if (!Subtarget.hasVInstructionsI64())
1613       return false;
1614     break;
1615   case MVT::f16:
1616     if (!Subtarget.hasVInstructionsF16())
1617       return false;
1618     break;
1619   case MVT::f32:
1620     if (!Subtarget.hasVInstructionsF32())
1621       return false;
1622     break;
1623   case MVT::f64:
1624     if (!Subtarget.hasVInstructionsF64())
1625       return false;
1626     break;
1627   }
1628 
1629   // Reject elements larger than ELEN.
1630   if (EltVT.getSizeInBits() > Subtarget.getELEN())
1631     return false;
1632 
1633   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1634   // Don't use RVV for types that don't fit.
1635   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1636     return false;
1637 
1638   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1639   // the base fixed length RVV support in place.
1640   if (!VT.isPow2VectorType())
1641     return false;
1642 
1643   return true;
1644 }
1645 
1646 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1647   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1648 }
1649 
1650 // Return the largest legal scalable vector type that matches VT's element type.
1651 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1652                                             const RISCVSubtarget &Subtarget) {
1653   // This may be called before legal types are setup.
1654   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1655           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1656          "Expected legal fixed length vector!");
1657 
1658   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1659   unsigned MaxELen = Subtarget.getELEN();
1660 
1661   MVT EltVT = VT.getVectorElementType();
1662   switch (EltVT.SimpleTy) {
1663   default:
1664     llvm_unreachable("unexpected element type for RVV container");
1665   case MVT::i1:
1666   case MVT::i8:
1667   case MVT::i16:
1668   case MVT::i32:
1669   case MVT::i64:
1670   case MVT::f16:
1671   case MVT::f32:
1672   case MVT::f64: {
1673     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1674     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1675     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1676     unsigned NumElts =
1677         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1678     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1679     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1680     return MVT::getScalableVectorVT(EltVT, NumElts);
1681   }
1682   }
1683 }
1684 
1685 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1686                                             const RISCVSubtarget &Subtarget) {
1687   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1688                                           Subtarget);
1689 }
1690 
1691 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1692   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1693 }
1694 
1695 // Grow V to consume an entire RVV register.
1696 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1697                                        const RISCVSubtarget &Subtarget) {
1698   assert(VT.isScalableVector() &&
1699          "Expected to convert into a scalable vector!");
1700   assert(V.getValueType().isFixedLengthVector() &&
1701          "Expected a fixed length vector operand!");
1702   SDLoc DL(V);
1703   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1704   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1705 }
1706 
1707 // Shrink V so it's just big enough to maintain a VT's worth of data.
1708 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1709                                          const RISCVSubtarget &Subtarget) {
1710   assert(VT.isFixedLengthVector() &&
1711          "Expected to convert into a fixed length vector!");
1712   assert(V.getValueType().isScalableVector() &&
1713          "Expected a scalable vector operand!");
1714   SDLoc DL(V);
1715   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1716   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1717 }
1718 
1719 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1720 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1721 // the vector type that it is contained in.
1722 static std::pair<SDValue, SDValue>
1723 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1724                 const RISCVSubtarget &Subtarget) {
1725   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1726   MVT XLenVT = Subtarget.getXLenVT();
1727   SDValue VL = VecVT.isFixedLengthVector()
1728                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1729                    : DAG.getRegister(RISCV::X0, XLenVT);
1730   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1731   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1732   return {Mask, VL};
1733 }
1734 
1735 // As above but assuming the given type is a scalable vector type.
1736 static std::pair<SDValue, SDValue>
1737 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1738                         const RISCVSubtarget &Subtarget) {
1739   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1740   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1741 }
1742 
1743 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1744 // of either is (currently) supported. This can get us into an infinite loop
1745 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1746 // as a ..., etc.
1747 // Until either (or both) of these can reliably lower any node, reporting that
1748 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1749 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1750 // which is not desirable.
1751 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1752     EVT VT, unsigned DefinedValues) const {
1753   return false;
1754 }
1755 
1756 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1757                                   const RISCVSubtarget &Subtarget) {
1758   // RISCV FP-to-int conversions saturate to the destination register size, but
1759   // don't produce 0 for nan. We can use a conversion instruction and fix the
1760   // nan case with a compare and a select.
1761   SDValue Src = Op.getOperand(0);
1762 
1763   EVT DstVT = Op.getValueType();
1764   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1765 
1766   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1767   unsigned Opc;
1768   if (SatVT == DstVT)
1769     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1770   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1771     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1772   else
1773     return SDValue();
1774   // FIXME: Support other SatVTs by clamping before or after the conversion.
1775 
1776   SDLoc DL(Op);
1777   SDValue FpToInt = DAG.getNode(
1778       Opc, DL, DstVT, Src,
1779       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1780 
1781   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1782   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1783 }
1784 
1785 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1786 // and back. Taking care to avoid converting values that are nan or already
1787 // correct.
1788 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1789 // have FRM dependencies modeled yet.
1790 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1791   MVT VT = Op.getSimpleValueType();
1792   assert(VT.isVector() && "Unexpected type");
1793 
1794   SDLoc DL(Op);
1795 
1796   // Freeze the source since we are increasing the number of uses.
1797   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1798 
1799   // Truncate to integer and convert back to FP.
1800   MVT IntVT = VT.changeVectorElementTypeToInteger();
1801   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1802   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1803 
1804   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1805 
1806   if (Op.getOpcode() == ISD::FCEIL) {
1807     // If the truncated value is the greater than or equal to the original
1808     // value, we've computed the ceil. Otherwise, we went the wrong way and
1809     // need to increase by 1.
1810     // FIXME: This should use a masked operation. Handle here or in isel?
1811     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1812                                  DAG.getConstantFP(1.0, DL, VT));
1813     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1814     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1815   } else if (Op.getOpcode() == ISD::FFLOOR) {
1816     // If the truncated value is the less than or equal to the original value,
1817     // we've computed the floor. Otherwise, we went the wrong way and need to
1818     // decrease by 1.
1819     // FIXME: This should use a masked operation. Handle here or in isel?
1820     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1821                                  DAG.getConstantFP(1.0, DL, VT));
1822     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1823     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1824   }
1825 
1826   // Restore the original sign so that -0.0 is preserved.
1827   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1828 
1829   // Determine the largest integer that can be represented exactly. This and
1830   // values larger than it don't have any fractional bits so don't need to
1831   // be converted.
1832   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1833   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1834   APFloat MaxVal = APFloat(FltSem);
1835   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1836                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1837   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1838 
1839   // If abs(Src) was larger than MaxVal or nan, keep it.
1840   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1841   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1842   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1843 }
1844 
1845 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1846 // This mode isn't supported in vector hardware on RISCV. But as long as we
1847 // aren't compiling with trapping math, we can emulate this with
1848 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1849 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1850 // dependencies modeled yet.
1851 // FIXME: Use masked operations to avoid final merge.
1852 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1853   MVT VT = Op.getSimpleValueType();
1854   assert(VT.isVector() && "Unexpected type");
1855 
1856   SDLoc DL(Op);
1857 
1858   // Freeze the source since we are increasing the number of uses.
1859   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1860 
1861   // We do the conversion on the absolute value and fix the sign at the end.
1862   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1863 
1864   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1865   bool Ignored;
1866   APFloat Point5Pred = APFloat(0.5f);
1867   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1868   Point5Pred.next(/*nextDown*/ true);
1869 
1870   // Add the adjustment.
1871   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1872                                DAG.getConstantFP(Point5Pred, DL, VT));
1873 
1874   // Truncate to integer and convert back to fp.
1875   MVT IntVT = VT.changeVectorElementTypeToInteger();
1876   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1877   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1878 
1879   // Restore the original sign.
1880   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1881 
1882   // Determine the largest integer that can be represented exactly. This and
1883   // values larger than it don't have any fractional bits so don't need to
1884   // be converted.
1885   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1886   APFloat MaxVal = APFloat(FltSem);
1887   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1888                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1889   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1890 
1891   // If abs(Src) was larger than MaxVal or nan, keep it.
1892   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1893   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1894   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1895 }
1896 
1897 struct VIDSequence {
1898   int64_t StepNumerator;
1899   unsigned StepDenominator;
1900   int64_t Addend;
1901 };
1902 
1903 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1904 // to the (non-zero) step S and start value X. This can be then lowered as the
1905 // RVV sequence (VID * S) + X, for example.
1906 // The step S is represented as an integer numerator divided by a positive
1907 // denominator. Note that the implementation currently only identifies
1908 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1909 // cannot detect 2/3, for example.
1910 // Note that this method will also match potentially unappealing index
1911 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1912 // determine whether this is worth generating code for.
1913 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1914   unsigned NumElts = Op.getNumOperands();
1915   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1916   if (!Op.getValueType().isInteger())
1917     return None;
1918 
1919   Optional<unsigned> SeqStepDenom;
1920   Optional<int64_t> SeqStepNum, SeqAddend;
1921   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1922   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1923   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1924     // Assume undef elements match the sequence; we just have to be careful
1925     // when interpolating across them.
1926     if (Op.getOperand(Idx).isUndef())
1927       continue;
1928     // The BUILD_VECTOR must be all constants.
1929     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1930       return None;
1931 
1932     uint64_t Val = Op.getConstantOperandVal(Idx) &
1933                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1934 
1935     if (PrevElt) {
1936       // Calculate the step since the last non-undef element, and ensure
1937       // it's consistent across the entire sequence.
1938       unsigned IdxDiff = Idx - PrevElt->second;
1939       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1940 
1941       // A zero-value value difference means that we're somewhere in the middle
1942       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1943       // step change before evaluating the sequence.
1944       if (ValDiff == 0)
1945         continue;
1946 
1947       int64_t Remainder = ValDiff % IdxDiff;
1948       // Normalize the step if it's greater than 1.
1949       if (Remainder != ValDiff) {
1950         // The difference must cleanly divide the element span.
1951         if (Remainder != 0)
1952           return None;
1953         ValDiff /= IdxDiff;
1954         IdxDiff = 1;
1955       }
1956 
1957       if (!SeqStepNum)
1958         SeqStepNum = ValDiff;
1959       else if (ValDiff != SeqStepNum)
1960         return None;
1961 
1962       if (!SeqStepDenom)
1963         SeqStepDenom = IdxDiff;
1964       else if (IdxDiff != *SeqStepDenom)
1965         return None;
1966     }
1967 
1968     // Record this non-undef element for later.
1969     if (!PrevElt || PrevElt->first != Val)
1970       PrevElt = std::make_pair(Val, Idx);
1971   }
1972 
1973   // We need to have logged a step for this to count as a legal index sequence.
1974   if (!SeqStepNum || !SeqStepDenom)
1975     return None;
1976 
1977   // Loop back through the sequence and validate elements we might have skipped
1978   // while waiting for a valid step. While doing this, log any sequence addend.
1979   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1980     if (Op.getOperand(Idx).isUndef())
1981       continue;
1982     uint64_t Val = Op.getConstantOperandVal(Idx) &
1983                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1984     uint64_t ExpectedVal =
1985         (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1986     int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1987     if (!SeqAddend)
1988       SeqAddend = Addend;
1989     else if (Addend != SeqAddend)
1990       return None;
1991   }
1992 
1993   assert(SeqAddend && "Must have an addend if we have a step");
1994 
1995   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1996 }
1997 
1998 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1999 // and lower it as a VRGATHER_VX_VL from the source vector.
2000 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
2001                                   SelectionDAG &DAG,
2002                                   const RISCVSubtarget &Subtarget) {
2003   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
2004     return SDValue();
2005   SDValue Vec = SplatVal.getOperand(0);
2006   // Only perform this optimization on vectors of the same size for simplicity.
2007   if (Vec.getValueType() != VT)
2008     return SDValue();
2009   SDValue Idx = SplatVal.getOperand(1);
2010   // The index must be a legal type.
2011   if (Idx.getValueType() != Subtarget.getXLenVT())
2012     return SDValue();
2013 
2014   MVT ContainerVT = VT;
2015   if (VT.isFixedLengthVector()) {
2016     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2017     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2018   }
2019 
2020   SDValue Mask, VL;
2021   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2022 
2023   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
2024                                Idx, Mask, VL);
2025 
2026   if (!VT.isFixedLengthVector())
2027     return Gather;
2028 
2029   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2030 }
2031 
2032 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
2033                                  const RISCVSubtarget &Subtarget) {
2034   MVT VT = Op.getSimpleValueType();
2035   assert(VT.isFixedLengthVector() && "Unexpected vector!");
2036 
2037   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2038 
2039   SDLoc DL(Op);
2040   SDValue Mask, VL;
2041   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2042 
2043   MVT XLenVT = Subtarget.getXLenVT();
2044   unsigned NumElts = Op.getNumOperands();
2045 
2046   if (VT.getVectorElementType() == MVT::i1) {
2047     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
2048       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
2049       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
2050     }
2051 
2052     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
2053       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
2054       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
2055     }
2056 
2057     // Lower constant mask BUILD_VECTORs via an integer vector type, in
2058     // scalar integer chunks whose bit-width depends on the number of mask
2059     // bits and XLEN.
2060     // First, determine the most appropriate scalar integer type to use. This
2061     // is at most XLenVT, but may be shrunk to a smaller vector element type
2062     // according to the size of the final vector - use i8 chunks rather than
2063     // XLenVT if we're producing a v8i1. This results in more consistent
2064     // codegen across RV32 and RV64.
2065     unsigned NumViaIntegerBits =
2066         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2067     NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN());
2068     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2069       // If we have to use more than one INSERT_VECTOR_ELT then this
2070       // optimization is likely to increase code size; avoid peforming it in
2071       // such a case. We can use a load from a constant pool in this case.
2072       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2073         return SDValue();
2074       // Now we can create our integer vector type. Note that it may be larger
2075       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2076       MVT IntegerViaVecVT =
2077           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2078                            divideCeil(NumElts, NumViaIntegerBits));
2079 
2080       uint64_t Bits = 0;
2081       unsigned BitPos = 0, IntegerEltIdx = 0;
2082       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2083 
2084       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2085         // Once we accumulate enough bits to fill our scalar type, insert into
2086         // our vector and clear our accumulated data.
2087         if (I != 0 && I % NumViaIntegerBits == 0) {
2088           if (NumViaIntegerBits <= 32)
2089             Bits = SignExtend64(Bits, 32);
2090           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2091           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2092                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2093           Bits = 0;
2094           BitPos = 0;
2095           IntegerEltIdx++;
2096         }
2097         SDValue V = Op.getOperand(I);
2098         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2099         Bits |= ((uint64_t)BitValue << BitPos);
2100       }
2101 
2102       // Insert the (remaining) scalar value into position in our integer
2103       // vector type.
2104       if (NumViaIntegerBits <= 32)
2105         Bits = SignExtend64(Bits, 32);
2106       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2107       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2108                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2109 
2110       if (NumElts < NumViaIntegerBits) {
2111         // If we're producing a smaller vector than our minimum legal integer
2112         // type, bitcast to the equivalent (known-legal) mask type, and extract
2113         // our final mask.
2114         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2115         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2116         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2117                           DAG.getConstant(0, DL, XLenVT));
2118       } else {
2119         // Else we must have produced an integer type with the same size as the
2120         // mask type; bitcast for the final result.
2121         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2122         Vec = DAG.getBitcast(VT, Vec);
2123       }
2124 
2125       return Vec;
2126     }
2127 
2128     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2129     // vector type, we have a legal equivalently-sized i8 type, so we can use
2130     // that.
2131     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2132     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2133 
2134     SDValue WideVec;
2135     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2136       // For a splat, perform a scalar truncate before creating the wider
2137       // vector.
2138       assert(Splat.getValueType() == XLenVT &&
2139              "Unexpected type for i1 splat value");
2140       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2141                           DAG.getConstant(1, DL, XLenVT));
2142       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2143     } else {
2144       SmallVector<SDValue, 8> Ops(Op->op_values());
2145       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2146       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2147       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2148     }
2149 
2150     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2151   }
2152 
2153   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2154     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2155       return Gather;
2156     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2157                                         : RISCVISD::VMV_V_X_VL;
2158     Splat =
2159         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2160     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2161   }
2162 
2163   // Try and match index sequences, which we can lower to the vid instruction
2164   // with optional modifications. An all-undef vector is matched by
2165   // getSplatValue, above.
2166   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2167     int64_t StepNumerator = SimpleVID->StepNumerator;
2168     unsigned StepDenominator = SimpleVID->StepDenominator;
2169     int64_t Addend = SimpleVID->Addend;
2170 
2171     assert(StepNumerator != 0 && "Invalid step");
2172     bool Negate = false;
2173     int64_t SplatStepVal = StepNumerator;
2174     unsigned StepOpcode = ISD::MUL;
2175     if (StepNumerator != 1) {
2176       if (isPowerOf2_64(std::abs(StepNumerator))) {
2177         Negate = StepNumerator < 0;
2178         StepOpcode = ISD::SHL;
2179         SplatStepVal = Log2_64(std::abs(StepNumerator));
2180       }
2181     }
2182 
2183     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2184     // threshold since it's the immediate value many RVV instructions accept.
2185     // There is no vmul.vi instruction so ensure multiply constant can fit in
2186     // a single addi instruction.
2187     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2188          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2189         isPowerOf2_32(StepDenominator) &&
2190         (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) {
2191       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2192       // Convert right out of the scalable type so we can use standard ISD
2193       // nodes for the rest of the computation. If we used scalable types with
2194       // these, we'd lose the fixed-length vector info and generate worse
2195       // vsetvli code.
2196       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2197       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2198           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2199         SDValue SplatStep = DAG.getSplatBuildVector(
2200             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2201         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2202       }
2203       if (StepDenominator != 1) {
2204         SDValue SplatStep = DAG.getSplatBuildVector(
2205             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2206         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2207       }
2208       if (Addend != 0 || Negate) {
2209         SDValue SplatAddend = DAG.getSplatBuildVector(
2210             VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2211         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2212       }
2213       return VID;
2214     }
2215   }
2216 
2217   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2218   // when re-interpreted as a vector with a larger element type. For example,
2219   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2220   // could be instead splat as
2221   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2222   // TODO: This optimization could also work on non-constant splats, but it
2223   // would require bit-manipulation instructions to construct the splat value.
2224   SmallVector<SDValue> Sequence;
2225   unsigned EltBitSize = VT.getScalarSizeInBits();
2226   const auto *BV = cast<BuildVectorSDNode>(Op);
2227   if (VT.isInteger() && EltBitSize < 64 &&
2228       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2229       BV->getRepeatedSequence(Sequence) &&
2230       (Sequence.size() * EltBitSize) <= 64) {
2231     unsigned SeqLen = Sequence.size();
2232     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2233     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2234     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2235             ViaIntVT == MVT::i64) &&
2236            "Unexpected sequence type");
2237 
2238     unsigned EltIdx = 0;
2239     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2240     uint64_t SplatValue = 0;
2241     // Construct the amalgamated value which can be splatted as this larger
2242     // vector type.
2243     for (const auto &SeqV : Sequence) {
2244       if (!SeqV.isUndef())
2245         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2246                        << (EltIdx * EltBitSize));
2247       EltIdx++;
2248     }
2249 
2250     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2251     // achieve better constant materializion.
2252     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2253       SplatValue = SignExtend64(SplatValue, 32);
2254 
2255     // Since we can't introduce illegal i64 types at this stage, we can only
2256     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2257     // way we can use RVV instructions to splat.
2258     assert((ViaIntVT.bitsLE(XLenVT) ||
2259             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2260            "Unexpected bitcast sequence");
2261     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2262       SDValue ViaVL =
2263           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2264       MVT ViaContainerVT =
2265           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2266       SDValue Splat =
2267           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2268                       DAG.getUNDEF(ViaContainerVT),
2269                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2270       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2271       return DAG.getBitcast(VT, Splat);
2272     }
2273   }
2274 
2275   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2276   // which constitute a large proportion of the elements. In such cases we can
2277   // splat a vector with the dominant element and make up the shortfall with
2278   // INSERT_VECTOR_ELTs.
2279   // Note that this includes vectors of 2 elements by association. The
2280   // upper-most element is the "dominant" one, allowing us to use a splat to
2281   // "insert" the upper element, and an insert of the lower element at position
2282   // 0, which improves codegen.
2283   SDValue DominantValue;
2284   unsigned MostCommonCount = 0;
2285   DenseMap<SDValue, unsigned> ValueCounts;
2286   unsigned NumUndefElts =
2287       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2288 
2289   // Track the number of scalar loads we know we'd be inserting, estimated as
2290   // any non-zero floating-point constant. Other kinds of element are either
2291   // already in registers or are materialized on demand. The threshold at which
2292   // a vector load is more desirable than several scalar materializion and
2293   // vector-insertion instructions is not known.
2294   unsigned NumScalarLoads = 0;
2295 
2296   for (SDValue V : Op->op_values()) {
2297     if (V.isUndef())
2298       continue;
2299 
2300     ValueCounts.insert(std::make_pair(V, 0));
2301     unsigned &Count = ValueCounts[V];
2302 
2303     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2304       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2305 
2306     // Is this value dominant? In case of a tie, prefer the highest element as
2307     // it's cheaper to insert near the beginning of a vector than it is at the
2308     // end.
2309     if (++Count >= MostCommonCount) {
2310       DominantValue = V;
2311       MostCommonCount = Count;
2312     }
2313   }
2314 
2315   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2316   unsigned NumDefElts = NumElts - NumUndefElts;
2317   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2318 
2319   // Don't perform this optimization when optimizing for size, since
2320   // materializing elements and inserting them tends to cause code bloat.
2321   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2322       ((MostCommonCount > DominantValueCountThreshold) ||
2323        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2324     // Start by splatting the most common element.
2325     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2326 
2327     DenseSet<SDValue> Processed{DominantValue};
2328     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2329     for (const auto &OpIdx : enumerate(Op->ops())) {
2330       const SDValue &V = OpIdx.value();
2331       if (V.isUndef() || !Processed.insert(V).second)
2332         continue;
2333       if (ValueCounts[V] == 1) {
2334         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2335                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2336       } else {
2337         // Blend in all instances of this value using a VSELECT, using a
2338         // mask where each bit signals whether that element is the one
2339         // we're after.
2340         SmallVector<SDValue> Ops;
2341         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2342           return DAG.getConstant(V == V1, DL, XLenVT);
2343         });
2344         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2345                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2346                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2347       }
2348     }
2349 
2350     return Vec;
2351   }
2352 
2353   return SDValue();
2354 }
2355 
2356 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2357                                    SDValue Lo, SDValue Hi, SDValue VL,
2358                                    SelectionDAG &DAG) {
2359   if (!Passthru)
2360     Passthru = DAG.getUNDEF(VT);
2361   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2362     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2363     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2364     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2365     // node in order to try and match RVV vector/scalar instructions.
2366     if ((LoC >> 31) == HiC)
2367       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2368 
2369     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2370     // vmv.v.x whose EEW = 32 to lower it.
2371     auto *Const = dyn_cast<ConstantSDNode>(VL);
2372     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2373       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2374       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2375       // access the subtarget here now.
2376       auto InterVec = DAG.getNode(
2377           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2378                                   DAG.getRegister(RISCV::X0, MVT::i32));
2379       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2380     }
2381   }
2382 
2383   // Fall back to a stack store and stride x0 vector load.
2384   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2385                      Hi, VL);
2386 }
2387 
2388 // Called by type legalization to handle splat of i64 on RV32.
2389 // FIXME: We can optimize this when the type has sign or zero bits in one
2390 // of the halves.
2391 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2392                                    SDValue Scalar, SDValue VL,
2393                                    SelectionDAG &DAG) {
2394   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2395   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2396                            DAG.getConstant(0, DL, MVT::i32));
2397   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2398                            DAG.getConstant(1, DL, MVT::i32));
2399   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2400 }
2401 
2402 // This function lowers a splat of a scalar operand Splat with the vector
2403 // length VL. It ensures the final sequence is type legal, which is useful when
2404 // lowering a splat after type legalization.
2405 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2406                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2407                                 const RISCVSubtarget &Subtarget) {
2408   bool HasPassthru = Passthru && !Passthru.isUndef();
2409   if (!HasPassthru && !Passthru)
2410     Passthru = DAG.getUNDEF(VT);
2411   if (VT.isFloatingPoint()) {
2412     // If VL is 1, we could use vfmv.s.f.
2413     if (isOneConstant(VL))
2414       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2415     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2416   }
2417 
2418   MVT XLenVT = Subtarget.getXLenVT();
2419 
2420   // Simplest case is that the operand needs to be promoted to XLenVT.
2421   if (Scalar.getValueType().bitsLE(XLenVT)) {
2422     // If the operand is a constant, sign extend to increase our chances
2423     // of being able to use a .vi instruction. ANY_EXTEND would become a
2424     // a zero extend and the simm5 check in isel would fail.
2425     // FIXME: Should we ignore the upper bits in isel instead?
2426     unsigned ExtOpc =
2427         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2428     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2429     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2430     // If VL is 1 and the scalar value won't benefit from immediate, we could
2431     // use vmv.s.x.
2432     if (isOneConstant(VL) &&
2433         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2434       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2435     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2436   }
2437 
2438   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2439          "Unexpected scalar for splat lowering!");
2440 
2441   if (isOneConstant(VL) && isNullConstant(Scalar))
2442     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2443                        DAG.getConstant(0, DL, XLenVT), VL);
2444 
2445   // Otherwise use the more complicated splatting algorithm.
2446   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2447 }
2448 
2449 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2450                                 const RISCVSubtarget &Subtarget) {
2451   // We need to be able to widen elements to the next larger integer type.
2452   if (VT.getScalarSizeInBits() >= Subtarget.getELEN())
2453     return false;
2454 
2455   int Size = Mask.size();
2456   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2457 
2458   int Srcs[] = {-1, -1};
2459   for (int i = 0; i != Size; ++i) {
2460     // Ignore undef elements.
2461     if (Mask[i] < 0)
2462       continue;
2463 
2464     // Is this an even or odd element.
2465     int Pol = i % 2;
2466 
2467     // Ensure we consistently use the same source for this element polarity.
2468     int Src = Mask[i] / Size;
2469     if (Srcs[Pol] < 0)
2470       Srcs[Pol] = Src;
2471     if (Srcs[Pol] != Src)
2472       return false;
2473 
2474     // Make sure the element within the source is appropriate for this element
2475     // in the destination.
2476     int Elt = Mask[i] % Size;
2477     if (Elt != i / 2)
2478       return false;
2479   }
2480 
2481   // We need to find a source for each polarity and they can't be the same.
2482   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2483     return false;
2484 
2485   // Swap the sources if the second source was in the even polarity.
2486   SwapSources = Srcs[0] > Srcs[1];
2487 
2488   return true;
2489 }
2490 
2491 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2492 /// and then extract the original number of elements from the rotated result.
2493 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2494 /// returned rotation amount is for a rotate right, where elements move from
2495 /// higher elements to lower elements. \p LoSrc indicates the first source
2496 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2497 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2498 /// 0 or 1 if a rotation is found.
2499 ///
2500 /// NOTE: We talk about rotate to the right which matches how bit shift and
2501 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2502 /// and the table below write vectors with the lowest elements on the left.
2503 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2504   int Size = Mask.size();
2505 
2506   // We need to detect various ways of spelling a rotation:
2507   //   [11, 12, 13, 14, 15,  0,  1,  2]
2508   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2509   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2510   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2511   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2512   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2513   int Rotation = 0;
2514   LoSrc = -1;
2515   HiSrc = -1;
2516   for (int i = 0; i != Size; ++i) {
2517     int M = Mask[i];
2518     if (M < 0)
2519       continue;
2520 
2521     // Determine where a rotate vector would have started.
2522     int StartIdx = i - (M % Size);
2523     // The identity rotation isn't interesting, stop.
2524     if (StartIdx == 0)
2525       return -1;
2526 
2527     // If we found the tail of a vector the rotation must be the missing
2528     // front. If we found the head of a vector, it must be how much of the
2529     // head.
2530     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2531 
2532     if (Rotation == 0)
2533       Rotation = CandidateRotation;
2534     else if (Rotation != CandidateRotation)
2535       // The rotations don't match, so we can't match this mask.
2536       return -1;
2537 
2538     // Compute which value this mask is pointing at.
2539     int MaskSrc = M < Size ? 0 : 1;
2540 
2541     // Compute which of the two target values this index should be assigned to.
2542     // This reflects whether the high elements are remaining or the low elemnts
2543     // are remaining.
2544     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2545 
2546     // Either set up this value if we've not encountered it before, or check
2547     // that it remains consistent.
2548     if (TargetSrc < 0)
2549       TargetSrc = MaskSrc;
2550     else if (TargetSrc != MaskSrc)
2551       // This may be a rotation, but it pulls from the inputs in some
2552       // unsupported interleaving.
2553       return -1;
2554   }
2555 
2556   // Check that we successfully analyzed the mask, and normalize the results.
2557   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2558   assert((LoSrc >= 0 || HiSrc >= 0) &&
2559          "Failed to find a rotated input vector!");
2560 
2561   return Rotation;
2562 }
2563 
2564 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2565                                    const RISCVSubtarget &Subtarget) {
2566   SDValue V1 = Op.getOperand(0);
2567   SDValue V2 = Op.getOperand(1);
2568   SDLoc DL(Op);
2569   MVT XLenVT = Subtarget.getXLenVT();
2570   MVT VT = Op.getSimpleValueType();
2571   unsigned NumElts = VT.getVectorNumElements();
2572   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2573 
2574   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2575 
2576   SDValue TrueMask, VL;
2577   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2578 
2579   if (SVN->isSplat()) {
2580     const int Lane = SVN->getSplatIndex();
2581     if (Lane >= 0) {
2582       MVT SVT = VT.getVectorElementType();
2583 
2584       // Turn splatted vector load into a strided load with an X0 stride.
2585       SDValue V = V1;
2586       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2587       // with undef.
2588       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2589       int Offset = Lane;
2590       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2591         int OpElements =
2592             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2593         V = V.getOperand(Offset / OpElements);
2594         Offset %= OpElements;
2595       }
2596 
2597       // We need to ensure the load isn't atomic or volatile.
2598       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2599         auto *Ld = cast<LoadSDNode>(V);
2600         Offset *= SVT.getStoreSize();
2601         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2602                                                    TypeSize::Fixed(Offset), DL);
2603 
2604         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2605         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2606           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2607           SDValue IntID =
2608               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2609           SDValue Ops[] = {Ld->getChain(),
2610                            IntID,
2611                            DAG.getUNDEF(ContainerVT),
2612                            NewAddr,
2613                            DAG.getRegister(RISCV::X0, XLenVT),
2614                            VL};
2615           SDValue NewLoad = DAG.getMemIntrinsicNode(
2616               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2617               DAG.getMachineFunction().getMachineMemOperand(
2618                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2619           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2620           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2621         }
2622 
2623         // Otherwise use a scalar load and splat. This will give the best
2624         // opportunity to fold a splat into the operation. ISel can turn it into
2625         // the x0 strided load if we aren't able to fold away the select.
2626         if (SVT.isFloatingPoint())
2627           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2628                           Ld->getPointerInfo().getWithOffset(Offset),
2629                           Ld->getOriginalAlign(),
2630                           Ld->getMemOperand()->getFlags());
2631         else
2632           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2633                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2634                              Ld->getOriginalAlign(),
2635                              Ld->getMemOperand()->getFlags());
2636         DAG.makeEquivalentMemoryOrdering(Ld, V);
2637 
2638         unsigned Opc =
2639             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2640         SDValue Splat =
2641             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2642         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2643       }
2644 
2645       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2646       assert(Lane < (int)NumElts && "Unexpected lane!");
2647       SDValue Gather =
2648           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2649                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2650       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2651     }
2652   }
2653 
2654   ArrayRef<int> Mask = SVN->getMask();
2655 
2656   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2657   // be undef which can be handled with a single SLIDEDOWN/UP.
2658   int LoSrc, HiSrc;
2659   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2660   if (Rotation > 0) {
2661     SDValue LoV, HiV;
2662     if (LoSrc >= 0) {
2663       LoV = LoSrc == 0 ? V1 : V2;
2664       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2665     }
2666     if (HiSrc >= 0) {
2667       HiV = HiSrc == 0 ? V1 : V2;
2668       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2669     }
2670 
2671     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2672     // to slide LoV up by (NumElts - Rotation).
2673     unsigned InvRotate = NumElts - Rotation;
2674 
2675     SDValue Res = DAG.getUNDEF(ContainerVT);
2676     if (HiV) {
2677       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2678       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2679       // causes multiple vsetvlis in some test cases such as lowering
2680       // reduce.mul
2681       SDValue DownVL = VL;
2682       if (LoV)
2683         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2684       Res =
2685           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2686                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2687     }
2688     if (LoV)
2689       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2690                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2691 
2692     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2693   }
2694 
2695   // Detect an interleave shuffle and lower to
2696   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2697   bool SwapSources;
2698   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2699     // Swap sources if needed.
2700     if (SwapSources)
2701       std::swap(V1, V2);
2702 
2703     // Extract the lower half of the vectors.
2704     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2705     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2706                      DAG.getConstant(0, DL, XLenVT));
2707     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2708                      DAG.getConstant(0, DL, XLenVT));
2709 
2710     // Double the element width and halve the number of elements in an int type.
2711     unsigned EltBits = VT.getScalarSizeInBits();
2712     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2713     MVT WideIntVT =
2714         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2715     // Convert this to a scalable vector. We need to base this on the
2716     // destination size to ensure there's always a type with a smaller LMUL.
2717     MVT WideIntContainerVT =
2718         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2719 
2720     // Convert sources to scalable vectors with the same element count as the
2721     // larger type.
2722     MVT HalfContainerVT = MVT::getVectorVT(
2723         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2724     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2725     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2726 
2727     // Cast sources to integer.
2728     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2729     MVT IntHalfVT =
2730         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2731     V1 = DAG.getBitcast(IntHalfVT, V1);
2732     V2 = DAG.getBitcast(IntHalfVT, V2);
2733 
2734     // Freeze V2 since we use it twice and we need to be sure that the add and
2735     // multiply see the same value.
2736     V2 = DAG.getFreeze(V2);
2737 
2738     // Recreate TrueMask using the widened type's element count.
2739     MVT MaskVT =
2740         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2741     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2742 
2743     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2744     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2745                               V2, TrueMask, VL);
2746     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2747     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2748                                      DAG.getUNDEF(IntHalfVT),
2749                                      DAG.getAllOnesConstant(DL, XLenVT));
2750     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2751                                    V2, Multiplier, TrueMask, VL);
2752     // Add the new copies to our previous addition giving us 2^eltbits copies of
2753     // V2. This is equivalent to shifting V2 left by eltbits. This should
2754     // combine with the vwmulu.vv above to form vwmaccu.vv.
2755     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2756                       TrueMask, VL);
2757     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2758     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2759     // vector VT.
2760     ContainerVT =
2761         MVT::getVectorVT(VT.getVectorElementType(),
2762                          WideIntContainerVT.getVectorElementCount() * 2);
2763     Add = DAG.getBitcast(ContainerVT, Add);
2764     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2765   }
2766 
2767   // Detect shuffles which can be re-expressed as vector selects; these are
2768   // shuffles in which each element in the destination is taken from an element
2769   // at the corresponding index in either source vectors.
2770   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2771     int MaskIndex = MaskIdx.value();
2772     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2773   });
2774 
2775   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2776 
2777   SmallVector<SDValue> MaskVals;
2778   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2779   // merged with a second vrgather.
2780   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2781 
2782   // By default we preserve the original operand order, and use a mask to
2783   // select LHS as true and RHS as false. However, since RVV vector selects may
2784   // feature splats but only on the LHS, we may choose to invert our mask and
2785   // instead select between RHS and LHS.
2786   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2787   bool InvertMask = IsSelect == SwapOps;
2788 
2789   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2790   // half.
2791   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2792 
2793   // Now construct the mask that will be used by the vselect or blended
2794   // vrgather operation. For vrgathers, construct the appropriate indices into
2795   // each vector.
2796   for (int MaskIndex : Mask) {
2797     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2798     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2799     if (!IsSelect) {
2800       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2801       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2802                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2803                                      : DAG.getUNDEF(XLenVT));
2804       GatherIndicesRHS.push_back(
2805           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2806                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2807       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2808         ++LHSIndexCounts[MaskIndex];
2809       if (!IsLHSOrUndefIndex)
2810         ++RHSIndexCounts[MaskIndex - NumElts];
2811     }
2812   }
2813 
2814   if (SwapOps) {
2815     std::swap(V1, V2);
2816     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2817   }
2818 
2819   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2820   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2821   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2822 
2823   if (IsSelect)
2824     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2825 
2826   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2827     // On such a large vector we're unable to use i8 as the index type.
2828     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2829     // may involve vector splitting if we're already at LMUL=8, or our
2830     // user-supplied maximum fixed-length LMUL.
2831     return SDValue();
2832   }
2833 
2834   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2835   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2836   MVT IndexVT = VT.changeTypeToInteger();
2837   // Since we can't introduce illegal index types at this stage, use i16 and
2838   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2839   // than XLenVT.
2840   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2841     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2842     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2843   }
2844 
2845   MVT IndexContainerVT =
2846       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2847 
2848   SDValue Gather;
2849   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2850   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2851   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2852     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2853                               Subtarget);
2854   } else {
2855     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2856     // If only one index is used, we can use a "splat" vrgather.
2857     // TODO: We can splat the most-common index and fix-up any stragglers, if
2858     // that's beneficial.
2859     if (LHSIndexCounts.size() == 1) {
2860       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2861       Gather =
2862           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2863                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2864     } else {
2865       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2866       LHSIndices =
2867           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2868 
2869       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2870                            TrueMask, VL);
2871     }
2872   }
2873 
2874   // If a second vector operand is used by this shuffle, blend it in with an
2875   // additional vrgather.
2876   if (!V2.isUndef()) {
2877     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2878     // If only one index is used, we can use a "splat" vrgather.
2879     // TODO: We can splat the most-common index and fix-up any stragglers, if
2880     // that's beneficial.
2881     if (RHSIndexCounts.size() == 1) {
2882       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2883       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2884                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2885     } else {
2886       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2887       RHSIndices =
2888           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2889       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2890                        VL);
2891     }
2892 
2893     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2894     SelectMask =
2895         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2896 
2897     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2898                          Gather, VL);
2899   }
2900 
2901   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2902 }
2903 
2904 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2905   // Support splats for any type. These should type legalize well.
2906   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2907     return true;
2908 
2909   // Only support legal VTs for other shuffles for now.
2910   if (!isTypeLegal(VT))
2911     return false;
2912 
2913   MVT SVT = VT.getSimpleVT();
2914 
2915   bool SwapSources;
2916   int LoSrc, HiSrc;
2917   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2918          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2919 }
2920 
2921 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2922                                      SDLoc DL, SelectionDAG &DAG,
2923                                      const RISCVSubtarget &Subtarget) {
2924   if (VT.isScalableVector())
2925     return DAG.getFPExtendOrRound(Op, DL, VT);
2926   assert(VT.isFixedLengthVector() &&
2927          "Unexpected value type for RVV FP extend/round lowering");
2928   SDValue Mask, VL;
2929   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2930   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2931                         ? RISCVISD::FP_EXTEND_VL
2932                         : RISCVISD::FP_ROUND_VL;
2933   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2934 }
2935 
2936 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2937 // the exponent.
2938 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2939   MVT VT = Op.getSimpleValueType();
2940   unsigned EltSize = VT.getScalarSizeInBits();
2941   SDValue Src = Op.getOperand(0);
2942   SDLoc DL(Op);
2943 
2944   // We need a FP type that can represent the value.
2945   // TODO: Use f16 for i8 when possible?
2946   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2947   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2948 
2949   // Legal types should have been checked in the RISCVTargetLowering
2950   // constructor.
2951   // TODO: Splitting may make sense in some cases.
2952   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2953          "Expected legal float type!");
2954 
2955   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2956   // The trailing zero count is equal to log2 of this single bit value.
2957   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2958     SDValue Neg =
2959         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2960     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2961   }
2962 
2963   // We have a legal FP type, convert to it.
2964   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2965   // Bitcast to integer and shift the exponent to the LSB.
2966   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2967   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2968   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2969   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2970                               DAG.getConstant(ShiftAmt, DL, IntVT));
2971   // Truncate back to original type to allow vnsrl.
2972   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2973   // The exponent contains log2 of the value in biased form.
2974   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2975 
2976   // For trailing zeros, we just need to subtract the bias.
2977   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2978     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2979                        DAG.getConstant(ExponentBias, DL, VT));
2980 
2981   // For leading zeros, we need to remove the bias and convert from log2 to
2982   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2983   unsigned Adjust = ExponentBias + (EltSize - 1);
2984   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2985 }
2986 
2987 // While RVV has alignment restrictions, we should always be able to load as a
2988 // legal equivalently-sized byte-typed vector instead. This method is
2989 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2990 // the load is already correctly-aligned, it returns SDValue().
2991 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2992                                                     SelectionDAG &DAG) const {
2993   auto *Load = cast<LoadSDNode>(Op);
2994   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2995 
2996   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2997                                      Load->getMemoryVT(),
2998                                      *Load->getMemOperand()))
2999     return SDValue();
3000 
3001   SDLoc DL(Op);
3002   MVT VT = Op.getSimpleValueType();
3003   unsigned EltSizeBits = VT.getScalarSizeInBits();
3004   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3005          "Unexpected unaligned RVV load type");
3006   MVT NewVT =
3007       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3008   assert(NewVT.isValid() &&
3009          "Expecting equally-sized RVV vector types to be legal");
3010   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
3011                           Load->getPointerInfo(), Load->getOriginalAlign(),
3012                           Load->getMemOperand()->getFlags());
3013   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
3014 }
3015 
3016 // While RVV has alignment restrictions, we should always be able to store as a
3017 // legal equivalently-sized byte-typed vector instead. This method is
3018 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
3019 // returns SDValue() if the store is already correctly aligned.
3020 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
3021                                                      SelectionDAG &DAG) const {
3022   auto *Store = cast<StoreSDNode>(Op);
3023   assert(Store && Store->getValue().getValueType().isVector() &&
3024          "Expected vector store");
3025 
3026   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3027                                      Store->getMemoryVT(),
3028                                      *Store->getMemOperand()))
3029     return SDValue();
3030 
3031   SDLoc DL(Op);
3032   SDValue StoredVal = Store->getValue();
3033   MVT VT = StoredVal.getSimpleValueType();
3034   unsigned EltSizeBits = VT.getScalarSizeInBits();
3035   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3036          "Unexpected unaligned RVV store type");
3037   MVT NewVT =
3038       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3039   assert(NewVT.isValid() &&
3040          "Expecting equally-sized RVV vector types to be legal");
3041   StoredVal = DAG.getBitcast(NewVT, StoredVal);
3042   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
3043                       Store->getPointerInfo(), Store->getOriginalAlign(),
3044                       Store->getMemOperand()->getFlags());
3045 }
3046 
3047 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
3048                                             SelectionDAG &DAG) const {
3049   switch (Op.getOpcode()) {
3050   default:
3051     report_fatal_error("unimplemented operand");
3052   case ISD::GlobalAddress:
3053     return lowerGlobalAddress(Op, DAG);
3054   case ISD::BlockAddress:
3055     return lowerBlockAddress(Op, DAG);
3056   case ISD::ConstantPool:
3057     return lowerConstantPool(Op, DAG);
3058   case ISD::JumpTable:
3059     return lowerJumpTable(Op, DAG);
3060   case ISD::GlobalTLSAddress:
3061     return lowerGlobalTLSAddress(Op, DAG);
3062   case ISD::SELECT:
3063     return lowerSELECT(Op, DAG);
3064   case ISD::BRCOND:
3065     return lowerBRCOND(Op, DAG);
3066   case ISD::VASTART:
3067     return lowerVASTART(Op, DAG);
3068   case ISD::FRAMEADDR:
3069     return lowerFRAMEADDR(Op, DAG);
3070   case ISD::RETURNADDR:
3071     return lowerRETURNADDR(Op, DAG);
3072   case ISD::SHL_PARTS:
3073     return lowerShiftLeftParts(Op, DAG);
3074   case ISD::SRA_PARTS:
3075     return lowerShiftRightParts(Op, DAG, true);
3076   case ISD::SRL_PARTS:
3077     return lowerShiftRightParts(Op, DAG, false);
3078   case ISD::BITCAST: {
3079     SDLoc DL(Op);
3080     EVT VT = Op.getValueType();
3081     SDValue Op0 = Op.getOperand(0);
3082     EVT Op0VT = Op0.getValueType();
3083     MVT XLenVT = Subtarget.getXLenVT();
3084     if (VT.isFixedLengthVector()) {
3085       // We can handle fixed length vector bitcasts with a simple replacement
3086       // in isel.
3087       if (Op0VT.isFixedLengthVector())
3088         return Op;
3089       // When bitcasting from scalar to fixed-length vector, insert the scalar
3090       // into a one-element vector of the result type, and perform a vector
3091       // bitcast.
3092       if (!Op0VT.isVector()) {
3093         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3094         if (!isTypeLegal(BVT))
3095           return SDValue();
3096         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3097                                               DAG.getUNDEF(BVT), Op0,
3098                                               DAG.getConstant(0, DL, XLenVT)));
3099       }
3100       return SDValue();
3101     }
3102     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3103     // thus: bitcast the vector to a one-element vector type whose element type
3104     // is the same as the result type, and extract the first element.
3105     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3106       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3107       if (!isTypeLegal(BVT))
3108         return SDValue();
3109       SDValue BVec = DAG.getBitcast(BVT, Op0);
3110       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3111                          DAG.getConstant(0, DL, XLenVT));
3112     }
3113     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3114       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3115       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3116       return FPConv;
3117     }
3118     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3119         Subtarget.hasStdExtF()) {
3120       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3121       SDValue FPConv =
3122           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3123       return FPConv;
3124     }
3125     return SDValue();
3126   }
3127   case ISD::INTRINSIC_WO_CHAIN:
3128     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3129   case ISD::INTRINSIC_W_CHAIN:
3130     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3131   case ISD::INTRINSIC_VOID:
3132     return LowerINTRINSIC_VOID(Op, DAG);
3133   case ISD::BSWAP:
3134   case ISD::BITREVERSE: {
3135     MVT VT = Op.getSimpleValueType();
3136     SDLoc DL(Op);
3137     if (Subtarget.hasStdExtZbp()) {
3138       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3139       // Start with the maximum immediate value which is the bitwidth - 1.
3140       unsigned Imm = VT.getSizeInBits() - 1;
3141       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3142       if (Op.getOpcode() == ISD::BSWAP)
3143         Imm &= ~0x7U;
3144       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3145                          DAG.getConstant(Imm, DL, VT));
3146     }
3147     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3148     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3149     // Expand bitreverse to a bswap(rev8) followed by brev8.
3150     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3151     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3152     // as brev8 by an isel pattern.
3153     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3154                        DAG.getConstant(7, DL, VT));
3155   }
3156   case ISD::FSHL:
3157   case ISD::FSHR: {
3158     MVT VT = Op.getSimpleValueType();
3159     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3160     SDLoc DL(Op);
3161     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3162     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3163     // accidentally setting the extra bit.
3164     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3165     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3166                                 DAG.getConstant(ShAmtWidth, DL, VT));
3167     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3168     // instruction use different orders. fshl will return its first operand for
3169     // shift of zero, fshr will return its second operand. fsl and fsr both
3170     // return rs1 so the ISD nodes need to have different operand orders.
3171     // Shift amount is in rs2.
3172     SDValue Op0 = Op.getOperand(0);
3173     SDValue Op1 = Op.getOperand(1);
3174     unsigned Opc = RISCVISD::FSL;
3175     if (Op.getOpcode() == ISD::FSHR) {
3176       std::swap(Op0, Op1);
3177       Opc = RISCVISD::FSR;
3178     }
3179     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3180   }
3181   case ISD::TRUNCATE:
3182     // Only custom-lower vector truncates
3183     if (!Op.getSimpleValueType().isVector())
3184       return Op;
3185     return lowerVectorTruncLike(Op, DAG);
3186   case ISD::ANY_EXTEND:
3187   case ISD::ZERO_EXTEND:
3188     if (Op.getOperand(0).getValueType().isVector() &&
3189         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3190       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3191     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3192   case ISD::SIGN_EXTEND:
3193     if (Op.getOperand(0).getValueType().isVector() &&
3194         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3195       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3196     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3197   case ISD::SPLAT_VECTOR_PARTS:
3198     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3199   case ISD::INSERT_VECTOR_ELT:
3200     return lowerINSERT_VECTOR_ELT(Op, DAG);
3201   case ISD::EXTRACT_VECTOR_ELT:
3202     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3203   case ISD::VSCALE: {
3204     MVT VT = Op.getSimpleValueType();
3205     SDLoc DL(Op);
3206     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3207     // We define our scalable vector types for lmul=1 to use a 64 bit known
3208     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3209     // vscale as VLENB / 8.
3210     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3211     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3212       report_fatal_error("Support for VLEN==32 is incomplete.");
3213     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3214       // We assume VLENB is a multiple of 8. We manually choose the best shift
3215       // here because SimplifyDemandedBits isn't always able to simplify it.
3216       uint64_t Val = Op.getConstantOperandVal(0);
3217       if (isPowerOf2_64(Val)) {
3218         uint64_t Log2 = Log2_64(Val);
3219         if (Log2 < 3)
3220           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3221                              DAG.getConstant(3 - Log2, DL, VT));
3222         if (Log2 > 3)
3223           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3224                              DAG.getConstant(Log2 - 3, DL, VT));
3225         return VLENB;
3226       }
3227       // If the multiplier is a multiple of 8, scale it down to avoid needing
3228       // to shift the VLENB value.
3229       if ((Val % 8) == 0)
3230         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3231                            DAG.getConstant(Val / 8, DL, VT));
3232     }
3233 
3234     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3235                                  DAG.getConstant(3, DL, VT));
3236     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3237   }
3238   case ISD::FPOWI: {
3239     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3240     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3241     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3242         Op.getOperand(1).getValueType() == MVT::i32) {
3243       SDLoc DL(Op);
3244       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3245       SDValue Powi =
3246           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3247       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3248                          DAG.getIntPtrConstant(0, DL));
3249     }
3250     return SDValue();
3251   }
3252   case ISD::FP_EXTEND: {
3253     // RVV can only do fp_extend to types double the size as the source. We
3254     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3255     // via f32.
3256     SDLoc DL(Op);
3257     MVT VT = Op.getSimpleValueType();
3258     SDValue Src = Op.getOperand(0);
3259     MVT SrcVT = Src.getSimpleValueType();
3260 
3261     // Prepare any fixed-length vector operands.
3262     MVT ContainerVT = VT;
3263     if (SrcVT.isFixedLengthVector()) {
3264       ContainerVT = getContainerForFixedLengthVector(VT);
3265       MVT SrcContainerVT =
3266           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3267       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3268     }
3269 
3270     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3271         SrcVT.getVectorElementType() != MVT::f16) {
3272       // For scalable vectors, we only need to close the gap between
3273       // vXf16->vXf64.
3274       if (!VT.isFixedLengthVector())
3275         return Op;
3276       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3277       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3278       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3279     }
3280 
3281     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3282     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3283     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3284         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3285 
3286     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3287                                            DL, DAG, Subtarget);
3288     if (VT.isFixedLengthVector())
3289       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3290     return Extend;
3291   }
3292   case ISD::FP_ROUND:
3293     if (!Op.getValueType().isVector())
3294       return Op;
3295     return lowerVectorFPRoundLike(Op, DAG);
3296   case ISD::FP_TO_SINT:
3297   case ISD::FP_TO_UINT:
3298   case ISD::SINT_TO_FP:
3299   case ISD::UINT_TO_FP: {
3300     // RVV can only do fp<->int conversions to types half/double the size as
3301     // the source. We custom-lower any conversions that do two hops into
3302     // sequences.
3303     MVT VT = Op.getSimpleValueType();
3304     if (!VT.isVector())
3305       return Op;
3306     SDLoc DL(Op);
3307     SDValue Src = Op.getOperand(0);
3308     MVT EltVT = VT.getVectorElementType();
3309     MVT SrcVT = Src.getSimpleValueType();
3310     MVT SrcEltVT = SrcVT.getVectorElementType();
3311     unsigned EltSize = EltVT.getSizeInBits();
3312     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3313     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3314            "Unexpected vector element types");
3315 
3316     bool IsInt2FP = SrcEltVT.isInteger();
3317     // Widening conversions
3318     if (EltSize > (2 * SrcEltSize)) {
3319       if (IsInt2FP) {
3320         // Do a regular integer sign/zero extension then convert to float.
3321         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize),
3322                                       VT.getVectorElementCount());
3323         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3324                                  ? ISD::ZERO_EXTEND
3325                                  : ISD::SIGN_EXTEND;
3326         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3327         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3328       }
3329       // FP2Int
3330       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3331       // Do one doubling fp_extend then complete the operation by converting
3332       // to int.
3333       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3334       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3335       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3336     }
3337 
3338     // Narrowing conversions
3339     if (SrcEltSize > (2 * EltSize)) {
3340       if (IsInt2FP) {
3341         // One narrowing int_to_fp, then an fp_round.
3342         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3343         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3344         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3345         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3346       }
3347       // FP2Int
3348       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3349       // representable by the integer, the result is poison.
3350       MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
3351                                     VT.getVectorElementCount());
3352       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3353       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3354     }
3355 
3356     // Scalable vectors can exit here. Patterns will handle equally-sized
3357     // conversions halving/doubling ones.
3358     if (!VT.isFixedLengthVector())
3359       return Op;
3360 
3361     // For fixed-length vectors we lower to a custom "VL" node.
3362     unsigned RVVOpc = 0;
3363     switch (Op.getOpcode()) {
3364     default:
3365       llvm_unreachable("Impossible opcode");
3366     case ISD::FP_TO_SINT:
3367       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3368       break;
3369     case ISD::FP_TO_UINT:
3370       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3371       break;
3372     case ISD::SINT_TO_FP:
3373       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3374       break;
3375     case ISD::UINT_TO_FP:
3376       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3377       break;
3378     }
3379 
3380     MVT ContainerVT, SrcContainerVT;
3381     // Derive the reference container type from the larger vector type.
3382     if (SrcEltSize > EltSize) {
3383       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3384       ContainerVT =
3385           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3386     } else {
3387       ContainerVT = getContainerForFixedLengthVector(VT);
3388       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3389     }
3390 
3391     SDValue Mask, VL;
3392     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3393 
3394     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3395     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3396     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3397   }
3398   case ISD::FP_TO_SINT_SAT:
3399   case ISD::FP_TO_UINT_SAT:
3400     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3401   case ISD::FTRUNC:
3402   case ISD::FCEIL:
3403   case ISD::FFLOOR:
3404     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3405   case ISD::FROUND:
3406     return lowerFROUND(Op, DAG);
3407   case ISD::VECREDUCE_ADD:
3408   case ISD::VECREDUCE_UMAX:
3409   case ISD::VECREDUCE_SMAX:
3410   case ISD::VECREDUCE_UMIN:
3411   case ISD::VECREDUCE_SMIN:
3412     return lowerVECREDUCE(Op, DAG);
3413   case ISD::VECREDUCE_AND:
3414   case ISD::VECREDUCE_OR:
3415   case ISD::VECREDUCE_XOR:
3416     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3417       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3418     return lowerVECREDUCE(Op, DAG);
3419   case ISD::VECREDUCE_FADD:
3420   case ISD::VECREDUCE_SEQ_FADD:
3421   case ISD::VECREDUCE_FMIN:
3422   case ISD::VECREDUCE_FMAX:
3423     return lowerFPVECREDUCE(Op, DAG);
3424   case ISD::VP_REDUCE_ADD:
3425   case ISD::VP_REDUCE_UMAX:
3426   case ISD::VP_REDUCE_SMAX:
3427   case ISD::VP_REDUCE_UMIN:
3428   case ISD::VP_REDUCE_SMIN:
3429   case ISD::VP_REDUCE_FADD:
3430   case ISD::VP_REDUCE_SEQ_FADD:
3431   case ISD::VP_REDUCE_FMIN:
3432   case ISD::VP_REDUCE_FMAX:
3433     return lowerVPREDUCE(Op, DAG);
3434   case ISD::VP_REDUCE_AND:
3435   case ISD::VP_REDUCE_OR:
3436   case ISD::VP_REDUCE_XOR:
3437     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3438       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3439     return lowerVPREDUCE(Op, DAG);
3440   case ISD::INSERT_SUBVECTOR:
3441     return lowerINSERT_SUBVECTOR(Op, DAG);
3442   case ISD::EXTRACT_SUBVECTOR:
3443     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3444   case ISD::STEP_VECTOR:
3445     return lowerSTEP_VECTOR(Op, DAG);
3446   case ISD::VECTOR_REVERSE:
3447     return lowerVECTOR_REVERSE(Op, DAG);
3448   case ISD::VECTOR_SPLICE:
3449     return lowerVECTOR_SPLICE(Op, DAG);
3450   case ISD::BUILD_VECTOR:
3451     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3452   case ISD::SPLAT_VECTOR:
3453     if (Op.getValueType().getVectorElementType() == MVT::i1)
3454       return lowerVectorMaskSplat(Op, DAG);
3455     return SDValue();
3456   case ISD::VECTOR_SHUFFLE:
3457     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3458   case ISD::CONCAT_VECTORS: {
3459     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3460     // better than going through the stack, as the default expansion does.
3461     SDLoc DL(Op);
3462     MVT VT = Op.getSimpleValueType();
3463     unsigned NumOpElts =
3464         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3465     SDValue Vec = DAG.getUNDEF(VT);
3466     for (const auto &OpIdx : enumerate(Op->ops())) {
3467       SDValue SubVec = OpIdx.value();
3468       // Don't insert undef subvectors.
3469       if (SubVec.isUndef())
3470         continue;
3471       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3472                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3473     }
3474     return Vec;
3475   }
3476   case ISD::LOAD:
3477     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3478       return V;
3479     if (Op.getValueType().isFixedLengthVector())
3480       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3481     return Op;
3482   case ISD::STORE:
3483     if (auto V = expandUnalignedRVVStore(Op, DAG))
3484       return V;
3485     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3486       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3487     return Op;
3488   case ISD::MLOAD:
3489   case ISD::VP_LOAD:
3490     return lowerMaskedLoad(Op, DAG);
3491   case ISD::MSTORE:
3492   case ISD::VP_STORE:
3493     return lowerMaskedStore(Op, DAG);
3494   case ISD::SETCC:
3495     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3496   case ISD::ADD:
3497     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3498   case ISD::SUB:
3499     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3500   case ISD::MUL:
3501     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3502   case ISD::MULHS:
3503     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3504   case ISD::MULHU:
3505     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3506   case ISD::AND:
3507     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3508                                               RISCVISD::AND_VL);
3509   case ISD::OR:
3510     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3511                                               RISCVISD::OR_VL);
3512   case ISD::XOR:
3513     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3514                                               RISCVISD::XOR_VL);
3515   case ISD::SDIV:
3516     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3517   case ISD::SREM:
3518     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3519   case ISD::UDIV:
3520     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3521   case ISD::UREM:
3522     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3523   case ISD::SHL:
3524   case ISD::SRA:
3525   case ISD::SRL:
3526     if (Op.getSimpleValueType().isFixedLengthVector())
3527       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3528     // This can be called for an i32 shift amount that needs to be promoted.
3529     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3530            "Unexpected custom legalisation");
3531     return SDValue();
3532   case ISD::SADDSAT:
3533     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3534   case ISD::UADDSAT:
3535     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3536   case ISD::SSUBSAT:
3537     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3538   case ISD::USUBSAT:
3539     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3540   case ISD::FADD:
3541     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3542   case ISD::FSUB:
3543     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3544   case ISD::FMUL:
3545     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3546   case ISD::FDIV:
3547     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3548   case ISD::FNEG:
3549     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3550   case ISD::FABS:
3551     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3552   case ISD::FSQRT:
3553     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3554   case ISD::FMA:
3555     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3556   case ISD::SMIN:
3557     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3558   case ISD::SMAX:
3559     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3560   case ISD::UMIN:
3561     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3562   case ISD::UMAX:
3563     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3564   case ISD::FMINNUM:
3565     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3566   case ISD::FMAXNUM:
3567     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3568   case ISD::ABS:
3569     return lowerABS(Op, DAG);
3570   case ISD::CTLZ_ZERO_UNDEF:
3571   case ISD::CTTZ_ZERO_UNDEF:
3572     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3573   case ISD::VSELECT:
3574     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3575   case ISD::FCOPYSIGN:
3576     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3577   case ISD::MGATHER:
3578   case ISD::VP_GATHER:
3579     return lowerMaskedGather(Op, DAG);
3580   case ISD::MSCATTER:
3581   case ISD::VP_SCATTER:
3582     return lowerMaskedScatter(Op, DAG);
3583   case ISD::FLT_ROUNDS_:
3584     return lowerGET_ROUNDING(Op, DAG);
3585   case ISD::SET_ROUNDING:
3586     return lowerSET_ROUNDING(Op, DAG);
3587   case ISD::VP_SELECT:
3588     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3589   case ISD::VP_MERGE:
3590     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3591   case ISD::VP_ADD:
3592     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3593   case ISD::VP_SUB:
3594     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3595   case ISD::VP_MUL:
3596     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3597   case ISD::VP_SDIV:
3598     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3599   case ISD::VP_UDIV:
3600     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3601   case ISD::VP_SREM:
3602     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3603   case ISD::VP_UREM:
3604     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3605   case ISD::VP_AND:
3606     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3607   case ISD::VP_OR:
3608     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3609   case ISD::VP_XOR:
3610     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3611   case ISD::VP_ASHR:
3612     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3613   case ISD::VP_LSHR:
3614     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3615   case ISD::VP_SHL:
3616     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3617   case ISD::VP_FADD:
3618     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3619   case ISD::VP_FSUB:
3620     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3621   case ISD::VP_FMUL:
3622     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3623   case ISD::VP_FDIV:
3624     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3625   case ISD::VP_FNEG:
3626     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3627   case ISD::VP_FMA:
3628     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3629   case ISD::VP_SEXT:
3630   case ISD::VP_ZEXT:
3631     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3632       return lowerVPExtMaskOp(Op, DAG);
3633     return lowerVPOp(Op, DAG,
3634                      Op.getOpcode() == ISD::VP_SEXT ? RISCVISD::VSEXT_VL
3635                                                     : RISCVISD::VZEXT_VL);
3636   case ISD::VP_TRUNC:
3637     return lowerVectorTruncLike(Op, DAG);
3638   case ISD::VP_FP_ROUND:
3639     return lowerVectorFPRoundLike(Op, DAG);
3640   case ISD::VP_FPTOSI:
3641     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL);
3642   case ISD::VP_FPTOUI:
3643     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL);
3644   case ISD::VP_SITOFP:
3645     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
3646   case ISD::VP_UITOFP:
3647     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL);
3648   case ISD::VP_SETCC:
3649     return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL);
3650   }
3651 }
3652 
3653 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3654                              SelectionDAG &DAG, unsigned Flags) {
3655   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3656 }
3657 
3658 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3659                              SelectionDAG &DAG, unsigned Flags) {
3660   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3661                                    Flags);
3662 }
3663 
3664 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3665                              SelectionDAG &DAG, unsigned Flags) {
3666   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3667                                    N->getOffset(), Flags);
3668 }
3669 
3670 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3671                              SelectionDAG &DAG, unsigned Flags) {
3672   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3673 }
3674 
3675 template <class NodeTy>
3676 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3677                                      bool IsLocal) const {
3678   SDLoc DL(N);
3679   EVT Ty = getPointerTy(DAG.getDataLayout());
3680 
3681   if (isPositionIndependent()) {
3682     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3683     if (IsLocal)
3684       // Use PC-relative addressing to access the symbol. This generates the
3685       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3686       // %pcrel_lo(auipc)).
3687       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3688 
3689     // Use PC-relative addressing to access the GOT for this symbol, then load
3690     // the address from the GOT. This generates the pattern (PseudoLA sym),
3691     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3692     SDValue Load =
3693         SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3694     MachineFunction &MF = DAG.getMachineFunction();
3695     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3696         MachinePointerInfo::getGOT(MF),
3697         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3698             MachineMemOperand::MOInvariant,
3699         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3700     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3701     return Load;
3702   }
3703 
3704   switch (getTargetMachine().getCodeModel()) {
3705   default:
3706     report_fatal_error("Unsupported code model for lowering");
3707   case CodeModel::Small: {
3708     // Generate a sequence for accessing addresses within the first 2 GiB of
3709     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3710     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3711     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3712     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3713     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3714   }
3715   case CodeModel::Medium: {
3716     // Generate a sequence for accessing addresses within any 2GiB range within
3717     // the address space. This generates the pattern (PseudoLLA sym), which
3718     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3719     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3720     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3721   }
3722   }
3723 }
3724 
3725 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>(
3726     GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3727 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>(
3728     BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3729 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>(
3730     ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3731 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>(
3732     JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3733 
3734 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3735                                                 SelectionDAG &DAG) const {
3736   SDLoc DL(Op);
3737   EVT Ty = Op.getValueType();
3738   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3739   int64_t Offset = N->getOffset();
3740   MVT XLenVT = Subtarget.getXLenVT();
3741 
3742   const GlobalValue *GV = N->getGlobal();
3743   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3744   SDValue Addr = getAddr(N, DAG, IsLocal);
3745 
3746   // In order to maximise the opportunity for common subexpression elimination,
3747   // emit a separate ADD node for the global address offset instead of folding
3748   // it in the global address node. Later peephole optimisations may choose to
3749   // fold it back in when profitable.
3750   if (Offset != 0)
3751     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3752                        DAG.getConstant(Offset, DL, XLenVT));
3753   return Addr;
3754 }
3755 
3756 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3757                                                SelectionDAG &DAG) const {
3758   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3759 
3760   return getAddr(N, DAG);
3761 }
3762 
3763 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3764                                                SelectionDAG &DAG) const {
3765   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3766 
3767   return getAddr(N, DAG);
3768 }
3769 
3770 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3771                                             SelectionDAG &DAG) const {
3772   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3773 
3774   return getAddr(N, DAG);
3775 }
3776 
3777 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3778                                               SelectionDAG &DAG,
3779                                               bool UseGOT) const {
3780   SDLoc DL(N);
3781   EVT Ty = getPointerTy(DAG.getDataLayout());
3782   const GlobalValue *GV = N->getGlobal();
3783   MVT XLenVT = Subtarget.getXLenVT();
3784 
3785   if (UseGOT) {
3786     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3787     // load the address from the GOT and add the thread pointer. This generates
3788     // the pattern (PseudoLA_TLS_IE sym), which expands to
3789     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3790     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3791     SDValue Load =
3792         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3793     MachineFunction &MF = DAG.getMachineFunction();
3794     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3795         MachinePointerInfo::getGOT(MF),
3796         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3797             MachineMemOperand::MOInvariant,
3798         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3799     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3800 
3801     // Add the thread pointer.
3802     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3803     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3804   }
3805 
3806   // Generate a sequence for accessing the address relative to the thread
3807   // pointer, with the appropriate adjustment for the thread pointer offset.
3808   // This generates the pattern
3809   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3810   SDValue AddrHi =
3811       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3812   SDValue AddrAdd =
3813       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3814   SDValue AddrLo =
3815       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3816 
3817   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3818   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3819   SDValue MNAdd = SDValue(
3820       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3821       0);
3822   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3823 }
3824 
3825 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3826                                                SelectionDAG &DAG) const {
3827   SDLoc DL(N);
3828   EVT Ty = getPointerTy(DAG.getDataLayout());
3829   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3830   const GlobalValue *GV = N->getGlobal();
3831 
3832   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3833   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3834   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3835   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3836   SDValue Load =
3837       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3838 
3839   // Prepare argument list to generate call.
3840   ArgListTy Args;
3841   ArgListEntry Entry;
3842   Entry.Node = Load;
3843   Entry.Ty = CallTy;
3844   Args.push_back(Entry);
3845 
3846   // Setup call to __tls_get_addr.
3847   TargetLowering::CallLoweringInfo CLI(DAG);
3848   CLI.setDebugLoc(DL)
3849       .setChain(DAG.getEntryNode())
3850       .setLibCallee(CallingConv::C, CallTy,
3851                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3852                     std::move(Args));
3853 
3854   return LowerCallTo(CLI).first;
3855 }
3856 
3857 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3858                                                    SelectionDAG &DAG) const {
3859   SDLoc DL(Op);
3860   EVT Ty = Op.getValueType();
3861   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3862   int64_t Offset = N->getOffset();
3863   MVT XLenVT = Subtarget.getXLenVT();
3864 
3865   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3866 
3867   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3868       CallingConv::GHC)
3869     report_fatal_error("In GHC calling convention TLS is not supported");
3870 
3871   SDValue Addr;
3872   switch (Model) {
3873   case TLSModel::LocalExec:
3874     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3875     break;
3876   case TLSModel::InitialExec:
3877     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3878     break;
3879   case TLSModel::LocalDynamic:
3880   case TLSModel::GeneralDynamic:
3881     Addr = getDynamicTLSAddr(N, DAG);
3882     break;
3883   }
3884 
3885   // In order to maximise the opportunity for common subexpression elimination,
3886   // emit a separate ADD node for the global address offset instead of folding
3887   // it in the global address node. Later peephole optimisations may choose to
3888   // fold it back in when profitable.
3889   if (Offset != 0)
3890     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3891                        DAG.getConstant(Offset, DL, XLenVT));
3892   return Addr;
3893 }
3894 
3895 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3896   SDValue CondV = Op.getOperand(0);
3897   SDValue TrueV = Op.getOperand(1);
3898   SDValue FalseV = Op.getOperand(2);
3899   SDLoc DL(Op);
3900   MVT VT = Op.getSimpleValueType();
3901   MVT XLenVT = Subtarget.getXLenVT();
3902 
3903   // Lower vector SELECTs to VSELECTs by splatting the condition.
3904   if (VT.isVector()) {
3905     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3906     SDValue CondSplat = VT.isScalableVector()
3907                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3908                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3909     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3910   }
3911 
3912   // If the result type is XLenVT and CondV is the output of a SETCC node
3913   // which also operated on XLenVT inputs, then merge the SETCC node into the
3914   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3915   // compare+branch instructions. i.e.:
3916   // (select (setcc lhs, rhs, cc), truev, falsev)
3917   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3918   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3919       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3920     SDValue LHS = CondV.getOperand(0);
3921     SDValue RHS = CondV.getOperand(1);
3922     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3923     ISD::CondCode CCVal = CC->get();
3924 
3925     // Special case for a select of 2 constants that have a diffence of 1.
3926     // Normally this is done by DAGCombine, but if the select is introduced by
3927     // type legalization or op legalization, we miss it. Restricting to SETLT
3928     // case for now because that is what signed saturating add/sub need.
3929     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3930     // but we would probably want to swap the true/false values if the condition
3931     // is SETGE/SETLE to avoid an XORI.
3932     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3933         CCVal == ISD::SETLT) {
3934       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3935       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3936       if (TrueVal - 1 == FalseVal)
3937         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3938       if (TrueVal + 1 == FalseVal)
3939         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3940     }
3941 
3942     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3943 
3944     SDValue TargetCC = DAG.getCondCode(CCVal);
3945     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3946     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3947   }
3948 
3949   // Otherwise:
3950   // (select condv, truev, falsev)
3951   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3952   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3953   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3954 
3955   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3956 
3957   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3958 }
3959 
3960 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3961   SDValue CondV = Op.getOperand(1);
3962   SDLoc DL(Op);
3963   MVT XLenVT = Subtarget.getXLenVT();
3964 
3965   if (CondV.getOpcode() == ISD::SETCC &&
3966       CondV.getOperand(0).getValueType() == XLenVT) {
3967     SDValue LHS = CondV.getOperand(0);
3968     SDValue RHS = CondV.getOperand(1);
3969     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3970 
3971     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3972 
3973     SDValue TargetCC = DAG.getCondCode(CCVal);
3974     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3975                        LHS, RHS, TargetCC, Op.getOperand(2));
3976   }
3977 
3978   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3979                      CondV, DAG.getConstant(0, DL, XLenVT),
3980                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
3981 }
3982 
3983 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3984   MachineFunction &MF = DAG.getMachineFunction();
3985   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
3986 
3987   SDLoc DL(Op);
3988   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3989                                  getPointerTy(MF.getDataLayout()));
3990 
3991   // vastart just stores the address of the VarArgsFrameIndex slot into the
3992   // memory location argument.
3993   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3994   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
3995                       MachinePointerInfo(SV));
3996 }
3997 
3998 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
3999                                             SelectionDAG &DAG) const {
4000   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4001   MachineFunction &MF = DAG.getMachineFunction();
4002   MachineFrameInfo &MFI = MF.getFrameInfo();
4003   MFI.setFrameAddressIsTaken(true);
4004   Register FrameReg = RI.getFrameRegister(MF);
4005   int XLenInBytes = Subtarget.getXLen() / 8;
4006 
4007   EVT VT = Op.getValueType();
4008   SDLoc DL(Op);
4009   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
4010   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4011   while (Depth--) {
4012     int Offset = -(XLenInBytes * 2);
4013     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
4014                               DAG.getIntPtrConstant(Offset, DL));
4015     FrameAddr =
4016         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
4017   }
4018   return FrameAddr;
4019 }
4020 
4021 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
4022                                              SelectionDAG &DAG) const {
4023   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4024   MachineFunction &MF = DAG.getMachineFunction();
4025   MachineFrameInfo &MFI = MF.getFrameInfo();
4026   MFI.setReturnAddressIsTaken(true);
4027   MVT XLenVT = Subtarget.getXLenVT();
4028   int XLenInBytes = Subtarget.getXLen() / 8;
4029 
4030   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4031     return SDValue();
4032 
4033   EVT VT = Op.getValueType();
4034   SDLoc DL(Op);
4035   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4036   if (Depth) {
4037     int Off = -XLenInBytes;
4038     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4039     SDValue Offset = DAG.getConstant(Off, DL, VT);
4040     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4041                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4042                        MachinePointerInfo());
4043   }
4044 
4045   // Return the value of the return address register, marking it an implicit
4046   // live-in.
4047   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
4048   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
4049 }
4050 
4051 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
4052                                                  SelectionDAG &DAG) const {
4053   SDLoc DL(Op);
4054   SDValue Lo = Op.getOperand(0);
4055   SDValue Hi = Op.getOperand(1);
4056   SDValue Shamt = Op.getOperand(2);
4057   EVT VT = Lo.getValueType();
4058 
4059   // if Shamt-XLEN < 0: // Shamt < XLEN
4060   //   Lo = Lo << Shamt
4061   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
4062   // else:
4063   //   Lo = 0
4064   //   Hi = Lo << (Shamt-XLEN)
4065 
4066   SDValue Zero = DAG.getConstant(0, DL, VT);
4067   SDValue One = DAG.getConstant(1, DL, VT);
4068   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4069   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4070   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4071   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4072 
4073   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
4074   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
4075   SDValue ShiftRightLo =
4076       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
4077   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
4078   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
4079   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
4080 
4081   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4082 
4083   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
4084   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4085 
4086   SDValue Parts[2] = {Lo, Hi};
4087   return DAG.getMergeValues(Parts, DL);
4088 }
4089 
4090 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
4091                                                   bool IsSRA) const {
4092   SDLoc DL(Op);
4093   SDValue Lo = Op.getOperand(0);
4094   SDValue Hi = Op.getOperand(1);
4095   SDValue Shamt = Op.getOperand(2);
4096   EVT VT = Lo.getValueType();
4097 
4098   // SRA expansion:
4099   //   if Shamt-XLEN < 0: // Shamt < XLEN
4100   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4101   //     Hi = Hi >>s Shamt
4102   //   else:
4103   //     Lo = Hi >>s (Shamt-XLEN);
4104   //     Hi = Hi >>s (XLEN-1)
4105   //
4106   // SRL expansion:
4107   //   if Shamt-XLEN < 0: // Shamt < XLEN
4108   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4109   //     Hi = Hi >>u Shamt
4110   //   else:
4111   //     Lo = Hi >>u (Shamt-XLEN);
4112   //     Hi = 0;
4113 
4114   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4115 
4116   SDValue Zero = DAG.getConstant(0, DL, VT);
4117   SDValue One = DAG.getConstant(1, DL, VT);
4118   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4119   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4120   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4121   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4122 
4123   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4124   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4125   SDValue ShiftLeftHi =
4126       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4127   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4128   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4129   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4130   SDValue HiFalse =
4131       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4132 
4133   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4134 
4135   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4136   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4137 
4138   SDValue Parts[2] = {Lo, Hi};
4139   return DAG.getMergeValues(Parts, DL);
4140 }
4141 
4142 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4143 // legal equivalently-sized i8 type, so we can use that as a go-between.
4144 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4145                                                   SelectionDAG &DAG) const {
4146   SDLoc DL(Op);
4147   MVT VT = Op.getSimpleValueType();
4148   SDValue SplatVal = Op.getOperand(0);
4149   // All-zeros or all-ones splats are handled specially.
4150   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4151     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4152     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4153   }
4154   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4155     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4156     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4157   }
4158   MVT XLenVT = Subtarget.getXLenVT();
4159   assert(SplatVal.getValueType() == XLenVT &&
4160          "Unexpected type for i1 splat value");
4161   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4162   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4163                          DAG.getConstant(1, DL, XLenVT));
4164   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4165   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4166   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4167 }
4168 
4169 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4170 // illegal (currently only vXi64 RV32).
4171 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4172 // them to VMV_V_X_VL.
4173 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4174                                                      SelectionDAG &DAG) const {
4175   SDLoc DL(Op);
4176   MVT VecVT = Op.getSimpleValueType();
4177   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4178          "Unexpected SPLAT_VECTOR_PARTS lowering");
4179 
4180   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4181   SDValue Lo = Op.getOperand(0);
4182   SDValue Hi = Op.getOperand(1);
4183 
4184   if (VecVT.isFixedLengthVector()) {
4185     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4186     SDLoc DL(Op);
4187     SDValue Mask, VL;
4188     std::tie(Mask, VL) =
4189         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4190 
4191     SDValue Res =
4192         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4193     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4194   }
4195 
4196   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4197     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4198     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4199     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4200     // node in order to try and match RVV vector/scalar instructions.
4201     if ((LoC >> 31) == HiC)
4202       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4203                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4204   }
4205 
4206   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4207   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4208       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4209       Hi.getConstantOperandVal(1) == 31)
4210     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4211                        DAG.getRegister(RISCV::X0, MVT::i32));
4212 
4213   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4214   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4215                      DAG.getUNDEF(VecVT), Lo, Hi,
4216                      DAG.getRegister(RISCV::X0, MVT::i32));
4217 }
4218 
4219 // Custom-lower extensions from mask vectors by using a vselect either with 1
4220 // for zero/any-extension or -1 for sign-extension:
4221 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4222 // Note that any-extension is lowered identically to zero-extension.
4223 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4224                                                 int64_t ExtTrueVal) const {
4225   SDLoc DL(Op);
4226   MVT VecVT = Op.getSimpleValueType();
4227   SDValue Src = Op.getOperand(0);
4228   // Only custom-lower extensions from mask types
4229   assert(Src.getValueType().isVector() &&
4230          Src.getValueType().getVectorElementType() == MVT::i1);
4231 
4232   if (VecVT.isScalableVector()) {
4233     SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
4234     SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
4235     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4236   }
4237 
4238   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4239   MVT I1ContainerVT =
4240       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4241 
4242   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4243 
4244   SDValue Mask, VL;
4245   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4246 
4247   MVT XLenVT = Subtarget.getXLenVT();
4248   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4249   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4250 
4251   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4252                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4253   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4254                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4255   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4256                                SplatTrueVal, SplatZero, VL);
4257 
4258   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4259 }
4260 
4261 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4262     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4263   MVT ExtVT = Op.getSimpleValueType();
4264   // Only custom-lower extensions from fixed-length vector types.
4265   if (!ExtVT.isFixedLengthVector())
4266     return Op;
4267   MVT VT = Op.getOperand(0).getSimpleValueType();
4268   // Grab the canonical container type for the extended type. Infer the smaller
4269   // type from that to ensure the same number of vector elements, as we know
4270   // the LMUL will be sufficient to hold the smaller type.
4271   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4272   // Get the extended container type manually to ensure the same number of
4273   // vector elements between source and dest.
4274   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4275                                      ContainerExtVT.getVectorElementCount());
4276 
4277   SDValue Op1 =
4278       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4279 
4280   SDLoc DL(Op);
4281   SDValue Mask, VL;
4282   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4283 
4284   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4285 
4286   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4287 }
4288 
4289 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4290 // setcc operation:
4291 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4292 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op,
4293                                                       SelectionDAG &DAG) const {
4294   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNC;
4295   SDLoc DL(Op);
4296   EVT MaskVT = Op.getValueType();
4297   // Only expect to custom-lower truncations to mask types
4298   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4299          "Unexpected type for vector mask lowering");
4300   SDValue Src = Op.getOperand(0);
4301   MVT VecVT = Src.getSimpleValueType();
4302   SDValue Mask, VL;
4303   if (IsVPTrunc) {
4304     Mask = Op.getOperand(1);
4305     VL = Op.getOperand(2);
4306   }
4307   // If this is a fixed vector, we need to convert it to a scalable vector.
4308   MVT ContainerVT = VecVT;
4309 
4310   if (VecVT.isFixedLengthVector()) {
4311     ContainerVT = getContainerForFixedLengthVector(VecVT);
4312     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4313     if (IsVPTrunc) {
4314       MVT MaskContainerVT =
4315           getContainerForFixedLengthVector(Mask.getSimpleValueType());
4316       Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget);
4317     }
4318   }
4319 
4320   if (!IsVPTrunc) {
4321     std::tie(Mask, VL) =
4322         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4323   }
4324 
4325   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4326   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4327 
4328   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4329                          DAG.getUNDEF(ContainerVT), SplatOne, VL);
4330   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4331                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4332 
4333   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4334   SDValue Trunc =
4335       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4336   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4337                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4338   if (MaskVT.isFixedLengthVector())
4339     Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4340   return Trunc;
4341 }
4342 
4343 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op,
4344                                                   SelectionDAG &DAG) const {
4345   bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNC;
4346   SDLoc DL(Op);
4347 
4348   MVT VT = Op.getSimpleValueType();
4349   // Only custom-lower vector truncates
4350   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4351 
4352   // Truncates to mask types are handled differently
4353   if (VT.getVectorElementType() == MVT::i1)
4354     return lowerVectorMaskTruncLike(Op, DAG);
4355 
4356   // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
4357   // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
4358   // truncate by one power of two at a time.
4359   MVT DstEltVT = VT.getVectorElementType();
4360 
4361   SDValue Src = Op.getOperand(0);
4362   MVT SrcVT = Src.getSimpleValueType();
4363   MVT SrcEltVT = SrcVT.getVectorElementType();
4364 
4365   assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) &&
4366          isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
4367          "Unexpected vector truncate lowering");
4368 
4369   MVT ContainerVT = SrcVT;
4370   SDValue Mask, VL;
4371   if (IsVPTrunc) {
4372     Mask = Op.getOperand(1);
4373     VL = Op.getOperand(2);
4374   }
4375   if (SrcVT.isFixedLengthVector()) {
4376     ContainerVT = getContainerForFixedLengthVector(SrcVT);
4377     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4378     if (IsVPTrunc) {
4379       MVT MaskVT =
4380           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4381       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4382     }
4383   }
4384 
4385   SDValue Result = Src;
4386   if (!IsVPTrunc) {
4387     std::tie(Mask, VL) =
4388         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4389   }
4390 
4391   LLVMContext &Context = *DAG.getContext();
4392   const ElementCount Count = ContainerVT.getVectorElementCount();
4393   do {
4394     SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
4395     EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
4396     Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
4397                          Mask, VL);
4398   } while (SrcEltVT != DstEltVT);
4399 
4400   if (SrcVT.isFixedLengthVector())
4401     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4402 
4403   return Result;
4404 }
4405 
4406 SDValue RISCVTargetLowering::lowerVectorFPRoundLike(SDValue Op,
4407                                                     SelectionDAG &DAG) const {
4408   bool IsVPFPTrunc = Op.getOpcode() == ISD::VP_FP_ROUND;
4409   // RVV can only do truncate fp to types half the size as the source. We
4410   // custom-lower f64->f16 rounds via RVV's round-to-odd float
4411   // conversion instruction.
4412   SDLoc DL(Op);
4413   MVT VT = Op.getSimpleValueType();
4414 
4415   assert(VT.isVector() && "Unexpected type for vector truncate lowering");
4416 
4417   SDValue Src = Op.getOperand(0);
4418   MVT SrcVT = Src.getSimpleValueType();
4419 
4420   bool IsDirectConv = VT.getVectorElementType() != MVT::f16 ||
4421                       SrcVT.getVectorElementType() != MVT::f64;
4422 
4423   // For FP_ROUND of scalable vectors, leave it to the pattern.
4424   if (!VT.isFixedLengthVector() && !IsVPFPTrunc && IsDirectConv)
4425     return Op;
4426 
4427   // Prepare any fixed-length vector operands.
4428   MVT ContainerVT = VT;
4429   SDValue Mask, VL;
4430   if (IsVPFPTrunc) {
4431     Mask = Op.getOperand(1);
4432     VL = Op.getOperand(2);
4433   }
4434   if (VT.isFixedLengthVector()) {
4435     MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
4436     ContainerVT =
4437         SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
4438     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
4439     if (IsVPFPTrunc) {
4440       MVT MaskVT =
4441           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4442       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4443     }
4444   }
4445 
4446   if (!IsVPFPTrunc)
4447     std::tie(Mask, VL) =
4448         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
4449 
4450   if (IsDirectConv) {
4451     Src = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, ContainerVT, Src, Mask, VL);
4452     if (VT.isFixedLengthVector())
4453       Src = convertFromScalableVector(VT, Src, DAG, Subtarget);
4454     return Src;
4455   }
4456 
4457   MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
4458   SDValue IntermediateRound =
4459       DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
4460   SDValue Round = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, ContainerVT,
4461                               IntermediateRound, Mask, VL);
4462   if (VT.isFixedLengthVector())
4463     return convertFromScalableVector(VT, Round, DAG, Subtarget);
4464   return Round;
4465 }
4466 
4467 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4468 // first position of a vector, and that vector is slid up to the insert index.
4469 // By limiting the active vector length to index+1 and merging with the
4470 // original vector (with an undisturbed tail policy for elements >= VL), we
4471 // achieve the desired result of leaving all elements untouched except the one
4472 // at VL-1, which is replaced with the desired value.
4473 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4474                                                     SelectionDAG &DAG) const {
4475   SDLoc DL(Op);
4476   MVT VecVT = Op.getSimpleValueType();
4477   SDValue Vec = Op.getOperand(0);
4478   SDValue Val = Op.getOperand(1);
4479   SDValue Idx = Op.getOperand(2);
4480 
4481   if (VecVT.getVectorElementType() == MVT::i1) {
4482     // FIXME: For now we just promote to an i8 vector and insert into that,
4483     // but this is probably not optimal.
4484     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4485     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4486     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4487     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4488   }
4489 
4490   MVT ContainerVT = VecVT;
4491   // If the operand is a fixed-length vector, convert to a scalable one.
4492   if (VecVT.isFixedLengthVector()) {
4493     ContainerVT = getContainerForFixedLengthVector(VecVT);
4494     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4495   }
4496 
4497   MVT XLenVT = Subtarget.getXLenVT();
4498 
4499   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4500   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4501   // Even i64-element vectors on RV32 can be lowered without scalar
4502   // legalization if the most-significant 32 bits of the value are not affected
4503   // by the sign-extension of the lower 32 bits.
4504   // TODO: We could also catch sign extensions of a 32-bit value.
4505   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4506     const auto *CVal = cast<ConstantSDNode>(Val);
4507     if (isInt<32>(CVal->getSExtValue())) {
4508       IsLegalInsert = true;
4509       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4510     }
4511   }
4512 
4513   SDValue Mask, VL;
4514   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4515 
4516   SDValue ValInVec;
4517 
4518   if (IsLegalInsert) {
4519     unsigned Opc =
4520         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4521     if (isNullConstant(Idx)) {
4522       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4523       if (!VecVT.isFixedLengthVector())
4524         return Vec;
4525       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4526     }
4527     ValInVec =
4528         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4529   } else {
4530     // On RV32, i64-element vectors must be specially handled to place the
4531     // value at element 0, by using two vslide1up instructions in sequence on
4532     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4533     // this.
4534     SDValue One = DAG.getConstant(1, DL, XLenVT);
4535     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4536     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4537     MVT I32ContainerVT =
4538         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4539     SDValue I32Mask =
4540         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4541     // Limit the active VL to two.
4542     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4543     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4544     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4545     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4546                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4547     // First slide in the hi value, then the lo in underneath it.
4548     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4549                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4550                            I32Mask, InsertI64VL);
4551     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4552                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4553                            I32Mask, InsertI64VL);
4554     // Bitcast back to the right container type.
4555     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4556   }
4557 
4558   // Now that the value is in a vector, slide it into position.
4559   SDValue InsertVL =
4560       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4561   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4562                                 ValInVec, Idx, Mask, InsertVL);
4563   if (!VecVT.isFixedLengthVector())
4564     return Slideup;
4565   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4566 }
4567 
4568 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4569 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4570 // types this is done using VMV_X_S to allow us to glean information about the
4571 // sign bits of the result.
4572 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4573                                                      SelectionDAG &DAG) const {
4574   SDLoc DL(Op);
4575   SDValue Idx = Op.getOperand(1);
4576   SDValue Vec = Op.getOperand(0);
4577   EVT EltVT = Op.getValueType();
4578   MVT VecVT = Vec.getSimpleValueType();
4579   MVT XLenVT = Subtarget.getXLenVT();
4580 
4581   if (VecVT.getVectorElementType() == MVT::i1) {
4582     if (VecVT.isFixedLengthVector()) {
4583       unsigned NumElts = VecVT.getVectorNumElements();
4584       if (NumElts >= 8) {
4585         MVT WideEltVT;
4586         unsigned WidenVecLen;
4587         SDValue ExtractElementIdx;
4588         SDValue ExtractBitIdx;
4589         unsigned MaxEEW = Subtarget.getELEN();
4590         MVT LargestEltVT = MVT::getIntegerVT(
4591             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4592         if (NumElts <= LargestEltVT.getSizeInBits()) {
4593           assert(isPowerOf2_32(NumElts) &&
4594                  "the number of elements should be power of 2");
4595           WideEltVT = MVT::getIntegerVT(NumElts);
4596           WidenVecLen = 1;
4597           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4598           ExtractBitIdx = Idx;
4599         } else {
4600           WideEltVT = LargestEltVT;
4601           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4602           // extract element index = index / element width
4603           ExtractElementIdx = DAG.getNode(
4604               ISD::SRL, DL, XLenVT, Idx,
4605               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4606           // mask bit index = index % element width
4607           ExtractBitIdx = DAG.getNode(
4608               ISD::AND, DL, XLenVT, Idx,
4609               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4610         }
4611         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4612         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4613         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4614                                          Vec, ExtractElementIdx);
4615         // Extract the bit from GPR.
4616         SDValue ShiftRight =
4617             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4618         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4619                            DAG.getConstant(1, DL, XLenVT));
4620       }
4621     }
4622     // Otherwise, promote to an i8 vector and extract from that.
4623     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4624     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4625     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4626   }
4627 
4628   // If this is a fixed vector, we need to convert it to a scalable vector.
4629   MVT ContainerVT = VecVT;
4630   if (VecVT.isFixedLengthVector()) {
4631     ContainerVT = getContainerForFixedLengthVector(VecVT);
4632     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4633   }
4634 
4635   // If the index is 0, the vector is already in the right position.
4636   if (!isNullConstant(Idx)) {
4637     // Use a VL of 1 to avoid processing more elements than we need.
4638     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4639     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4640     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4641     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4642                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4643   }
4644 
4645   if (!EltVT.isInteger()) {
4646     // Floating-point extracts are handled in TableGen.
4647     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4648                        DAG.getConstant(0, DL, XLenVT));
4649   }
4650 
4651   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4652   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4653 }
4654 
4655 // Some RVV intrinsics may claim that they want an integer operand to be
4656 // promoted or expanded.
4657 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4658                                            const RISCVSubtarget &Subtarget) {
4659   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4660           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4661          "Unexpected opcode");
4662 
4663   if (!Subtarget.hasVInstructions())
4664     return SDValue();
4665 
4666   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4667   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4668   SDLoc DL(Op);
4669 
4670   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4671       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4672   if (!II || !II->hasScalarOperand())
4673     return SDValue();
4674 
4675   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4676   assert(SplatOp < Op.getNumOperands());
4677 
4678   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4679   SDValue &ScalarOp = Operands[SplatOp];
4680   MVT OpVT = ScalarOp.getSimpleValueType();
4681   MVT XLenVT = Subtarget.getXLenVT();
4682 
4683   // If this isn't a scalar, or its type is XLenVT we're done.
4684   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4685     return SDValue();
4686 
4687   // Simplest case is that the operand needs to be promoted to XLenVT.
4688   if (OpVT.bitsLT(XLenVT)) {
4689     // If the operand is a constant, sign extend to increase our chances
4690     // of being able to use a .vi instruction. ANY_EXTEND would become a
4691     // a zero extend and the simm5 check in isel would fail.
4692     // FIXME: Should we ignore the upper bits in isel instead?
4693     unsigned ExtOpc =
4694         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4695     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4696     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4697   }
4698 
4699   // Use the previous operand to get the vXi64 VT. The result might be a mask
4700   // VT for compares. Using the previous operand assumes that the previous
4701   // operand will never have a smaller element size than a scalar operand and
4702   // that a widening operation never uses SEW=64.
4703   // NOTE: If this fails the below assert, we can probably just find the
4704   // element count from any operand or result and use it to construct the VT.
4705   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4706   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4707 
4708   // The more complex case is when the scalar is larger than XLenVT.
4709   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4710          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4711 
4712   // If this is a sign-extended 32-bit value, we can truncate it and rely on the
4713   // instruction to sign-extend since SEW>XLEN.
4714   if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
4715     ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
4716     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4717   }
4718 
4719   switch (IntNo) {
4720   case Intrinsic::riscv_vslide1up:
4721   case Intrinsic::riscv_vslide1down:
4722   case Intrinsic::riscv_vslide1up_mask:
4723   case Intrinsic::riscv_vslide1down_mask: {
4724     // We need to special case these when the scalar is larger than XLen.
4725     unsigned NumOps = Op.getNumOperands();
4726     bool IsMasked = NumOps == 7;
4727 
4728     // Convert the vector source to the equivalent nxvXi32 vector.
4729     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4730     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4731 
4732     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4733                                    DAG.getConstant(0, DL, XLenVT));
4734     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4735                                    DAG.getConstant(1, DL, XLenVT));
4736 
4737     // Double the VL since we halved SEW.
4738     SDValue AVL = getVLOperand(Op);
4739     SDValue I32VL;
4740 
4741     // Optimize for constant AVL
4742     if (isa<ConstantSDNode>(AVL)) {
4743       unsigned EltSize = VT.getScalarSizeInBits();
4744       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4745 
4746       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4747       unsigned MaxVLMAX =
4748           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4749 
4750       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4751       unsigned MinVLMAX =
4752           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4753 
4754       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4755       if (AVLInt <= MinVLMAX) {
4756         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4757       } else if (AVLInt >= 2 * MaxVLMAX) {
4758         // Just set vl to VLMAX in this situation
4759         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4760         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4761         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4762         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4763         SDValue SETVLMAX = DAG.getTargetConstant(
4764             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4765         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4766                             LMUL);
4767       } else {
4768         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4769         // is related to the hardware implementation.
4770         // So let the following code handle
4771       }
4772     }
4773     if (!I32VL) {
4774       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4775       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4776       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4777       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4778       SDValue SETVL =
4779           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4780       // Using vsetvli instruction to get actually used length which related to
4781       // the hardware implementation
4782       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4783                                SEW, LMUL);
4784       I32VL =
4785           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4786     }
4787 
4788     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4789     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, I32VL);
4790 
4791     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4792     // instructions.
4793     SDValue Passthru;
4794     if (IsMasked)
4795       Passthru = DAG.getUNDEF(I32VT);
4796     else
4797       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4798 
4799     if (IntNo == Intrinsic::riscv_vslide1up ||
4800         IntNo == Intrinsic::riscv_vslide1up_mask) {
4801       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4802                         ScalarHi, I32Mask, I32VL);
4803       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4804                         ScalarLo, I32Mask, I32VL);
4805     } else {
4806       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4807                         ScalarLo, I32Mask, I32VL);
4808       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4809                         ScalarHi, I32Mask, I32VL);
4810     }
4811 
4812     // Convert back to nxvXi64.
4813     Vec = DAG.getBitcast(VT, Vec);
4814 
4815     if (!IsMasked)
4816       return Vec;
4817     // Apply mask after the operation.
4818     SDValue Mask = Operands[NumOps - 3];
4819     SDValue MaskedOff = Operands[1];
4820     // Assume Policy operand is the last operand.
4821     uint64_t Policy =
4822         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4823     // We don't need to select maskedoff if it's undef.
4824     if (MaskedOff.isUndef())
4825       return Vec;
4826     // TAMU
4827     if (Policy == RISCVII::TAIL_AGNOSTIC)
4828       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4829                          AVL);
4830     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4831     // It's fine because vmerge does not care mask policy.
4832     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4833                        AVL);
4834   }
4835   }
4836 
4837   // We need to convert the scalar to a splat vector.
4838   SDValue VL = getVLOperand(Op);
4839   assert(VL.getValueType() == XLenVT);
4840   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4841   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4842 }
4843 
4844 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4845                                                      SelectionDAG &DAG) const {
4846   unsigned IntNo = Op.getConstantOperandVal(0);
4847   SDLoc DL(Op);
4848   MVT XLenVT = Subtarget.getXLenVT();
4849 
4850   switch (IntNo) {
4851   default:
4852     break; // Don't custom lower most intrinsics.
4853   case Intrinsic::thread_pointer: {
4854     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4855     return DAG.getRegister(RISCV::X4, PtrVT);
4856   }
4857   case Intrinsic::riscv_orc_b:
4858   case Intrinsic::riscv_brev8: {
4859     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4860     unsigned Opc =
4861         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4862     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4863                        DAG.getConstant(7, DL, XLenVT));
4864   }
4865   case Intrinsic::riscv_grev:
4866   case Intrinsic::riscv_gorc: {
4867     unsigned Opc =
4868         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4869     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4870   }
4871   case Intrinsic::riscv_zip:
4872   case Intrinsic::riscv_unzip: {
4873     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4874     // For i32 the immediate is 15. For i64 the immediate is 31.
4875     unsigned Opc =
4876         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4877     unsigned BitWidth = Op.getValueSizeInBits();
4878     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4879     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4880                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4881   }
4882   case Intrinsic::riscv_shfl:
4883   case Intrinsic::riscv_unshfl: {
4884     unsigned Opc =
4885         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4886     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4887   }
4888   case Intrinsic::riscv_bcompress:
4889   case Intrinsic::riscv_bdecompress: {
4890     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4891                                                        : RISCVISD::BDECOMPRESS;
4892     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4893   }
4894   case Intrinsic::riscv_bfp:
4895     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4896                        Op.getOperand(2));
4897   case Intrinsic::riscv_fsl:
4898     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4899                        Op.getOperand(2), Op.getOperand(3));
4900   case Intrinsic::riscv_fsr:
4901     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4902                        Op.getOperand(2), Op.getOperand(3));
4903   case Intrinsic::riscv_vmv_x_s:
4904     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4905     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4906                        Op.getOperand(1));
4907   case Intrinsic::riscv_vmv_v_x:
4908     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4909                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4910                             Subtarget);
4911   case Intrinsic::riscv_vfmv_v_f:
4912     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4913                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4914   case Intrinsic::riscv_vmv_s_x: {
4915     SDValue Scalar = Op.getOperand(2);
4916 
4917     if (Scalar.getValueType().bitsLE(XLenVT)) {
4918       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4919       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4920                          Op.getOperand(1), Scalar, Op.getOperand(3));
4921     }
4922 
4923     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4924 
4925     // This is an i64 value that lives in two scalar registers. We have to
4926     // insert this in a convoluted way. First we build vXi64 splat containing
4927     // the two values that we assemble using some bit math. Next we'll use
4928     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4929     // to merge element 0 from our splat into the source vector.
4930     // FIXME: This is probably not the best way to do this, but it is
4931     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4932     // point.
4933     //   sw lo, (a0)
4934     //   sw hi, 4(a0)
4935     //   vlse vX, (a0)
4936     //
4937     //   vid.v      vVid
4938     //   vmseq.vx   mMask, vVid, 0
4939     //   vmerge.vvm vDest, vSrc, vVal, mMask
4940     MVT VT = Op.getSimpleValueType();
4941     SDValue Vec = Op.getOperand(1);
4942     SDValue VL = getVLOperand(Op);
4943 
4944     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4945     if (Op.getOperand(1).isUndef())
4946       return SplattedVal;
4947     SDValue SplattedIdx =
4948         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4949                     DAG.getConstant(0, DL, MVT::i32), VL);
4950 
4951     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4952     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4953     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4954     SDValue SelectCond =
4955         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4956                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4957     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4958                        Vec, VL);
4959   }
4960   }
4961 
4962   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4963 }
4964 
4965 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4966                                                     SelectionDAG &DAG) const {
4967   unsigned IntNo = Op.getConstantOperandVal(1);
4968   switch (IntNo) {
4969   default:
4970     break;
4971   case Intrinsic::riscv_masked_strided_load: {
4972     SDLoc DL(Op);
4973     MVT XLenVT = Subtarget.getXLenVT();
4974 
4975     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4976     // the selection of the masked intrinsics doesn't do this for us.
4977     SDValue Mask = Op.getOperand(5);
4978     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4979 
4980     MVT VT = Op->getSimpleValueType(0);
4981     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4982 
4983     SDValue PassThru = Op.getOperand(2);
4984     if (!IsUnmasked) {
4985       MVT MaskVT =
4986           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4987       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4988       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4989     }
4990 
4991     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4992 
4993     SDValue IntID = DAG.getTargetConstant(
4994         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4995         XLenVT);
4996 
4997     auto *Load = cast<MemIntrinsicSDNode>(Op);
4998     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4999     if (IsUnmasked)
5000       Ops.push_back(DAG.getUNDEF(ContainerVT));
5001     else
5002       Ops.push_back(PassThru);
5003     Ops.push_back(Op.getOperand(3)); // Ptr
5004     Ops.push_back(Op.getOperand(4)); // Stride
5005     if (!IsUnmasked)
5006       Ops.push_back(Mask);
5007     Ops.push_back(VL);
5008     if (!IsUnmasked) {
5009       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
5010       Ops.push_back(Policy);
5011     }
5012 
5013     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5014     SDValue Result =
5015         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5016                                 Load->getMemoryVT(), Load->getMemOperand());
5017     SDValue Chain = Result.getValue(1);
5018     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5019     return DAG.getMergeValues({Result, Chain}, DL);
5020   }
5021   case Intrinsic::riscv_seg2_load:
5022   case Intrinsic::riscv_seg3_load:
5023   case Intrinsic::riscv_seg4_load:
5024   case Intrinsic::riscv_seg5_load:
5025   case Intrinsic::riscv_seg6_load:
5026   case Intrinsic::riscv_seg7_load:
5027   case Intrinsic::riscv_seg8_load: {
5028     SDLoc DL(Op);
5029     static const Intrinsic::ID VlsegInts[7] = {
5030         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
5031         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
5032         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
5033         Intrinsic::riscv_vlseg8};
5034     unsigned NF = Op->getNumValues() - 1;
5035     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
5036     MVT XLenVT = Subtarget.getXLenVT();
5037     MVT VT = Op->getSimpleValueType(0);
5038     MVT ContainerVT = getContainerForFixedLengthVector(VT);
5039 
5040     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5041     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
5042     auto *Load = cast<MemIntrinsicSDNode>(Op);
5043     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
5044     ContainerVTs.push_back(MVT::Other);
5045     SDVTList VTs = DAG.getVTList(ContainerVTs);
5046     SDValue Result =
5047         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs,
5048                                 {Load->getChain(), IntID, Op.getOperand(2), VL},
5049                                 Load->getMemoryVT(), Load->getMemOperand());
5050     SmallVector<SDValue, 9> Results;
5051     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
5052       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
5053                                                   DAG, Subtarget));
5054     Results.push_back(Result.getValue(NF));
5055     return DAG.getMergeValues(Results, DL);
5056   }
5057   }
5058 
5059   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
5060 }
5061 
5062 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
5063                                                  SelectionDAG &DAG) const {
5064   unsigned IntNo = Op.getConstantOperandVal(1);
5065   switch (IntNo) {
5066   default:
5067     break;
5068   case Intrinsic::riscv_masked_strided_store: {
5069     SDLoc DL(Op);
5070     MVT XLenVT = Subtarget.getXLenVT();
5071 
5072     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5073     // the selection of the masked intrinsics doesn't do this for us.
5074     SDValue Mask = Op.getOperand(5);
5075     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5076 
5077     SDValue Val = Op.getOperand(2);
5078     MVT VT = Val.getSimpleValueType();
5079     MVT ContainerVT = getContainerForFixedLengthVector(VT);
5080 
5081     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5082     if (!IsUnmasked) {
5083       MVT MaskVT =
5084           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5085       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5086     }
5087 
5088     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5089 
5090     SDValue IntID = DAG.getTargetConstant(
5091         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
5092         XLenVT);
5093 
5094     auto *Store = cast<MemIntrinsicSDNode>(Op);
5095     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
5096     Ops.push_back(Val);
5097     Ops.push_back(Op.getOperand(3)); // Ptr
5098     Ops.push_back(Op.getOperand(4)); // Stride
5099     if (!IsUnmasked)
5100       Ops.push_back(Mask);
5101     Ops.push_back(VL);
5102 
5103     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
5104                                    Ops, Store->getMemoryVT(),
5105                                    Store->getMemOperand());
5106   }
5107   }
5108 
5109   return SDValue();
5110 }
5111 
5112 static MVT getLMUL1VT(MVT VT) {
5113   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
5114          "Unexpected vector MVT");
5115   return MVT::getScalableVectorVT(
5116       VT.getVectorElementType(),
5117       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
5118 }
5119 
5120 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
5121   switch (ISDOpcode) {
5122   default:
5123     llvm_unreachable("Unhandled reduction");
5124   case ISD::VECREDUCE_ADD:
5125     return RISCVISD::VECREDUCE_ADD_VL;
5126   case ISD::VECREDUCE_UMAX:
5127     return RISCVISD::VECREDUCE_UMAX_VL;
5128   case ISD::VECREDUCE_SMAX:
5129     return RISCVISD::VECREDUCE_SMAX_VL;
5130   case ISD::VECREDUCE_UMIN:
5131     return RISCVISD::VECREDUCE_UMIN_VL;
5132   case ISD::VECREDUCE_SMIN:
5133     return RISCVISD::VECREDUCE_SMIN_VL;
5134   case ISD::VECREDUCE_AND:
5135     return RISCVISD::VECREDUCE_AND_VL;
5136   case ISD::VECREDUCE_OR:
5137     return RISCVISD::VECREDUCE_OR_VL;
5138   case ISD::VECREDUCE_XOR:
5139     return RISCVISD::VECREDUCE_XOR_VL;
5140   }
5141 }
5142 
5143 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
5144                                                          SelectionDAG &DAG,
5145                                                          bool IsVP) const {
5146   SDLoc DL(Op);
5147   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5148   MVT VecVT = Vec.getSimpleValueType();
5149   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5150           Op.getOpcode() == ISD::VECREDUCE_OR ||
5151           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5152           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5153           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5154           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5155          "Unexpected reduction lowering");
5156 
5157   MVT XLenVT = Subtarget.getXLenVT();
5158   assert(Op.getValueType() == XLenVT &&
5159          "Expected reduction output to be legalized to XLenVT");
5160 
5161   MVT ContainerVT = VecVT;
5162   if (VecVT.isFixedLengthVector()) {
5163     ContainerVT = getContainerForFixedLengthVector(VecVT);
5164     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5165   }
5166 
5167   SDValue Mask, VL;
5168   if (IsVP) {
5169     Mask = Op.getOperand(2);
5170     VL = Op.getOperand(3);
5171   } else {
5172     std::tie(Mask, VL) =
5173         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5174   }
5175 
5176   unsigned BaseOpc;
5177   ISD::CondCode CC;
5178   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5179 
5180   switch (Op.getOpcode()) {
5181   default:
5182     llvm_unreachable("Unhandled reduction");
5183   case ISD::VECREDUCE_AND:
5184   case ISD::VP_REDUCE_AND: {
5185     // vcpop ~x == 0
5186     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5187     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5188     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5189     CC = ISD::SETEQ;
5190     BaseOpc = ISD::AND;
5191     break;
5192   }
5193   case ISD::VECREDUCE_OR:
5194   case ISD::VP_REDUCE_OR:
5195     // vcpop x != 0
5196     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5197     CC = ISD::SETNE;
5198     BaseOpc = ISD::OR;
5199     break;
5200   case ISD::VECREDUCE_XOR:
5201   case ISD::VP_REDUCE_XOR: {
5202     // ((vcpop x) & 1) != 0
5203     SDValue One = DAG.getConstant(1, DL, XLenVT);
5204     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5205     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5206     CC = ISD::SETNE;
5207     BaseOpc = ISD::XOR;
5208     break;
5209   }
5210   }
5211 
5212   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5213 
5214   if (!IsVP)
5215     return SetCC;
5216 
5217   // Now include the start value in the operation.
5218   // Note that we must return the start value when no elements are operated
5219   // upon. The vcpop instructions we've emitted in each case above will return
5220   // 0 for an inactive vector, and so we've already received the neutral value:
5221   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5222   // can simply include the start value.
5223   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5224 }
5225 
5226 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5227                                             SelectionDAG &DAG) const {
5228   SDLoc DL(Op);
5229   SDValue Vec = Op.getOperand(0);
5230   EVT VecEVT = Vec.getValueType();
5231 
5232   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5233 
5234   // Due to ordering in legalize types we may have a vector type that needs to
5235   // be split. Do that manually so we can get down to a legal type.
5236   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5237          TargetLowering::TypeSplitVector) {
5238     SDValue Lo, Hi;
5239     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5240     VecEVT = Lo.getValueType();
5241     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5242   }
5243 
5244   // TODO: The type may need to be widened rather than split. Or widened before
5245   // it can be split.
5246   if (!isTypeLegal(VecEVT))
5247     return SDValue();
5248 
5249   MVT VecVT = VecEVT.getSimpleVT();
5250   MVT VecEltVT = VecVT.getVectorElementType();
5251   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5252 
5253   MVT ContainerVT = VecVT;
5254   if (VecVT.isFixedLengthVector()) {
5255     ContainerVT = getContainerForFixedLengthVector(VecVT);
5256     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5257   }
5258 
5259   MVT M1VT = getLMUL1VT(ContainerVT);
5260   MVT XLenVT = Subtarget.getXLenVT();
5261 
5262   SDValue Mask, VL;
5263   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5264 
5265   SDValue NeutralElem =
5266       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5267   SDValue IdentitySplat =
5268       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5269                        M1VT, DL, DAG, Subtarget);
5270   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5271                                   IdentitySplat, Mask, VL);
5272   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5273                              DAG.getConstant(0, DL, XLenVT));
5274   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5275 }
5276 
5277 // Given a reduction op, this function returns the matching reduction opcode,
5278 // the vector SDValue and the scalar SDValue required to lower this to a
5279 // RISCVISD node.
5280 static std::tuple<unsigned, SDValue, SDValue>
5281 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5282   SDLoc DL(Op);
5283   auto Flags = Op->getFlags();
5284   unsigned Opcode = Op.getOpcode();
5285   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5286   switch (Opcode) {
5287   default:
5288     llvm_unreachable("Unhandled reduction");
5289   case ISD::VECREDUCE_FADD: {
5290     // Use positive zero if we can. It is cheaper to materialize.
5291     SDValue Zero =
5292         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5293     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5294   }
5295   case ISD::VECREDUCE_SEQ_FADD:
5296     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5297                            Op.getOperand(0));
5298   case ISD::VECREDUCE_FMIN:
5299     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5300                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5301   case ISD::VECREDUCE_FMAX:
5302     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5303                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5304   }
5305 }
5306 
5307 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5308                                               SelectionDAG &DAG) const {
5309   SDLoc DL(Op);
5310   MVT VecEltVT = Op.getSimpleValueType();
5311 
5312   unsigned RVVOpcode;
5313   SDValue VectorVal, ScalarVal;
5314   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5315       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5316   MVT VecVT = VectorVal.getSimpleValueType();
5317 
5318   MVT ContainerVT = VecVT;
5319   if (VecVT.isFixedLengthVector()) {
5320     ContainerVT = getContainerForFixedLengthVector(VecVT);
5321     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5322   }
5323 
5324   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5325   MVT XLenVT = Subtarget.getXLenVT();
5326 
5327   SDValue Mask, VL;
5328   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5329 
5330   SDValue ScalarSplat =
5331       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5332                        M1VT, DL, DAG, Subtarget);
5333   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5334                                   VectorVal, ScalarSplat, Mask, VL);
5335   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5336                      DAG.getConstant(0, DL, XLenVT));
5337 }
5338 
5339 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5340   switch (ISDOpcode) {
5341   default:
5342     llvm_unreachable("Unhandled reduction");
5343   case ISD::VP_REDUCE_ADD:
5344     return RISCVISD::VECREDUCE_ADD_VL;
5345   case ISD::VP_REDUCE_UMAX:
5346     return RISCVISD::VECREDUCE_UMAX_VL;
5347   case ISD::VP_REDUCE_SMAX:
5348     return RISCVISD::VECREDUCE_SMAX_VL;
5349   case ISD::VP_REDUCE_UMIN:
5350     return RISCVISD::VECREDUCE_UMIN_VL;
5351   case ISD::VP_REDUCE_SMIN:
5352     return RISCVISD::VECREDUCE_SMIN_VL;
5353   case ISD::VP_REDUCE_AND:
5354     return RISCVISD::VECREDUCE_AND_VL;
5355   case ISD::VP_REDUCE_OR:
5356     return RISCVISD::VECREDUCE_OR_VL;
5357   case ISD::VP_REDUCE_XOR:
5358     return RISCVISD::VECREDUCE_XOR_VL;
5359   case ISD::VP_REDUCE_FADD:
5360     return RISCVISD::VECREDUCE_FADD_VL;
5361   case ISD::VP_REDUCE_SEQ_FADD:
5362     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5363   case ISD::VP_REDUCE_FMAX:
5364     return RISCVISD::VECREDUCE_FMAX_VL;
5365   case ISD::VP_REDUCE_FMIN:
5366     return RISCVISD::VECREDUCE_FMIN_VL;
5367   }
5368 }
5369 
5370 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5371                                            SelectionDAG &DAG) const {
5372   SDLoc DL(Op);
5373   SDValue Vec = Op.getOperand(1);
5374   EVT VecEVT = Vec.getValueType();
5375 
5376   // TODO: The type may need to be widened rather than split. Or widened before
5377   // it can be split.
5378   if (!isTypeLegal(VecEVT))
5379     return SDValue();
5380 
5381   MVT VecVT = VecEVT.getSimpleVT();
5382   MVT VecEltVT = VecVT.getVectorElementType();
5383   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5384 
5385   MVT ContainerVT = VecVT;
5386   if (VecVT.isFixedLengthVector()) {
5387     ContainerVT = getContainerForFixedLengthVector(VecVT);
5388     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5389   }
5390 
5391   SDValue VL = Op.getOperand(3);
5392   SDValue Mask = Op.getOperand(2);
5393 
5394   MVT M1VT = getLMUL1VT(ContainerVT);
5395   MVT XLenVT = Subtarget.getXLenVT();
5396   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5397 
5398   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5399                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5400                                         DL, DAG, Subtarget);
5401   SDValue Reduction =
5402       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5403   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5404                              DAG.getConstant(0, DL, XLenVT));
5405   if (!VecVT.isInteger())
5406     return Elt0;
5407   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5408 }
5409 
5410 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5411                                                    SelectionDAG &DAG) const {
5412   SDValue Vec = Op.getOperand(0);
5413   SDValue SubVec = Op.getOperand(1);
5414   MVT VecVT = Vec.getSimpleValueType();
5415   MVT SubVecVT = SubVec.getSimpleValueType();
5416 
5417   SDLoc DL(Op);
5418   MVT XLenVT = Subtarget.getXLenVT();
5419   unsigned OrigIdx = Op.getConstantOperandVal(2);
5420   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5421 
5422   // We don't have the ability to slide mask vectors up indexed by their i1
5423   // elements; the smallest we can do is i8. Often we are able to bitcast to
5424   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5425   // into a scalable one, we might not necessarily have enough scalable
5426   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5427   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5428       (OrigIdx != 0 || !Vec.isUndef())) {
5429     if (VecVT.getVectorMinNumElements() >= 8 &&
5430         SubVecVT.getVectorMinNumElements() >= 8) {
5431       assert(OrigIdx % 8 == 0 && "Invalid index");
5432       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5433              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5434              "Unexpected mask vector lowering");
5435       OrigIdx /= 8;
5436       SubVecVT =
5437           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5438                            SubVecVT.isScalableVector());
5439       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5440                                VecVT.isScalableVector());
5441       Vec = DAG.getBitcast(VecVT, Vec);
5442       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5443     } else {
5444       // We can't slide this mask vector up indexed by its i1 elements.
5445       // This poses a problem when we wish to insert a scalable vector which
5446       // can't be re-expressed as a larger type. Just choose the slow path and
5447       // extend to a larger type, then truncate back down.
5448       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5449       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5450       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5451       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5452       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5453                         Op.getOperand(2));
5454       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5455       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5456     }
5457   }
5458 
5459   // If the subvector vector is a fixed-length type, we cannot use subregister
5460   // manipulation to simplify the codegen; we don't know which register of a
5461   // LMUL group contains the specific subvector as we only know the minimum
5462   // register size. Therefore we must slide the vector group up the full
5463   // amount.
5464   if (SubVecVT.isFixedLengthVector()) {
5465     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5466       return Op;
5467     MVT ContainerVT = VecVT;
5468     if (VecVT.isFixedLengthVector()) {
5469       ContainerVT = getContainerForFixedLengthVector(VecVT);
5470       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5471     }
5472     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5473                          DAG.getUNDEF(ContainerVT), SubVec,
5474                          DAG.getConstant(0, DL, XLenVT));
5475     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5476       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5477       return DAG.getBitcast(Op.getValueType(), SubVec);
5478     }
5479     SDValue Mask =
5480         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5481     // Set the vector length to only the number of elements we care about. Note
5482     // that for slideup this includes the offset.
5483     SDValue VL =
5484         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5485     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5486     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5487                                   SubVec, SlideupAmt, Mask, VL);
5488     if (VecVT.isFixedLengthVector())
5489       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5490     return DAG.getBitcast(Op.getValueType(), Slideup);
5491   }
5492 
5493   unsigned SubRegIdx, RemIdx;
5494   std::tie(SubRegIdx, RemIdx) =
5495       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5496           VecVT, SubVecVT, OrigIdx, TRI);
5497 
5498   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5499   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5500                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5501                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5502 
5503   // 1. If the Idx has been completely eliminated and this subvector's size is
5504   // a vector register or a multiple thereof, or the surrounding elements are
5505   // undef, then this is a subvector insert which naturally aligns to a vector
5506   // register. These can easily be handled using subregister manipulation.
5507   // 2. If the subvector is smaller than a vector register, then the insertion
5508   // must preserve the undisturbed elements of the register. We do this by
5509   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5510   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5511   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5512   // LMUL=1 type back into the larger vector (resolving to another subregister
5513   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5514   // to avoid allocating a large register group to hold our subvector.
5515   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5516     return Op;
5517 
5518   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5519   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5520   // (in our case undisturbed). This means we can set up a subvector insertion
5521   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5522   // size of the subvector.
5523   MVT InterSubVT = VecVT;
5524   SDValue AlignedExtract = Vec;
5525   unsigned AlignedIdx = OrigIdx - RemIdx;
5526   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5527     InterSubVT = getLMUL1VT(VecVT);
5528     // Extract a subvector equal to the nearest full vector register type. This
5529     // should resolve to a EXTRACT_SUBREG instruction.
5530     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5531                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5532   }
5533 
5534   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5535   // For scalable vectors this must be further multiplied by vscale.
5536   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5537 
5538   SDValue Mask, VL;
5539   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5540 
5541   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5542   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5543   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5544   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5545 
5546   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5547                        DAG.getUNDEF(InterSubVT), SubVec,
5548                        DAG.getConstant(0, DL, XLenVT));
5549 
5550   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5551                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5552 
5553   // If required, insert this subvector back into the correct vector register.
5554   // This should resolve to an INSERT_SUBREG instruction.
5555   if (VecVT.bitsGT(InterSubVT))
5556     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5557                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5558 
5559   // We might have bitcast from a mask type: cast back to the original type if
5560   // required.
5561   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5562 }
5563 
5564 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5565                                                     SelectionDAG &DAG) const {
5566   SDValue Vec = Op.getOperand(0);
5567   MVT SubVecVT = Op.getSimpleValueType();
5568   MVT VecVT = Vec.getSimpleValueType();
5569 
5570   SDLoc DL(Op);
5571   MVT XLenVT = Subtarget.getXLenVT();
5572   unsigned OrigIdx = Op.getConstantOperandVal(1);
5573   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5574 
5575   // We don't have the ability to slide mask vectors down indexed by their i1
5576   // elements; the smallest we can do is i8. Often we are able to bitcast to
5577   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5578   // from a scalable one, we might not necessarily have enough scalable
5579   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5580   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5581     if (VecVT.getVectorMinNumElements() >= 8 &&
5582         SubVecVT.getVectorMinNumElements() >= 8) {
5583       assert(OrigIdx % 8 == 0 && "Invalid index");
5584       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5585              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5586              "Unexpected mask vector lowering");
5587       OrigIdx /= 8;
5588       SubVecVT =
5589           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5590                            SubVecVT.isScalableVector());
5591       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5592                                VecVT.isScalableVector());
5593       Vec = DAG.getBitcast(VecVT, Vec);
5594     } else {
5595       // We can't slide this mask vector down, indexed by its i1 elements.
5596       // This poses a problem when we wish to extract a scalable vector which
5597       // can't be re-expressed as a larger type. Just choose the slow path and
5598       // extend to a larger type, then truncate back down.
5599       // TODO: We could probably improve this when extracting certain fixed
5600       // from fixed, where we can extract as i8 and shift the correct element
5601       // right to reach the desired subvector?
5602       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5603       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5604       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5605       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5606                         Op.getOperand(1));
5607       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5608       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5609     }
5610   }
5611 
5612   // If the subvector vector is a fixed-length type, we cannot use subregister
5613   // manipulation to simplify the codegen; we don't know which register of a
5614   // LMUL group contains the specific subvector as we only know the minimum
5615   // register size. Therefore we must slide the vector group down the full
5616   // amount.
5617   if (SubVecVT.isFixedLengthVector()) {
5618     // With an index of 0 this is a cast-like subvector, which can be performed
5619     // with subregister operations.
5620     if (OrigIdx == 0)
5621       return Op;
5622     MVT ContainerVT = VecVT;
5623     if (VecVT.isFixedLengthVector()) {
5624       ContainerVT = getContainerForFixedLengthVector(VecVT);
5625       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5626     }
5627     SDValue Mask =
5628         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5629     // Set the vector length to only the number of elements we care about. This
5630     // avoids sliding down elements we're going to discard straight away.
5631     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5632     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5633     SDValue Slidedown =
5634         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5635                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5636     // Now we can use a cast-like subvector extract to get the result.
5637     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5638                             DAG.getConstant(0, DL, XLenVT));
5639     return DAG.getBitcast(Op.getValueType(), Slidedown);
5640   }
5641 
5642   unsigned SubRegIdx, RemIdx;
5643   std::tie(SubRegIdx, RemIdx) =
5644       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5645           VecVT, SubVecVT, OrigIdx, TRI);
5646 
5647   // If the Idx has been completely eliminated then this is a subvector extract
5648   // which naturally aligns to a vector register. These can easily be handled
5649   // using subregister manipulation.
5650   if (RemIdx == 0)
5651     return Op;
5652 
5653   // Else we must shift our vector register directly to extract the subvector.
5654   // Do this using VSLIDEDOWN.
5655 
5656   // If the vector type is an LMUL-group type, extract a subvector equal to the
5657   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5658   // instruction.
5659   MVT InterSubVT = VecVT;
5660   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5661     InterSubVT = getLMUL1VT(VecVT);
5662     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5663                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5664   }
5665 
5666   // Slide this vector register down by the desired number of elements in order
5667   // to place the desired subvector starting at element 0.
5668   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5669   // For scalable vectors this must be further multiplied by vscale.
5670   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5671 
5672   SDValue Mask, VL;
5673   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5674   SDValue Slidedown =
5675       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5676                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5677 
5678   // Now the vector is in the right position, extract our final subvector. This
5679   // should resolve to a COPY.
5680   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5681                           DAG.getConstant(0, DL, XLenVT));
5682 
5683   // We might have bitcast from a mask type: cast back to the original type if
5684   // required.
5685   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5686 }
5687 
5688 // Lower step_vector to the vid instruction. Any non-identity step value must
5689 // be accounted for my manual expansion.
5690 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5691                                               SelectionDAG &DAG) const {
5692   SDLoc DL(Op);
5693   MVT VT = Op.getSimpleValueType();
5694   MVT XLenVT = Subtarget.getXLenVT();
5695   SDValue Mask, VL;
5696   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5697   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5698   uint64_t StepValImm = Op.getConstantOperandVal(0);
5699   if (StepValImm != 1) {
5700     if (isPowerOf2_64(StepValImm)) {
5701       SDValue StepVal =
5702           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5703                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5704       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5705     } else {
5706       SDValue StepVal = lowerScalarSplat(
5707           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5708           VL, VT, DL, DAG, Subtarget);
5709       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5710     }
5711   }
5712   return StepVec;
5713 }
5714 
5715 // Implement vector_reverse using vrgather.vv with indices determined by
5716 // subtracting the id of each element from (VLMAX-1). This will convert
5717 // the indices like so:
5718 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5719 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5720 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5721                                                  SelectionDAG &DAG) const {
5722   SDLoc DL(Op);
5723   MVT VecVT = Op.getSimpleValueType();
5724   unsigned EltSize = VecVT.getScalarSizeInBits();
5725   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5726 
5727   unsigned MaxVLMAX = 0;
5728   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5729   if (VectorBitsMax != 0)
5730     MaxVLMAX =
5731         RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5732 
5733   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5734   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5735 
5736   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5737   // to use vrgatherei16.vv.
5738   // TODO: It's also possible to use vrgatherei16.vv for other types to
5739   // decrease register width for the index calculation.
5740   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5741     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5742     // Reverse each half, then reassemble them in reverse order.
5743     // NOTE: It's also possible that after splitting that VLMAX no longer
5744     // requires vrgatherei16.vv.
5745     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5746       SDValue Lo, Hi;
5747       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5748       EVT LoVT, HiVT;
5749       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5750       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5751       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5752       // Reassemble the low and high pieces reversed.
5753       // FIXME: This is a CONCAT_VECTORS.
5754       SDValue Res =
5755           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5756                       DAG.getIntPtrConstant(0, DL));
5757       return DAG.getNode(
5758           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5759           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5760     }
5761 
5762     // Just promote the int type to i16 which will double the LMUL.
5763     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5764     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5765   }
5766 
5767   MVT XLenVT = Subtarget.getXLenVT();
5768   SDValue Mask, VL;
5769   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5770 
5771   // Calculate VLMAX-1 for the desired SEW.
5772   unsigned MinElts = VecVT.getVectorMinNumElements();
5773   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5774                               DAG.getConstant(MinElts, DL, XLenVT));
5775   SDValue VLMinus1 =
5776       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5777 
5778   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5779   bool IsRV32E64 =
5780       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5781   SDValue SplatVL;
5782   if (!IsRV32E64)
5783     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5784   else
5785     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5786                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5787 
5788   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5789   SDValue Indices =
5790       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5791 
5792   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5793 }
5794 
5795 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5796                                                 SelectionDAG &DAG) const {
5797   SDLoc DL(Op);
5798   SDValue V1 = Op.getOperand(0);
5799   SDValue V2 = Op.getOperand(1);
5800   MVT XLenVT = Subtarget.getXLenVT();
5801   MVT VecVT = Op.getSimpleValueType();
5802 
5803   unsigned MinElts = VecVT.getVectorMinNumElements();
5804   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5805                               DAG.getConstant(MinElts, DL, XLenVT));
5806 
5807   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5808   SDValue DownOffset, UpOffset;
5809   if (ImmValue >= 0) {
5810     // The operand is a TargetConstant, we need to rebuild it as a regular
5811     // constant.
5812     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5813     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5814   } else {
5815     // The operand is a TargetConstant, we need to rebuild it as a regular
5816     // constant rather than negating the original operand.
5817     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5818     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5819   }
5820 
5821   MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5822   SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax);
5823 
5824   SDValue SlideDown =
5825       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5826                   DownOffset, TrueMask, UpOffset);
5827   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5828                      TrueMask,
5829                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5830 }
5831 
5832 SDValue
5833 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5834                                                      SelectionDAG &DAG) const {
5835   SDLoc DL(Op);
5836   auto *Load = cast<LoadSDNode>(Op);
5837 
5838   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5839                                         Load->getMemoryVT(),
5840                                         *Load->getMemOperand()) &&
5841          "Expecting a correctly-aligned load");
5842 
5843   MVT VT = Op.getSimpleValueType();
5844   MVT XLenVT = Subtarget.getXLenVT();
5845   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5846 
5847   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5848 
5849   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5850   SDValue IntID = DAG.getTargetConstant(
5851       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5852   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5853   if (!IsMaskOp)
5854     Ops.push_back(DAG.getUNDEF(ContainerVT));
5855   Ops.push_back(Load->getBasePtr());
5856   Ops.push_back(VL);
5857   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5858   SDValue NewLoad =
5859       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5860                               Load->getMemoryVT(), Load->getMemOperand());
5861 
5862   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5863   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5864 }
5865 
5866 SDValue
5867 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5868                                                       SelectionDAG &DAG) const {
5869   SDLoc DL(Op);
5870   auto *Store = cast<StoreSDNode>(Op);
5871 
5872   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5873                                         Store->getMemoryVT(),
5874                                         *Store->getMemOperand()) &&
5875          "Expecting a correctly-aligned store");
5876 
5877   SDValue StoreVal = Store->getValue();
5878   MVT VT = StoreVal.getSimpleValueType();
5879   MVT XLenVT = Subtarget.getXLenVT();
5880 
5881   // If the size less than a byte, we need to pad with zeros to make a byte.
5882   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5883     VT = MVT::v8i1;
5884     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5885                            DAG.getConstant(0, DL, VT), StoreVal,
5886                            DAG.getIntPtrConstant(0, DL));
5887   }
5888 
5889   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5890 
5891   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5892 
5893   SDValue NewValue =
5894       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5895 
5896   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5897   SDValue IntID = DAG.getTargetConstant(
5898       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5899   return DAG.getMemIntrinsicNode(
5900       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5901       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5902       Store->getMemoryVT(), Store->getMemOperand());
5903 }
5904 
5905 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5906                                              SelectionDAG &DAG) const {
5907   SDLoc DL(Op);
5908   MVT VT = Op.getSimpleValueType();
5909 
5910   const auto *MemSD = cast<MemSDNode>(Op);
5911   EVT MemVT = MemSD->getMemoryVT();
5912   MachineMemOperand *MMO = MemSD->getMemOperand();
5913   SDValue Chain = MemSD->getChain();
5914   SDValue BasePtr = MemSD->getBasePtr();
5915 
5916   SDValue Mask, PassThru, VL;
5917   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5918     Mask = VPLoad->getMask();
5919     PassThru = DAG.getUNDEF(VT);
5920     VL = VPLoad->getVectorLength();
5921   } else {
5922     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5923     Mask = MLoad->getMask();
5924     PassThru = MLoad->getPassThru();
5925   }
5926 
5927   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5928 
5929   MVT XLenVT = Subtarget.getXLenVT();
5930 
5931   MVT ContainerVT = VT;
5932   if (VT.isFixedLengthVector()) {
5933     ContainerVT = getContainerForFixedLengthVector(VT);
5934     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5935     if (!IsUnmasked) {
5936       MVT MaskVT =
5937           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5938       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5939     }
5940   }
5941 
5942   if (!VL)
5943     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5944 
5945   unsigned IntID =
5946       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5947   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5948   if (IsUnmasked)
5949     Ops.push_back(DAG.getUNDEF(ContainerVT));
5950   else
5951     Ops.push_back(PassThru);
5952   Ops.push_back(BasePtr);
5953   if (!IsUnmasked)
5954     Ops.push_back(Mask);
5955   Ops.push_back(VL);
5956   if (!IsUnmasked)
5957     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5958 
5959   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5960 
5961   SDValue Result =
5962       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5963   Chain = Result.getValue(1);
5964 
5965   if (VT.isFixedLengthVector())
5966     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5967 
5968   return DAG.getMergeValues({Result, Chain}, DL);
5969 }
5970 
5971 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5972                                               SelectionDAG &DAG) const {
5973   SDLoc DL(Op);
5974 
5975   const auto *MemSD = cast<MemSDNode>(Op);
5976   EVT MemVT = MemSD->getMemoryVT();
5977   MachineMemOperand *MMO = MemSD->getMemOperand();
5978   SDValue Chain = MemSD->getChain();
5979   SDValue BasePtr = MemSD->getBasePtr();
5980   SDValue Val, Mask, VL;
5981 
5982   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5983     Val = VPStore->getValue();
5984     Mask = VPStore->getMask();
5985     VL = VPStore->getVectorLength();
5986   } else {
5987     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5988     Val = MStore->getValue();
5989     Mask = MStore->getMask();
5990   }
5991 
5992   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5993 
5994   MVT VT = Val.getSimpleValueType();
5995   MVT XLenVT = Subtarget.getXLenVT();
5996 
5997   MVT ContainerVT = VT;
5998   if (VT.isFixedLengthVector()) {
5999     ContainerVT = getContainerForFixedLengthVector(VT);
6000 
6001     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6002     if (!IsUnmasked) {
6003       MVT MaskVT =
6004           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6005       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6006     }
6007   }
6008 
6009   if (!VL)
6010     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6011 
6012   unsigned IntID =
6013       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
6014   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6015   Ops.push_back(Val);
6016   Ops.push_back(BasePtr);
6017   if (!IsUnmasked)
6018     Ops.push_back(Mask);
6019   Ops.push_back(VL);
6020 
6021   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6022                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6023 }
6024 
6025 SDValue
6026 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
6027                                                       SelectionDAG &DAG) const {
6028   MVT InVT = Op.getOperand(0).getSimpleValueType();
6029   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
6030 
6031   MVT VT = Op.getSimpleValueType();
6032 
6033   SDValue Op1 =
6034       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
6035   SDValue Op2 =
6036       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6037 
6038   SDLoc DL(Op);
6039   SDValue VL =
6040       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
6041 
6042   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6043   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6044 
6045   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
6046                             Op.getOperand(2), Mask, VL);
6047 
6048   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
6049 }
6050 
6051 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
6052     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
6053   MVT VT = Op.getSimpleValueType();
6054 
6055   if (VT.getVectorElementType() == MVT::i1)
6056     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
6057 
6058   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
6059 }
6060 
6061 SDValue
6062 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
6063                                                       SelectionDAG &DAG) const {
6064   unsigned Opc;
6065   switch (Op.getOpcode()) {
6066   default: llvm_unreachable("Unexpected opcode!");
6067   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
6068   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
6069   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
6070   }
6071 
6072   return lowerToScalableOp(Op, DAG, Opc);
6073 }
6074 
6075 // Lower vector ABS to smax(X, sub(0, X)).
6076 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
6077   SDLoc DL(Op);
6078   MVT VT = Op.getSimpleValueType();
6079   SDValue X = Op.getOperand(0);
6080 
6081   assert(VT.isFixedLengthVector() && "Unexpected type");
6082 
6083   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6084   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
6085 
6086   SDValue Mask, VL;
6087   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6088 
6089   SDValue SplatZero = DAG.getNode(
6090       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
6091       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
6092   SDValue NegX =
6093       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
6094   SDValue Max =
6095       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
6096 
6097   return convertFromScalableVector(VT, Max, DAG, Subtarget);
6098 }
6099 
6100 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
6101     SDValue Op, SelectionDAG &DAG) const {
6102   SDLoc DL(Op);
6103   MVT VT = Op.getSimpleValueType();
6104   SDValue Mag = Op.getOperand(0);
6105   SDValue Sign = Op.getOperand(1);
6106   assert(Mag.getValueType() == Sign.getValueType() &&
6107          "Can only handle COPYSIGN with matching types.");
6108 
6109   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6110   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
6111   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
6112 
6113   SDValue Mask, VL;
6114   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6115 
6116   SDValue CopySign =
6117       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
6118 
6119   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
6120 }
6121 
6122 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
6123     SDValue Op, SelectionDAG &DAG) const {
6124   MVT VT = Op.getSimpleValueType();
6125   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6126 
6127   MVT I1ContainerVT =
6128       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6129 
6130   SDValue CC =
6131       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
6132   SDValue Op1 =
6133       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6134   SDValue Op2 =
6135       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
6136 
6137   SDLoc DL(Op);
6138   SDValue Mask, VL;
6139   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6140 
6141   SDValue Select =
6142       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
6143 
6144   return convertFromScalableVector(VT, Select, DAG, Subtarget);
6145 }
6146 
6147 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
6148                                                unsigned NewOpc,
6149                                                bool HasMask) const {
6150   MVT VT = Op.getSimpleValueType();
6151   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6152 
6153   // Create list of operands by converting existing ones to scalable types.
6154   SmallVector<SDValue, 6> Ops;
6155   for (const SDValue &V : Op->op_values()) {
6156     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6157 
6158     // Pass through non-vector operands.
6159     if (!V.getValueType().isVector()) {
6160       Ops.push_back(V);
6161       continue;
6162     }
6163 
6164     // "cast" fixed length vector to a scalable vector.
6165     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6166            "Only fixed length vectors are supported!");
6167     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6168   }
6169 
6170   SDLoc DL(Op);
6171   SDValue Mask, VL;
6172   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6173   if (HasMask)
6174     Ops.push_back(Mask);
6175   Ops.push_back(VL);
6176 
6177   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6178   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6179 }
6180 
6181 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6182 // * Operands of each node are assumed to be in the same order.
6183 // * The EVL operand is promoted from i32 to i64 on RV64.
6184 // * Fixed-length vectors are converted to their scalable-vector container
6185 //   types.
6186 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6187                                        unsigned RISCVISDOpc) const {
6188   SDLoc DL(Op);
6189   MVT VT = Op.getSimpleValueType();
6190   SmallVector<SDValue, 4> Ops;
6191 
6192   for (const auto &OpIdx : enumerate(Op->ops())) {
6193     SDValue V = OpIdx.value();
6194     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6195     // Pass through operands which aren't fixed-length vectors.
6196     if (!V.getValueType().isFixedLengthVector()) {
6197       Ops.push_back(V);
6198       continue;
6199     }
6200     // "cast" fixed length vector to a scalable vector.
6201     MVT OpVT = V.getSimpleValueType();
6202     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6203     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6204            "Only fixed length vectors are supported!");
6205     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6206   }
6207 
6208   if (!VT.isFixedLengthVector())
6209     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
6210 
6211   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6212 
6213   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
6214 
6215   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6216 }
6217 
6218 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op,
6219                                               SelectionDAG &DAG) const {
6220   SDLoc DL(Op);
6221   MVT VT = Op.getSimpleValueType();
6222 
6223   SDValue Src = Op.getOperand(0);
6224   // NOTE: Mask is dropped.
6225   SDValue VL = Op.getOperand(2);
6226 
6227   MVT ContainerVT = VT;
6228   if (VT.isFixedLengthVector()) {
6229     ContainerVT = getContainerForFixedLengthVector(VT);
6230     MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6231     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6232   }
6233 
6234   MVT XLenVT = Subtarget.getXLenVT();
6235   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6236   SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6237                                   DAG.getUNDEF(ContainerVT), Zero, VL);
6238 
6239   SDValue SplatValue =
6240       DAG.getConstant(Op.getOpcode() == ISD::VP_ZEXT ? 1 : -1, DL, XLenVT);
6241   SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6242                               DAG.getUNDEF(ContainerVT), SplatValue, VL);
6243 
6244   SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src,
6245                                Splat, ZeroSplat, VL);
6246   if (!VT.isFixedLengthVector())
6247     return Result;
6248   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6249 }
6250 
6251 // Lower Floating-Point/Integer Type-Convert VP SDNodes
6252 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
6253                                                 unsigned RISCVISDOpc) const {
6254   SDLoc DL(Op);
6255 
6256   SDValue Src = Op.getOperand(0);
6257   SDValue Mask = Op.getOperand(1);
6258   SDValue VL = Op.getOperand(2);
6259 
6260   MVT DstVT = Op.getSimpleValueType();
6261   MVT SrcVT = Src.getSimpleValueType();
6262   if (DstVT.isFixedLengthVector()) {
6263     DstVT = getContainerForFixedLengthVector(DstVT);
6264     SrcVT = getContainerForFixedLengthVector(SrcVT);
6265     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6266     MVT MaskVT = MVT::getVectorVT(MVT::i1, DstVT.getVectorElementCount());
6267     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6268   }
6269 
6270   unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL ||
6271                              RISCVISDOpc == RISCVISD::FP_TO_SINT_VL)
6272                                 ? RISCVISD::VSEXT_VL
6273                                 : RISCVISD::VZEXT_VL;
6274 
6275   unsigned DstEltSize = DstVT.getScalarSizeInBits();
6276   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
6277 
6278   SDValue Result;
6279   if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
6280     if (SrcVT.isInteger()) {
6281       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6282 
6283       // Do we need to do any pre-widening before converting?
6284       if (SrcEltSize == 1) {
6285         MVT IntVT = DstVT.changeVectorElementTypeToInteger();
6286         MVT XLenVT = Subtarget.getXLenVT();
6287         SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6288         SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6289                                         DAG.getUNDEF(IntVT), Zero, VL);
6290         SDValue One = DAG.getConstant(
6291             RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
6292         SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6293                                        DAG.getUNDEF(IntVT), One, VL);
6294         Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
6295                           ZeroSplat, VL);
6296       } else if (DstEltSize > (2 * SrcEltSize)) {
6297         // Widen before converting.
6298         MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
6299                                      DstVT.getVectorElementCount());
6300         Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL);
6301       }
6302 
6303       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6304     } else {
6305       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6306              "Wrong input/output vector types");
6307 
6308       // Convert f16 to f32 then convert f32 to i64.
6309       if (DstEltSize > (2 * SrcEltSize)) {
6310         assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6311         MVT InterimFVT =
6312             MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6313         Src =
6314             DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL);
6315       }
6316 
6317       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6318     }
6319   } else { // Narrowing + Conversion
6320     if (SrcVT.isInteger()) {
6321       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6322       // First do a narrowing convert to an FP type half the size, then round
6323       // the FP type to a small FP type if needed.
6324 
6325       MVT InterimFVT = DstVT;
6326       if (SrcEltSize > (2 * DstEltSize)) {
6327         assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
6328         assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6329         InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6330       }
6331 
6332       Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL);
6333 
6334       if (InterimFVT != DstVT) {
6335         Src = Result;
6336         Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL);
6337       }
6338     } else {
6339       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6340              "Wrong input/output vector types");
6341       // First do a narrowing conversion to an integer half the size, then
6342       // truncate if needed.
6343 
6344       if (DstEltSize == 1) {
6345         // First convert to the same size integer, then convert to mask using
6346         // setcc.
6347         assert(SrcEltSize >= 16 && "Unexpected FP type!");
6348         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize),
6349                                           DstVT.getVectorElementCount());
6350         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6351 
6352         // Compare the integer result to 0. The integer should be 0 or 1/-1,
6353         // otherwise the conversion was undefined.
6354         MVT XLenVT = Subtarget.getXLenVT();
6355         SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
6356         SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT,
6357                                 DAG.getUNDEF(InterimIVT), SplatZero);
6358         Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero,
6359                              DAG.getCondCode(ISD::SETNE), Mask, VL);
6360       } else {
6361         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6362                                           DstVT.getVectorElementCount());
6363 
6364         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6365 
6366         while (InterimIVT != DstVT) {
6367           SrcEltSize /= 2;
6368           Src = Result;
6369           InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6370                                         DstVT.getVectorElementCount());
6371           Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
6372                                Src, Mask, VL);
6373         }
6374       }
6375     }
6376   }
6377 
6378   MVT VT = Op.getSimpleValueType();
6379   if (!VT.isFixedLengthVector())
6380     return Result;
6381   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6382 }
6383 
6384 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6385                                             unsigned MaskOpc,
6386                                             unsigned VecOpc) const {
6387   MVT VT = Op.getSimpleValueType();
6388   if (VT.getVectorElementType() != MVT::i1)
6389     return lowerVPOp(Op, DAG, VecOpc);
6390 
6391   // It is safe to drop mask parameter as masked-off elements are undef.
6392   SDValue Op1 = Op->getOperand(0);
6393   SDValue Op2 = Op->getOperand(1);
6394   SDValue VL = Op->getOperand(3);
6395 
6396   MVT ContainerVT = VT;
6397   const bool IsFixed = VT.isFixedLengthVector();
6398   if (IsFixed) {
6399     ContainerVT = getContainerForFixedLengthVector(VT);
6400     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6401     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6402   }
6403 
6404   SDLoc DL(Op);
6405   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6406   if (!IsFixed)
6407     return Val;
6408   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6409 }
6410 
6411 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6412 // matched to a RVV indexed load. The RVV indexed load instructions only
6413 // support the "unsigned unscaled" addressing mode; indices are implicitly
6414 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6415 // signed or scaled indexing is extended to the XLEN value type and scaled
6416 // accordingly.
6417 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6418                                                SelectionDAG &DAG) const {
6419   SDLoc DL(Op);
6420   MVT VT = Op.getSimpleValueType();
6421 
6422   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6423   EVT MemVT = MemSD->getMemoryVT();
6424   MachineMemOperand *MMO = MemSD->getMemOperand();
6425   SDValue Chain = MemSD->getChain();
6426   SDValue BasePtr = MemSD->getBasePtr();
6427 
6428   ISD::LoadExtType LoadExtType;
6429   SDValue Index, Mask, PassThru, VL;
6430 
6431   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6432     Index = VPGN->getIndex();
6433     Mask = VPGN->getMask();
6434     PassThru = DAG.getUNDEF(VT);
6435     VL = VPGN->getVectorLength();
6436     // VP doesn't support extending loads.
6437     LoadExtType = ISD::NON_EXTLOAD;
6438   } else {
6439     // Else it must be a MGATHER.
6440     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6441     Index = MGN->getIndex();
6442     Mask = MGN->getMask();
6443     PassThru = MGN->getPassThru();
6444     LoadExtType = MGN->getExtensionType();
6445   }
6446 
6447   MVT IndexVT = Index.getSimpleValueType();
6448   MVT XLenVT = Subtarget.getXLenVT();
6449 
6450   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6451          "Unexpected VTs!");
6452   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6453   // Targets have to explicitly opt-in for extending vector loads.
6454   assert(LoadExtType == ISD::NON_EXTLOAD &&
6455          "Unexpected extending MGATHER/VP_GATHER");
6456   (void)LoadExtType;
6457 
6458   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6459   // the selection of the masked intrinsics doesn't do this for us.
6460   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6461 
6462   MVT ContainerVT = VT;
6463   if (VT.isFixedLengthVector()) {
6464     // We need to use the larger of the result and index type to determine the
6465     // scalable type to use so we don't increase LMUL for any operand/result.
6466     if (VT.bitsGE(IndexVT)) {
6467       ContainerVT = getContainerForFixedLengthVector(VT);
6468       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6469                                  ContainerVT.getVectorElementCount());
6470     } else {
6471       IndexVT = getContainerForFixedLengthVector(IndexVT);
6472       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
6473                                      IndexVT.getVectorElementCount());
6474     }
6475 
6476     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6477 
6478     if (!IsUnmasked) {
6479       MVT MaskVT =
6480           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6481       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6482       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6483     }
6484   }
6485 
6486   if (!VL)
6487     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6488 
6489   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6490     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6491     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6492                                    VL);
6493     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6494                         TrueMask, VL);
6495   }
6496 
6497   unsigned IntID =
6498       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6499   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6500   if (IsUnmasked)
6501     Ops.push_back(DAG.getUNDEF(ContainerVT));
6502   else
6503     Ops.push_back(PassThru);
6504   Ops.push_back(BasePtr);
6505   Ops.push_back(Index);
6506   if (!IsUnmasked)
6507     Ops.push_back(Mask);
6508   Ops.push_back(VL);
6509   if (!IsUnmasked)
6510     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6511 
6512   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6513   SDValue Result =
6514       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6515   Chain = Result.getValue(1);
6516 
6517   if (VT.isFixedLengthVector())
6518     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6519 
6520   return DAG.getMergeValues({Result, Chain}, DL);
6521 }
6522 
6523 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6524 // matched to a RVV indexed store. The RVV indexed store instructions only
6525 // support the "unsigned unscaled" addressing mode; indices are implicitly
6526 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6527 // signed or scaled indexing is extended to the XLEN value type and scaled
6528 // accordingly.
6529 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6530                                                 SelectionDAG &DAG) const {
6531   SDLoc DL(Op);
6532   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6533   EVT MemVT = MemSD->getMemoryVT();
6534   MachineMemOperand *MMO = MemSD->getMemOperand();
6535   SDValue Chain = MemSD->getChain();
6536   SDValue BasePtr = MemSD->getBasePtr();
6537 
6538   bool IsTruncatingStore = false;
6539   SDValue Index, Mask, Val, VL;
6540 
6541   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6542     Index = VPSN->getIndex();
6543     Mask = VPSN->getMask();
6544     Val = VPSN->getValue();
6545     VL = VPSN->getVectorLength();
6546     // VP doesn't support truncating stores.
6547     IsTruncatingStore = false;
6548   } else {
6549     // Else it must be a MSCATTER.
6550     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6551     Index = MSN->getIndex();
6552     Mask = MSN->getMask();
6553     Val = MSN->getValue();
6554     IsTruncatingStore = MSN->isTruncatingStore();
6555   }
6556 
6557   MVT VT = Val.getSimpleValueType();
6558   MVT IndexVT = Index.getSimpleValueType();
6559   MVT XLenVT = Subtarget.getXLenVT();
6560 
6561   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6562          "Unexpected VTs!");
6563   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6564   // Targets have to explicitly opt-in for extending vector loads and
6565   // truncating vector stores.
6566   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6567   (void)IsTruncatingStore;
6568 
6569   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6570   // the selection of the masked intrinsics doesn't do this for us.
6571   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6572 
6573   MVT ContainerVT = VT;
6574   if (VT.isFixedLengthVector()) {
6575     // We need to use the larger of the value and index type to determine the
6576     // scalable type to use so we don't increase LMUL for any operand/result.
6577     if (VT.bitsGE(IndexVT)) {
6578       ContainerVT = getContainerForFixedLengthVector(VT);
6579       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6580                                  ContainerVT.getVectorElementCount());
6581     } else {
6582       IndexVT = getContainerForFixedLengthVector(IndexVT);
6583       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
6584                                      IndexVT.getVectorElementCount());
6585     }
6586 
6587     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6588     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6589 
6590     if (!IsUnmasked) {
6591       MVT MaskVT =
6592           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6593       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6594     }
6595   }
6596 
6597   if (!VL)
6598     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6599 
6600   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6601     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6602     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6603                                    VL);
6604     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6605                         TrueMask, VL);
6606   }
6607 
6608   unsigned IntID =
6609       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6610   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6611   Ops.push_back(Val);
6612   Ops.push_back(BasePtr);
6613   Ops.push_back(Index);
6614   if (!IsUnmasked)
6615     Ops.push_back(Mask);
6616   Ops.push_back(VL);
6617 
6618   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6619                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6620 }
6621 
6622 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6623                                                SelectionDAG &DAG) const {
6624   const MVT XLenVT = Subtarget.getXLenVT();
6625   SDLoc DL(Op);
6626   SDValue Chain = Op->getOperand(0);
6627   SDValue SysRegNo = DAG.getTargetConstant(
6628       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6629   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6630   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6631 
6632   // Encoding used for rounding mode in RISCV differs from that used in
6633   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6634   // table, which consists of a sequence of 4-bit fields, each representing
6635   // corresponding FLT_ROUNDS mode.
6636   static const int Table =
6637       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6638       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6639       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6640       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6641       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6642 
6643   SDValue Shift =
6644       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6645   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6646                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6647   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6648                                DAG.getConstant(7, DL, XLenVT));
6649 
6650   return DAG.getMergeValues({Masked, Chain}, DL);
6651 }
6652 
6653 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6654                                                SelectionDAG &DAG) const {
6655   const MVT XLenVT = Subtarget.getXLenVT();
6656   SDLoc DL(Op);
6657   SDValue Chain = Op->getOperand(0);
6658   SDValue RMValue = Op->getOperand(1);
6659   SDValue SysRegNo = DAG.getTargetConstant(
6660       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6661 
6662   // Encoding used for rounding mode in RISCV differs from that used in
6663   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6664   // a table, which consists of a sequence of 4-bit fields, each representing
6665   // corresponding RISCV mode.
6666   static const unsigned Table =
6667       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6668       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6669       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6670       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6671       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6672 
6673   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6674                               DAG.getConstant(2, DL, XLenVT));
6675   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6676                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6677   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6678                         DAG.getConstant(0x7, DL, XLenVT));
6679   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6680                      RMValue);
6681 }
6682 
6683 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6684   switch (IntNo) {
6685   default:
6686     llvm_unreachable("Unexpected Intrinsic");
6687   case Intrinsic::riscv_bcompress:
6688     return RISCVISD::BCOMPRESSW;
6689   case Intrinsic::riscv_bdecompress:
6690     return RISCVISD::BDECOMPRESSW;
6691   case Intrinsic::riscv_bfp:
6692     return RISCVISD::BFPW;
6693   case Intrinsic::riscv_fsl:
6694     return RISCVISD::FSLW;
6695   case Intrinsic::riscv_fsr:
6696     return RISCVISD::FSRW;
6697   }
6698 }
6699 
6700 // Converts the given intrinsic to a i64 operation with any extension.
6701 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6702                                          unsigned IntNo) {
6703   SDLoc DL(N);
6704   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6705   // Deal with the Instruction Operands
6706   SmallVector<SDValue, 3> NewOps;
6707   for (SDValue Op : drop_begin(N->ops()))
6708     // Promote the operand to i64 type
6709     NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op));
6710   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps);
6711   // ReplaceNodeResults requires we maintain the same type for the return value.
6712   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6713 }
6714 
6715 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6716 // form of the given Opcode.
6717 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6718   switch (Opcode) {
6719   default:
6720     llvm_unreachable("Unexpected opcode");
6721   case ISD::SHL:
6722     return RISCVISD::SLLW;
6723   case ISD::SRA:
6724     return RISCVISD::SRAW;
6725   case ISD::SRL:
6726     return RISCVISD::SRLW;
6727   case ISD::SDIV:
6728     return RISCVISD::DIVW;
6729   case ISD::UDIV:
6730     return RISCVISD::DIVUW;
6731   case ISD::UREM:
6732     return RISCVISD::REMUW;
6733   case ISD::ROTL:
6734     return RISCVISD::ROLW;
6735   case ISD::ROTR:
6736     return RISCVISD::RORW;
6737   }
6738 }
6739 
6740 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6741 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6742 // otherwise be promoted to i64, making it difficult to select the
6743 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6744 // type i8/i16/i32 is lost.
6745 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6746                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6747   SDLoc DL(N);
6748   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6749   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6750   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6751   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6752   // ReplaceNodeResults requires we maintain the same type for the return value.
6753   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6754 }
6755 
6756 // Converts the given 32-bit operation to a i64 operation with signed extension
6757 // semantic to reduce the signed extension instructions.
6758 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6759   SDLoc DL(N);
6760   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6761   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6762   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6763   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6764                                DAG.getValueType(MVT::i32));
6765   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6766 }
6767 
6768 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6769                                              SmallVectorImpl<SDValue> &Results,
6770                                              SelectionDAG &DAG) const {
6771   SDLoc DL(N);
6772   switch (N->getOpcode()) {
6773   default:
6774     llvm_unreachable("Don't know how to custom type legalize this operation!");
6775   case ISD::STRICT_FP_TO_SINT:
6776   case ISD::STRICT_FP_TO_UINT:
6777   case ISD::FP_TO_SINT:
6778   case ISD::FP_TO_UINT: {
6779     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6780            "Unexpected custom legalisation");
6781     bool IsStrict = N->isStrictFPOpcode();
6782     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6783                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6784     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6785     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6786         TargetLowering::TypeSoftenFloat) {
6787       if (!isTypeLegal(Op0.getValueType()))
6788         return;
6789       if (IsStrict) {
6790         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6791                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6792         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6793         SDValue Res = DAG.getNode(
6794             Opc, DL, VTs, N->getOperand(0), Op0,
6795             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6796         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6797         Results.push_back(Res.getValue(1));
6798         return;
6799       }
6800       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6801       SDValue Res =
6802           DAG.getNode(Opc, DL, MVT::i64, Op0,
6803                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6804       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6805       return;
6806     }
6807     // If the FP type needs to be softened, emit a library call using the 'si'
6808     // version. If we left it to default legalization we'd end up with 'di'. If
6809     // the FP type doesn't need to be softened just let generic type
6810     // legalization promote the result type.
6811     RTLIB::Libcall LC;
6812     if (IsSigned)
6813       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6814     else
6815       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6816     MakeLibCallOptions CallOptions;
6817     EVT OpVT = Op0.getValueType();
6818     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6819     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6820     SDValue Result;
6821     std::tie(Result, Chain) =
6822         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6823     Results.push_back(Result);
6824     if (IsStrict)
6825       Results.push_back(Chain);
6826     break;
6827   }
6828   case ISD::READCYCLECOUNTER: {
6829     assert(!Subtarget.is64Bit() &&
6830            "READCYCLECOUNTER only has custom type legalization on riscv32");
6831 
6832     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6833     SDValue RCW =
6834         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6835 
6836     Results.push_back(
6837         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6838     Results.push_back(RCW.getValue(2));
6839     break;
6840   }
6841   case ISD::MUL: {
6842     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6843     unsigned XLen = Subtarget.getXLen();
6844     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6845     if (Size > XLen) {
6846       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6847       SDValue LHS = N->getOperand(0);
6848       SDValue RHS = N->getOperand(1);
6849       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6850 
6851       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6852       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6853       // We need exactly one side to be unsigned.
6854       if (LHSIsU == RHSIsU)
6855         return;
6856 
6857       auto MakeMULPair = [&](SDValue S, SDValue U) {
6858         MVT XLenVT = Subtarget.getXLenVT();
6859         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6860         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6861         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6862         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6863         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6864       };
6865 
6866       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6867       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6868 
6869       // The other operand should be signed, but still prefer MULH when
6870       // possible.
6871       if (RHSIsU && LHSIsS && !RHSIsS)
6872         Results.push_back(MakeMULPair(LHS, RHS));
6873       else if (LHSIsU && RHSIsS && !LHSIsS)
6874         Results.push_back(MakeMULPair(RHS, LHS));
6875 
6876       return;
6877     }
6878     LLVM_FALLTHROUGH;
6879   }
6880   case ISD::ADD:
6881   case ISD::SUB:
6882     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6883            "Unexpected custom legalisation");
6884     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6885     break;
6886   case ISD::SHL:
6887   case ISD::SRA:
6888   case ISD::SRL:
6889     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6890            "Unexpected custom legalisation");
6891     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6892       Results.push_back(customLegalizeToWOp(N, DAG));
6893       break;
6894     }
6895 
6896     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6897     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6898     // shift amount.
6899     if (N->getOpcode() == ISD::SHL) {
6900       SDLoc DL(N);
6901       SDValue NewOp0 =
6902           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6903       SDValue NewOp1 =
6904           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6905       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6906       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6907                                    DAG.getValueType(MVT::i32));
6908       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6909     }
6910 
6911     break;
6912   case ISD::ROTL:
6913   case ISD::ROTR:
6914     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6915            "Unexpected custom legalisation");
6916     Results.push_back(customLegalizeToWOp(N, DAG));
6917     break;
6918   case ISD::CTTZ:
6919   case ISD::CTTZ_ZERO_UNDEF:
6920   case ISD::CTLZ:
6921   case ISD::CTLZ_ZERO_UNDEF: {
6922     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6923            "Unexpected custom legalisation");
6924 
6925     SDValue NewOp0 =
6926         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6927     bool IsCTZ =
6928         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6929     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6930     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6931     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6932     return;
6933   }
6934   case ISD::SDIV:
6935   case ISD::UDIV:
6936   case ISD::UREM: {
6937     MVT VT = N->getSimpleValueType(0);
6938     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6939            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6940            "Unexpected custom legalisation");
6941     // Don't promote division/remainder by constant since we should expand those
6942     // to multiply by magic constant.
6943     // FIXME: What if the expansion is disabled for minsize.
6944     if (N->getOperand(1).getOpcode() == ISD::Constant)
6945       return;
6946 
6947     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6948     // the upper 32 bits. For other types we need to sign or zero extend
6949     // based on the opcode.
6950     unsigned ExtOpc = ISD::ANY_EXTEND;
6951     if (VT != MVT::i32)
6952       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6953                                            : ISD::ZERO_EXTEND;
6954 
6955     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6956     break;
6957   }
6958   case ISD::UADDO:
6959   case ISD::USUBO: {
6960     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6961            "Unexpected custom legalisation");
6962     bool IsAdd = N->getOpcode() == ISD::UADDO;
6963     // Create an ADDW or SUBW.
6964     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6965     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6966     SDValue Res =
6967         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6968     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6969                       DAG.getValueType(MVT::i32));
6970 
6971     SDValue Overflow;
6972     if (IsAdd && isOneConstant(RHS)) {
6973       // Special case uaddo X, 1 overflowed if the addition result is 0.
6974       // FIXME: We can do this for any constant RHS by using (X + C) < C.
6975       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res,
6976                               DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ);
6977     } else {
6978       // Sign extend the LHS and perform an unsigned compare with the ADDW
6979       // result. Since the inputs are sign extended from i32, this is equivalent
6980       // to comparing the lower 32 bits.
6981       LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6982       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6983                               IsAdd ? ISD::SETULT : ISD::SETUGT);
6984     }
6985 
6986     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6987     Results.push_back(Overflow);
6988     return;
6989   }
6990   case ISD::UADDSAT:
6991   case ISD::USUBSAT: {
6992     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6993            "Unexpected custom legalisation");
6994     if (Subtarget.hasStdExtZbb()) {
6995       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6996       // sign extend allows overflow of the lower 32 bits to be detected on
6997       // the promoted size.
6998       SDValue LHS =
6999           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
7000       SDValue RHS =
7001           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
7002       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
7003       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7004       return;
7005     }
7006 
7007     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
7008     // promotion for UADDO/USUBO.
7009     Results.push_back(expandAddSubSat(N, DAG));
7010     return;
7011   }
7012   case ISD::ABS: {
7013     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7014            "Unexpected custom legalisation");
7015           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
7016 
7017     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
7018 
7019     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7020 
7021     // Freeze the source so we can increase it's use count.
7022     Src = DAG.getFreeze(Src);
7023 
7024     // Copy sign bit to all bits using the sraiw pattern.
7025     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
7026                                    DAG.getValueType(MVT::i32));
7027     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
7028                            DAG.getConstant(31, DL, MVT::i64));
7029 
7030     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
7031     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
7032 
7033     // NOTE: The result is only required to be anyextended, but sext is
7034     // consistent with type legalization of sub.
7035     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
7036                          DAG.getValueType(MVT::i32));
7037     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
7038     return;
7039   }
7040   case ISD::BITCAST: {
7041     EVT VT = N->getValueType(0);
7042     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
7043     SDValue Op0 = N->getOperand(0);
7044     EVT Op0VT = Op0.getValueType();
7045     MVT XLenVT = Subtarget.getXLenVT();
7046     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
7047       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
7048       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
7049     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
7050                Subtarget.hasStdExtF()) {
7051       SDValue FPConv =
7052           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
7053       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
7054     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
7055                isTypeLegal(Op0VT)) {
7056       // Custom-legalize bitcasts from fixed-length vector types to illegal
7057       // scalar types in order to improve codegen. Bitcast the vector to a
7058       // one-element vector type whose element type is the same as the result
7059       // type, and extract the first element.
7060       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
7061       if (isTypeLegal(BVT)) {
7062         SDValue BVec = DAG.getBitcast(BVT, Op0);
7063         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
7064                                       DAG.getConstant(0, DL, XLenVT)));
7065       }
7066     }
7067     break;
7068   }
7069   case RISCVISD::GREV:
7070   case RISCVISD::GORC:
7071   case RISCVISD::SHFL: {
7072     MVT VT = N->getSimpleValueType(0);
7073     MVT XLenVT = Subtarget.getXLenVT();
7074     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
7075            "Unexpected custom legalisation");
7076     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
7077     assert((Subtarget.hasStdExtZbp() ||
7078             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
7079              N->getConstantOperandVal(1) == 7)) &&
7080            "Unexpected extension");
7081     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7082     SDValue NewOp1 =
7083         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
7084     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
7085     // ReplaceNodeResults requires we maintain the same type for the return
7086     // value.
7087     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
7088     break;
7089   }
7090   case ISD::BSWAP:
7091   case ISD::BITREVERSE: {
7092     MVT VT = N->getSimpleValueType(0);
7093     MVT XLenVT = Subtarget.getXLenVT();
7094     assert((VT == MVT::i8 || VT == MVT::i16 ||
7095             (VT == MVT::i32 && Subtarget.is64Bit())) &&
7096            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
7097     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7098     unsigned Imm = VT.getSizeInBits() - 1;
7099     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
7100     if (N->getOpcode() == ISD::BSWAP)
7101       Imm &= ~0x7U;
7102     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
7103                                 DAG.getConstant(Imm, DL, XLenVT));
7104     // ReplaceNodeResults requires we maintain the same type for the return
7105     // value.
7106     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
7107     break;
7108   }
7109   case ISD::FSHL:
7110   case ISD::FSHR: {
7111     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7112            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
7113     SDValue NewOp0 =
7114         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7115     SDValue NewOp1 =
7116         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7117     SDValue NewShAmt =
7118         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7119     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
7120     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
7121     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
7122                            DAG.getConstant(0x1f, DL, MVT::i64));
7123     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
7124     // instruction use different orders. fshl will return its first operand for
7125     // shift of zero, fshr will return its second operand. fsl and fsr both
7126     // return rs1 so the ISD nodes need to have different operand orders.
7127     // Shift amount is in rs2.
7128     unsigned Opc = RISCVISD::FSLW;
7129     if (N->getOpcode() == ISD::FSHR) {
7130       std::swap(NewOp0, NewOp1);
7131       Opc = RISCVISD::FSRW;
7132     }
7133     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
7134     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
7135     break;
7136   }
7137   case ISD::EXTRACT_VECTOR_ELT: {
7138     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
7139     // type is illegal (currently only vXi64 RV32).
7140     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
7141     // transferred to the destination register. We issue two of these from the
7142     // upper- and lower- halves of the SEW-bit vector element, slid down to the
7143     // first element.
7144     SDValue Vec = N->getOperand(0);
7145     SDValue Idx = N->getOperand(1);
7146 
7147     // The vector type hasn't been legalized yet so we can't issue target
7148     // specific nodes if it needs legalization.
7149     // FIXME: We would manually legalize if it's important.
7150     if (!isTypeLegal(Vec.getValueType()))
7151       return;
7152 
7153     MVT VecVT = Vec.getSimpleValueType();
7154 
7155     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7156            VecVT.getVectorElementType() == MVT::i64 &&
7157            "Unexpected EXTRACT_VECTOR_ELT legalization");
7158 
7159     // If this is a fixed vector, we need to convert it to a scalable vector.
7160     MVT ContainerVT = VecVT;
7161     if (VecVT.isFixedLengthVector()) {
7162       ContainerVT = getContainerForFixedLengthVector(VecVT);
7163       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7164     }
7165 
7166     MVT XLenVT = Subtarget.getXLenVT();
7167 
7168     // Use a VL of 1 to avoid processing more elements than we need.
7169     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
7170     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7171     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7172 
7173     // Unless the index is known to be 0, we must slide the vector down to get
7174     // the desired element into index 0.
7175     if (!isNullConstant(Idx)) {
7176       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7177                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7178     }
7179 
7180     // Extract the lower XLEN bits of the correct vector element.
7181     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7182 
7183     // To extract the upper XLEN bits of the vector element, shift the first
7184     // element right by 32 bits and re-extract the lower XLEN bits.
7185     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7186                                      DAG.getUNDEF(ContainerVT),
7187                                      DAG.getConstant(32, DL, XLenVT), VL);
7188     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7189                                  ThirtyTwoV, Mask, VL);
7190 
7191     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7192 
7193     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7194     break;
7195   }
7196   case ISD::INTRINSIC_WO_CHAIN: {
7197     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7198     switch (IntNo) {
7199     default:
7200       llvm_unreachable(
7201           "Don't know how to custom type legalize this intrinsic!");
7202     case Intrinsic::riscv_grev:
7203     case Intrinsic::riscv_gorc: {
7204       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7205              "Unexpected custom legalisation");
7206       SDValue NewOp1 =
7207           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7208       SDValue NewOp2 =
7209           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7210       unsigned Opc =
7211           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7212       // If the control is a constant, promote the node by clearing any extra
7213       // bits bits in the control. isel will form greviw/gorciw if the result is
7214       // sign extended.
7215       if (isa<ConstantSDNode>(NewOp2)) {
7216         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7217                              DAG.getConstant(0x1f, DL, MVT::i64));
7218         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7219       }
7220       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7221       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7222       break;
7223     }
7224     case Intrinsic::riscv_bcompress:
7225     case Intrinsic::riscv_bdecompress:
7226     case Intrinsic::riscv_bfp:
7227     case Intrinsic::riscv_fsl:
7228     case Intrinsic::riscv_fsr: {
7229       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7230              "Unexpected custom legalisation");
7231       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7232       break;
7233     }
7234     case Intrinsic::riscv_orc_b: {
7235       // Lower to the GORCI encoding for orc.b with the operand extended.
7236       SDValue NewOp =
7237           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7238       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7239                                 DAG.getConstant(7, DL, MVT::i64));
7240       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7241       return;
7242     }
7243     case Intrinsic::riscv_shfl:
7244     case Intrinsic::riscv_unshfl: {
7245       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7246              "Unexpected custom legalisation");
7247       SDValue NewOp1 =
7248           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7249       SDValue NewOp2 =
7250           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7251       unsigned Opc =
7252           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7253       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7254       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7255       // will be shuffled the same way as the lower 32 bit half, but the two
7256       // halves won't cross.
7257       if (isa<ConstantSDNode>(NewOp2)) {
7258         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7259                              DAG.getConstant(0xf, DL, MVT::i64));
7260         Opc =
7261             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7262       }
7263       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7264       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7265       break;
7266     }
7267     case Intrinsic::riscv_vmv_x_s: {
7268       EVT VT = N->getValueType(0);
7269       MVT XLenVT = Subtarget.getXLenVT();
7270       if (VT.bitsLT(XLenVT)) {
7271         // Simple case just extract using vmv.x.s and truncate.
7272         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7273                                       Subtarget.getXLenVT(), N->getOperand(1));
7274         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7275         return;
7276       }
7277 
7278       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7279              "Unexpected custom legalization");
7280 
7281       // We need to do the move in two steps.
7282       SDValue Vec = N->getOperand(1);
7283       MVT VecVT = Vec.getSimpleValueType();
7284 
7285       // First extract the lower XLEN bits of the element.
7286       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7287 
7288       // To extract the upper XLEN bits of the vector element, shift the first
7289       // element right by 32 bits and re-extract the lower XLEN bits.
7290       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7291       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7292       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7293       SDValue ThirtyTwoV =
7294           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7295                       DAG.getConstant(32, DL, XLenVT), VL);
7296       SDValue LShr32 =
7297           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7298       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7299 
7300       Results.push_back(
7301           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7302       break;
7303     }
7304     }
7305     break;
7306   }
7307   case ISD::VECREDUCE_ADD:
7308   case ISD::VECREDUCE_AND:
7309   case ISD::VECREDUCE_OR:
7310   case ISD::VECREDUCE_XOR:
7311   case ISD::VECREDUCE_SMAX:
7312   case ISD::VECREDUCE_UMAX:
7313   case ISD::VECREDUCE_SMIN:
7314   case ISD::VECREDUCE_UMIN:
7315     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7316       Results.push_back(V);
7317     break;
7318   case ISD::VP_REDUCE_ADD:
7319   case ISD::VP_REDUCE_AND:
7320   case ISD::VP_REDUCE_OR:
7321   case ISD::VP_REDUCE_XOR:
7322   case ISD::VP_REDUCE_SMAX:
7323   case ISD::VP_REDUCE_UMAX:
7324   case ISD::VP_REDUCE_SMIN:
7325   case ISD::VP_REDUCE_UMIN:
7326     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7327       Results.push_back(V);
7328     break;
7329   case ISD::FLT_ROUNDS_: {
7330     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7331     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7332     Results.push_back(Res.getValue(0));
7333     Results.push_back(Res.getValue(1));
7334     break;
7335   }
7336   }
7337 }
7338 
7339 // A structure to hold one of the bit-manipulation patterns below. Together, a
7340 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7341 //   (or (and (shl x, 1), 0xAAAAAAAA),
7342 //       (and (srl x, 1), 0x55555555))
7343 struct RISCVBitmanipPat {
7344   SDValue Op;
7345   unsigned ShAmt;
7346   bool IsSHL;
7347 
7348   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7349     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7350   }
7351 };
7352 
7353 // Matches patterns of the form
7354 //   (and (shl x, C2), (C1 << C2))
7355 //   (and (srl x, C2), C1)
7356 //   (shl (and x, C1), C2)
7357 //   (srl (and x, (C1 << C2)), C2)
7358 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7359 // The expected masks for each shift amount are specified in BitmanipMasks where
7360 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7361 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7362 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7363 // XLen is 64.
7364 static Optional<RISCVBitmanipPat>
7365 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7366   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7367          "Unexpected number of masks");
7368   Optional<uint64_t> Mask;
7369   // Optionally consume a mask around the shift operation.
7370   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7371     Mask = Op.getConstantOperandVal(1);
7372     Op = Op.getOperand(0);
7373   }
7374   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7375     return None;
7376   bool IsSHL = Op.getOpcode() == ISD::SHL;
7377 
7378   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7379     return None;
7380   uint64_t ShAmt = Op.getConstantOperandVal(1);
7381 
7382   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7383   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7384     return None;
7385   // If we don't have enough masks for 64 bit, then we must be trying to
7386   // match SHFL so we're only allowed to shift 1/4 of the width.
7387   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7388     return None;
7389 
7390   SDValue Src = Op.getOperand(0);
7391 
7392   // The expected mask is shifted left when the AND is found around SHL
7393   // patterns.
7394   //   ((x >> 1) & 0x55555555)
7395   //   ((x << 1) & 0xAAAAAAAA)
7396   bool SHLExpMask = IsSHL;
7397 
7398   if (!Mask) {
7399     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7400     // the mask is all ones: consume that now.
7401     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7402       Mask = Src.getConstantOperandVal(1);
7403       Src = Src.getOperand(0);
7404       // The expected mask is now in fact shifted left for SRL, so reverse the
7405       // decision.
7406       //   ((x & 0xAAAAAAAA) >> 1)
7407       //   ((x & 0x55555555) << 1)
7408       SHLExpMask = !SHLExpMask;
7409     } else {
7410       // Use a default shifted mask of all-ones if there's no AND, truncated
7411       // down to the expected width. This simplifies the logic later on.
7412       Mask = maskTrailingOnes<uint64_t>(Width);
7413       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7414     }
7415   }
7416 
7417   unsigned MaskIdx = Log2_32(ShAmt);
7418   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7419 
7420   if (SHLExpMask)
7421     ExpMask <<= ShAmt;
7422 
7423   if (Mask != ExpMask)
7424     return None;
7425 
7426   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7427 }
7428 
7429 // Matches any of the following bit-manipulation patterns:
7430 //   (and (shl x, 1), (0x55555555 << 1))
7431 //   (and (srl x, 1), 0x55555555)
7432 //   (shl (and x, 0x55555555), 1)
7433 //   (srl (and x, (0x55555555 << 1)), 1)
7434 // where the shift amount and mask may vary thus:
7435 //   [1]  = 0x55555555 / 0xAAAAAAAA
7436 //   [2]  = 0x33333333 / 0xCCCCCCCC
7437 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7438 //   [8]  = 0x00FF00FF / 0xFF00FF00
7439 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7440 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7441 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7442   // These are the unshifted masks which we use to match bit-manipulation
7443   // patterns. They may be shifted left in certain circumstances.
7444   static const uint64_t BitmanipMasks[] = {
7445       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7446       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7447 
7448   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7449 }
7450 
7451 // Match the following pattern as a GREVI(W) operation
7452 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7453 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7454                                const RISCVSubtarget &Subtarget) {
7455   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7456   EVT VT = Op.getValueType();
7457 
7458   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7459     auto LHS = matchGREVIPat(Op.getOperand(0));
7460     auto RHS = matchGREVIPat(Op.getOperand(1));
7461     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7462       SDLoc DL(Op);
7463       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7464                          DAG.getConstant(LHS->ShAmt, DL, VT));
7465     }
7466   }
7467   return SDValue();
7468 }
7469 
7470 // Matches any the following pattern as a GORCI(W) operation
7471 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7472 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7473 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7474 // Note that with the variant of 3.,
7475 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7476 // the inner pattern will first be matched as GREVI and then the outer
7477 // pattern will be matched to GORC via the first rule above.
7478 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7479 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7480                                const RISCVSubtarget &Subtarget) {
7481   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7482   EVT VT = Op.getValueType();
7483 
7484   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7485     SDLoc DL(Op);
7486     SDValue Op0 = Op.getOperand(0);
7487     SDValue Op1 = Op.getOperand(1);
7488 
7489     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7490       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7491           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7492           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7493         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7494       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7495       if ((Reverse.getOpcode() == ISD::ROTL ||
7496            Reverse.getOpcode() == ISD::ROTR) &&
7497           Reverse.getOperand(0) == X &&
7498           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7499         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7500         if (RotAmt == (VT.getSizeInBits() / 2))
7501           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7502                              DAG.getConstant(RotAmt, DL, VT));
7503       }
7504       return SDValue();
7505     };
7506 
7507     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7508     if (SDValue V = MatchOROfReverse(Op0, Op1))
7509       return V;
7510     if (SDValue V = MatchOROfReverse(Op1, Op0))
7511       return V;
7512 
7513     // OR is commutable so canonicalize its OR operand to the left
7514     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7515       std::swap(Op0, Op1);
7516     if (Op0.getOpcode() != ISD::OR)
7517       return SDValue();
7518     SDValue OrOp0 = Op0.getOperand(0);
7519     SDValue OrOp1 = Op0.getOperand(1);
7520     auto LHS = matchGREVIPat(OrOp0);
7521     // OR is commutable so swap the operands and try again: x might have been
7522     // on the left
7523     if (!LHS) {
7524       std::swap(OrOp0, OrOp1);
7525       LHS = matchGREVIPat(OrOp0);
7526     }
7527     auto RHS = matchGREVIPat(Op1);
7528     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7529       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7530                          DAG.getConstant(LHS->ShAmt, DL, VT));
7531     }
7532   }
7533   return SDValue();
7534 }
7535 
7536 // Matches any of the following bit-manipulation patterns:
7537 //   (and (shl x, 1), (0x22222222 << 1))
7538 //   (and (srl x, 1), 0x22222222)
7539 //   (shl (and x, 0x22222222), 1)
7540 //   (srl (and x, (0x22222222 << 1)), 1)
7541 // where the shift amount and mask may vary thus:
7542 //   [1]  = 0x22222222 / 0x44444444
7543 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7544 //   [4]  = 0x00F000F0 / 0x0F000F00
7545 //   [8]  = 0x0000FF00 / 0x00FF0000
7546 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7547 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7548   // These are the unshifted masks which we use to match bit-manipulation
7549   // patterns. They may be shifted left in certain circumstances.
7550   static const uint64_t BitmanipMasks[] = {
7551       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7552       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7553 
7554   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7555 }
7556 
7557 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7558 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7559                                const RISCVSubtarget &Subtarget) {
7560   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7561   EVT VT = Op.getValueType();
7562 
7563   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7564     return SDValue();
7565 
7566   SDValue Op0 = Op.getOperand(0);
7567   SDValue Op1 = Op.getOperand(1);
7568 
7569   // Or is commutable so canonicalize the second OR to the LHS.
7570   if (Op0.getOpcode() != ISD::OR)
7571     std::swap(Op0, Op1);
7572   if (Op0.getOpcode() != ISD::OR)
7573     return SDValue();
7574 
7575   // We found an inner OR, so our operands are the operands of the inner OR
7576   // and the other operand of the outer OR.
7577   SDValue A = Op0.getOperand(0);
7578   SDValue B = Op0.getOperand(1);
7579   SDValue C = Op1;
7580 
7581   auto Match1 = matchSHFLPat(A);
7582   auto Match2 = matchSHFLPat(B);
7583 
7584   // If neither matched, we failed.
7585   if (!Match1 && !Match2)
7586     return SDValue();
7587 
7588   // We had at least one match. if one failed, try the remaining C operand.
7589   if (!Match1) {
7590     std::swap(A, C);
7591     Match1 = matchSHFLPat(A);
7592     if (!Match1)
7593       return SDValue();
7594   } else if (!Match2) {
7595     std::swap(B, C);
7596     Match2 = matchSHFLPat(B);
7597     if (!Match2)
7598       return SDValue();
7599   }
7600   assert(Match1 && Match2);
7601 
7602   // Make sure our matches pair up.
7603   if (!Match1->formsPairWith(*Match2))
7604     return SDValue();
7605 
7606   // All the remains is to make sure C is an AND with the same input, that masks
7607   // out the bits that are being shuffled.
7608   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7609       C.getOperand(0) != Match1->Op)
7610     return SDValue();
7611 
7612   uint64_t Mask = C.getConstantOperandVal(1);
7613 
7614   static const uint64_t BitmanipMasks[] = {
7615       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7616       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7617   };
7618 
7619   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7620   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7621   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7622 
7623   if (Mask != ExpMask)
7624     return SDValue();
7625 
7626   SDLoc DL(Op);
7627   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7628                      DAG.getConstant(Match1->ShAmt, DL, VT));
7629 }
7630 
7631 // Optimize (add (shl x, c0), (shl y, c1)) ->
7632 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7633 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7634                                   const RISCVSubtarget &Subtarget) {
7635   // Perform this optimization only in the zba extension.
7636   if (!Subtarget.hasStdExtZba())
7637     return SDValue();
7638 
7639   // Skip for vector types and larger types.
7640   EVT VT = N->getValueType(0);
7641   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7642     return SDValue();
7643 
7644   // The two operand nodes must be SHL and have no other use.
7645   SDValue N0 = N->getOperand(0);
7646   SDValue N1 = N->getOperand(1);
7647   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7648       !N0->hasOneUse() || !N1->hasOneUse())
7649     return SDValue();
7650 
7651   // Check c0 and c1.
7652   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7653   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7654   if (!N0C || !N1C)
7655     return SDValue();
7656   int64_t C0 = N0C->getSExtValue();
7657   int64_t C1 = N1C->getSExtValue();
7658   if (C0 <= 0 || C1 <= 0)
7659     return SDValue();
7660 
7661   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7662   int64_t Bits = std::min(C0, C1);
7663   int64_t Diff = std::abs(C0 - C1);
7664   if (Diff != 1 && Diff != 2 && Diff != 3)
7665     return SDValue();
7666 
7667   // Build nodes.
7668   SDLoc DL(N);
7669   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7670   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7671   SDValue NA0 =
7672       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7673   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7674   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7675 }
7676 
7677 // Combine
7678 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7679 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7680 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7681 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7682 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7683 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7684 // The grev patterns represents BSWAP.
7685 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7686 // off the grev.
7687 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7688                                           const RISCVSubtarget &Subtarget) {
7689   bool IsWInstruction =
7690       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7691   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7692           IsWInstruction) &&
7693          "Unexpected opcode!");
7694   SDValue Src = N->getOperand(0);
7695   EVT VT = N->getValueType(0);
7696   SDLoc DL(N);
7697 
7698   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7699     return SDValue();
7700 
7701   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7702       !isa<ConstantSDNode>(Src.getOperand(1)))
7703     return SDValue();
7704 
7705   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7706   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7707 
7708   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7709   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7710   unsigned ShAmt1 = N->getConstantOperandVal(1);
7711   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7712   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7713     return SDValue();
7714 
7715   Src = Src.getOperand(0);
7716 
7717   // Toggle bit the MSB of the shift.
7718   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7719   if (CombinedShAmt == 0)
7720     return Src;
7721 
7722   SDValue Res = DAG.getNode(
7723       RISCVISD::GREV, DL, VT, Src,
7724       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7725   if (!IsWInstruction)
7726     return Res;
7727 
7728   // Sign extend the result to match the behavior of the rotate. This will be
7729   // selected to GREVIW in isel.
7730   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7731                      DAG.getValueType(MVT::i32));
7732 }
7733 
7734 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7735 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7736 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7737 // not undo itself, but they are redundant.
7738 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7739   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7740   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7741   SDValue Src = N->getOperand(0);
7742 
7743   if (Src.getOpcode() != N->getOpcode())
7744     return SDValue();
7745 
7746   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7747       !isa<ConstantSDNode>(Src.getOperand(1)))
7748     return SDValue();
7749 
7750   unsigned ShAmt1 = N->getConstantOperandVal(1);
7751   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7752   Src = Src.getOperand(0);
7753 
7754   unsigned CombinedShAmt;
7755   if (IsGORC)
7756     CombinedShAmt = ShAmt1 | ShAmt2;
7757   else
7758     CombinedShAmt = ShAmt1 ^ ShAmt2;
7759 
7760   if (CombinedShAmt == 0)
7761     return Src;
7762 
7763   SDLoc DL(N);
7764   return DAG.getNode(
7765       N->getOpcode(), DL, N->getValueType(0), Src,
7766       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7767 }
7768 
7769 // Combine a constant select operand into its use:
7770 //
7771 // (and (select cond, -1, c), x)
7772 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7773 // (or  (select cond, 0, c), x)
7774 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7775 // (xor (select cond, 0, c), x)
7776 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7777 // (add (select cond, 0, c), x)
7778 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7779 // (sub x, (select cond, 0, c))
7780 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7781 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7782                                    SelectionDAG &DAG, bool AllOnes) {
7783   EVT VT = N->getValueType(0);
7784 
7785   // Skip vectors.
7786   if (VT.isVector())
7787     return SDValue();
7788 
7789   if ((Slct.getOpcode() != ISD::SELECT &&
7790        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7791       !Slct.hasOneUse())
7792     return SDValue();
7793 
7794   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7795     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7796   };
7797 
7798   bool SwapSelectOps;
7799   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7800   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7801   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7802   SDValue NonConstantVal;
7803   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7804     SwapSelectOps = false;
7805     NonConstantVal = FalseVal;
7806   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7807     SwapSelectOps = true;
7808     NonConstantVal = TrueVal;
7809   } else
7810     return SDValue();
7811 
7812   // Slct is now know to be the desired identity constant when CC is true.
7813   TrueVal = OtherOp;
7814   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7815   // Unless SwapSelectOps says the condition should be false.
7816   if (SwapSelectOps)
7817     std::swap(TrueVal, FalseVal);
7818 
7819   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7820     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7821                        {Slct.getOperand(0), Slct.getOperand(1),
7822                         Slct.getOperand(2), TrueVal, FalseVal});
7823 
7824   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7825                      {Slct.getOperand(0), TrueVal, FalseVal});
7826 }
7827 
7828 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7829 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7830                                               bool AllOnes) {
7831   SDValue N0 = N->getOperand(0);
7832   SDValue N1 = N->getOperand(1);
7833   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7834     return Result;
7835   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7836     return Result;
7837   return SDValue();
7838 }
7839 
7840 // Transform (add (mul x, c0), c1) ->
7841 //           (add (mul (add x, c1/c0), c0), c1%c0).
7842 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7843 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7844 // to an infinite loop in DAGCombine if transformed.
7845 // Or transform (add (mul x, c0), c1) ->
7846 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7847 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7848 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7849 // lead to an infinite loop in DAGCombine if transformed.
7850 // Or transform (add (mul x, c0), c1) ->
7851 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7852 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7853 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7854 // lead to an infinite loop in DAGCombine if transformed.
7855 // Or transform (add (mul x, c0), c1) ->
7856 //              (mul (add x, c1/c0), c0).
7857 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7858 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7859                                      const RISCVSubtarget &Subtarget) {
7860   // Skip for vector types and larger types.
7861   EVT VT = N->getValueType(0);
7862   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7863     return SDValue();
7864   // The first operand node must be a MUL and has no other use.
7865   SDValue N0 = N->getOperand(0);
7866   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7867     return SDValue();
7868   // Check if c0 and c1 match above conditions.
7869   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7870   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7871   if (!N0C || !N1C)
7872     return SDValue();
7873   // If N0C has multiple uses it's possible one of the cases in
7874   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7875   // in an infinite loop.
7876   if (!N0C->hasOneUse())
7877     return SDValue();
7878   int64_t C0 = N0C->getSExtValue();
7879   int64_t C1 = N1C->getSExtValue();
7880   int64_t CA, CB;
7881   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7882     return SDValue();
7883   // Search for proper CA (non-zero) and CB that both are simm12.
7884   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7885       !isInt<12>(C0 * (C1 / C0))) {
7886     CA = C1 / C0;
7887     CB = C1 % C0;
7888   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7889              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7890     CA = C1 / C0 + 1;
7891     CB = C1 % C0 - C0;
7892   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7893              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7894     CA = C1 / C0 - 1;
7895     CB = C1 % C0 + C0;
7896   } else
7897     return SDValue();
7898   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7899   SDLoc DL(N);
7900   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7901                              DAG.getConstant(CA, DL, VT));
7902   SDValue New1 =
7903       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7904   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7905 }
7906 
7907 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7908                                  const RISCVSubtarget &Subtarget) {
7909   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7910     return V;
7911   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7912     return V;
7913   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7914   //      (select lhs, rhs, cc, x, (add x, y))
7915   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7916 }
7917 
7918 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7919   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7920   //      (select lhs, rhs, cc, x, (sub x, y))
7921   SDValue N0 = N->getOperand(0);
7922   SDValue N1 = N->getOperand(1);
7923   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7924 }
7925 
7926 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7927   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7928   //      (select lhs, rhs, cc, x, (and x, y))
7929   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7930 }
7931 
7932 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7933                                 const RISCVSubtarget &Subtarget) {
7934   if (Subtarget.hasStdExtZbp()) {
7935     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7936       return GREV;
7937     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7938       return GORC;
7939     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7940       return SHFL;
7941   }
7942 
7943   // fold (or (select cond, 0, y), x) ->
7944   //      (select cond, x, (or x, y))
7945   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7946 }
7947 
7948 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7949   SDValue N0 = N->getOperand(0);
7950   SDValue N1 = N->getOperand(1);
7951 
7952   // fold (xor (sllw 1, x), -1) -> (rolw ~1, x)
7953   // NOTE: Assumes ROL being legal means ROLW is legal.
7954   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7955   if (N0.getOpcode() == RISCVISD::SLLW &&
7956       isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) &&
7957       TLI.isOperationLegal(ISD::ROTL, MVT::i64)) {
7958     SDLoc DL(N);
7959     return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64,
7960                        DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1));
7961   }
7962 
7963   // fold (xor (select cond, 0, y), x) ->
7964   //      (select cond, x, (xor x, y))
7965   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7966 }
7967 
7968 static SDValue
7969 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
7970                                 const RISCVSubtarget &Subtarget) {
7971   SDValue Src = N->getOperand(0);
7972   EVT VT = N->getValueType(0);
7973 
7974   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
7975   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7976       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
7977     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
7978                        Src.getOperand(0));
7979 
7980   // Fold (i64 (sext_inreg (abs X), i32)) ->
7981   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
7982   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
7983   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
7984   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
7985   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
7986   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
7987   // may get combined into an earlier operation so we need to use
7988   // ComputeNumSignBits.
7989   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
7990   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
7991   // we can't assume that X has 33 sign bits. We must check.
7992   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
7993       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
7994       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
7995       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
7996     SDLoc DL(N);
7997     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
7998     SDValue Neg =
7999         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
8000     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
8001                       DAG.getValueType(MVT::i32));
8002     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
8003   }
8004 
8005   return SDValue();
8006 }
8007 
8008 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
8009 // vwadd(u).vv/vx or vwsub(u).vv/vx.
8010 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
8011                                              bool Commute = false) {
8012   assert((N->getOpcode() == RISCVISD::ADD_VL ||
8013           N->getOpcode() == RISCVISD::SUB_VL) &&
8014          "Unexpected opcode");
8015   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
8016   SDValue Op0 = N->getOperand(0);
8017   SDValue Op1 = N->getOperand(1);
8018   if (Commute)
8019     std::swap(Op0, Op1);
8020 
8021   MVT VT = N->getSimpleValueType(0);
8022 
8023   // Determine the narrow size for a widening add/sub.
8024   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8025   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8026                                   VT.getVectorElementCount());
8027 
8028   SDValue Mask = N->getOperand(2);
8029   SDValue VL = N->getOperand(3);
8030 
8031   SDLoc DL(N);
8032 
8033   // If the RHS is a sext or zext, we can form a widening op.
8034   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
8035        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
8036       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
8037     unsigned ExtOpc = Op1.getOpcode();
8038     Op1 = Op1.getOperand(0);
8039     // Re-introduce narrower extends if needed.
8040     if (Op1.getValueType() != NarrowVT)
8041       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8042 
8043     unsigned WOpc;
8044     if (ExtOpc == RISCVISD::VSEXT_VL)
8045       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
8046     else
8047       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
8048 
8049     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
8050   }
8051 
8052   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
8053   // sext/zext?
8054 
8055   return SDValue();
8056 }
8057 
8058 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
8059 // vwsub(u).vv/vx.
8060 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
8061   SDValue Op0 = N->getOperand(0);
8062   SDValue Op1 = N->getOperand(1);
8063   SDValue Mask = N->getOperand(2);
8064   SDValue VL = N->getOperand(3);
8065 
8066   MVT VT = N->getSimpleValueType(0);
8067   MVT NarrowVT = Op1.getSimpleValueType();
8068   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
8069 
8070   unsigned VOpc;
8071   switch (N->getOpcode()) {
8072   default: llvm_unreachable("Unexpected opcode");
8073   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
8074   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
8075   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
8076   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
8077   }
8078 
8079   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8080                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
8081 
8082   SDLoc DL(N);
8083 
8084   // If the LHS is a sext or zext, we can narrow this op to the same size as
8085   // the RHS.
8086   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
8087        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
8088       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
8089     unsigned ExtOpc = Op0.getOpcode();
8090     Op0 = Op0.getOperand(0);
8091     // Re-introduce narrower extends if needed.
8092     if (Op0.getValueType() != NarrowVT)
8093       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8094     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
8095   }
8096 
8097   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8098                N->getOpcode() == RISCVISD::VWADDU_W_VL;
8099 
8100   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
8101   // to commute and use a vwadd(u).vx instead.
8102   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
8103       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
8104     Op0 = Op0.getOperand(1);
8105 
8106     // See if have enough sign bits or zero bits in the scalar to use a
8107     // widening add/sub by splatting to smaller element size.
8108     unsigned EltBits = VT.getScalarSizeInBits();
8109     unsigned ScalarBits = Op0.getValueSizeInBits();
8110     // Make sure we're getting all element bits from the scalar register.
8111     // FIXME: Support implicit sign extension of vmv.v.x?
8112     if (ScalarBits < EltBits)
8113       return SDValue();
8114 
8115     if (IsSigned) {
8116       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
8117         return SDValue();
8118     } else {
8119       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8120       if (!DAG.MaskedValueIsZero(Op0, Mask))
8121         return SDValue();
8122     }
8123 
8124     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8125                       DAG.getUNDEF(NarrowVT), Op0, VL);
8126     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
8127   }
8128 
8129   return SDValue();
8130 }
8131 
8132 // Try to form VWMUL, VWMULU or VWMULSU.
8133 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
8134 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
8135                                        bool Commute) {
8136   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
8137   SDValue Op0 = N->getOperand(0);
8138   SDValue Op1 = N->getOperand(1);
8139   if (Commute)
8140     std::swap(Op0, Op1);
8141 
8142   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
8143   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
8144   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
8145   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
8146     return SDValue();
8147 
8148   SDValue Mask = N->getOperand(2);
8149   SDValue VL = N->getOperand(3);
8150 
8151   // Make sure the mask and VL match.
8152   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8153     return SDValue();
8154 
8155   MVT VT = N->getSimpleValueType(0);
8156 
8157   // Determine the narrow size for a widening multiply.
8158   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8159   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8160                                   VT.getVectorElementCount());
8161 
8162   SDLoc DL(N);
8163 
8164   // See if the other operand is the same opcode.
8165   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8166     if (!Op1.hasOneUse())
8167       return SDValue();
8168 
8169     // Make sure the mask and VL match.
8170     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8171       return SDValue();
8172 
8173     Op1 = Op1.getOperand(0);
8174   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8175     // The operand is a splat of a scalar.
8176 
8177     // The pasthru must be undef for tail agnostic
8178     if (!Op1.getOperand(0).isUndef())
8179       return SDValue();
8180     // The VL must be the same.
8181     if (Op1.getOperand(2) != VL)
8182       return SDValue();
8183 
8184     // Get the scalar value.
8185     Op1 = Op1.getOperand(1);
8186 
8187     // See if have enough sign bits or zero bits in the scalar to use a
8188     // widening multiply by splatting to smaller element size.
8189     unsigned EltBits = VT.getScalarSizeInBits();
8190     unsigned ScalarBits = Op1.getValueSizeInBits();
8191     // Make sure we're getting all element bits from the scalar register.
8192     // FIXME: Support implicit sign extension of vmv.v.x?
8193     if (ScalarBits < EltBits)
8194       return SDValue();
8195 
8196     // If the LHS is a sign extend, try to use vwmul.
8197     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8198       // Can use vwmul.
8199     } else {
8200       // Otherwise try to use vwmulu or vwmulsu.
8201       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8202       if (DAG.MaskedValueIsZero(Op1, Mask))
8203         IsVWMULSU = IsSignExt;
8204       else
8205         return SDValue();
8206     }
8207 
8208     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8209                       DAG.getUNDEF(NarrowVT), Op1, VL);
8210   } else
8211     return SDValue();
8212 
8213   Op0 = Op0.getOperand(0);
8214 
8215   // Re-introduce narrower extends if needed.
8216   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8217   if (Op0.getValueType() != NarrowVT)
8218     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8219   // vwmulsu requires second operand to be zero extended.
8220   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8221   if (Op1.getValueType() != NarrowVT)
8222     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8223 
8224   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8225   if (!IsVWMULSU)
8226     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8227   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8228 }
8229 
8230 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8231   switch (Op.getOpcode()) {
8232   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8233   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8234   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8235   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8236   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8237   }
8238 
8239   return RISCVFPRndMode::Invalid;
8240 }
8241 
8242 // Fold
8243 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8244 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8245 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8246 //   (fp_to_int (fceil X))      -> fcvt X, rup
8247 //   (fp_to_int (fround X))     -> fcvt X, rmm
8248 static SDValue performFP_TO_INTCombine(SDNode *N,
8249                                        TargetLowering::DAGCombinerInfo &DCI,
8250                                        const RISCVSubtarget &Subtarget) {
8251   SelectionDAG &DAG = DCI.DAG;
8252   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8253   MVT XLenVT = Subtarget.getXLenVT();
8254 
8255   // Only handle XLen or i32 types. Other types narrower than XLen will
8256   // eventually be legalized to XLenVT.
8257   EVT VT = N->getValueType(0);
8258   if (VT != MVT::i32 && VT != XLenVT)
8259     return SDValue();
8260 
8261   SDValue Src = N->getOperand(0);
8262 
8263   // Ensure the FP type is also legal.
8264   if (!TLI.isTypeLegal(Src.getValueType()))
8265     return SDValue();
8266 
8267   // Don't do this for f16 with Zfhmin and not Zfh.
8268   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8269     return SDValue();
8270 
8271   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8272   if (FRM == RISCVFPRndMode::Invalid)
8273     return SDValue();
8274 
8275   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8276 
8277   unsigned Opc;
8278   if (VT == XLenVT)
8279     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8280   else
8281     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8282 
8283   SDLoc DL(N);
8284   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8285                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8286   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8287 }
8288 
8289 // Fold
8290 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8291 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8292 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8293 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8294 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8295 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8296                                        TargetLowering::DAGCombinerInfo &DCI,
8297                                        const RISCVSubtarget &Subtarget) {
8298   SelectionDAG &DAG = DCI.DAG;
8299   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8300   MVT XLenVT = Subtarget.getXLenVT();
8301 
8302   // Only handle XLen types. Other types narrower than XLen will eventually be
8303   // legalized to XLenVT.
8304   EVT DstVT = N->getValueType(0);
8305   if (DstVT != XLenVT)
8306     return SDValue();
8307 
8308   SDValue Src = N->getOperand(0);
8309 
8310   // Ensure the FP type is also legal.
8311   if (!TLI.isTypeLegal(Src.getValueType()))
8312     return SDValue();
8313 
8314   // Don't do this for f16 with Zfhmin and not Zfh.
8315   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8316     return SDValue();
8317 
8318   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8319 
8320   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8321   if (FRM == RISCVFPRndMode::Invalid)
8322     return SDValue();
8323 
8324   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8325 
8326   unsigned Opc;
8327   if (SatVT == DstVT)
8328     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8329   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8330     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8331   else
8332     return SDValue();
8333   // FIXME: Support other SatVTs by clamping before or after the conversion.
8334 
8335   Src = Src.getOperand(0);
8336 
8337   SDLoc DL(N);
8338   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8339                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8340 
8341   // RISCV FP-to-int conversions saturate to the destination register size, but
8342   // don't produce 0 for nan.
8343   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8344   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8345 }
8346 
8347 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8348 // smaller than XLenVT.
8349 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8350                                         const RISCVSubtarget &Subtarget) {
8351   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8352 
8353   SDValue Src = N->getOperand(0);
8354   if (Src.getOpcode() != ISD::BSWAP)
8355     return SDValue();
8356 
8357   EVT VT = N->getValueType(0);
8358   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8359       !isPowerOf2_32(VT.getSizeInBits()))
8360     return SDValue();
8361 
8362   SDLoc DL(N);
8363   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8364                      DAG.getConstant(7, DL, VT));
8365 }
8366 
8367 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8368                                                DAGCombinerInfo &DCI) const {
8369   SelectionDAG &DAG = DCI.DAG;
8370 
8371   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8372   // bits are demanded. N will be added to the Worklist if it was not deleted.
8373   // Caller should return SDValue(N, 0) if this returns true.
8374   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8375     SDValue Op = N->getOperand(OpNo);
8376     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8377     if (!SimplifyDemandedBits(Op, Mask, DCI))
8378       return false;
8379 
8380     if (N->getOpcode() != ISD::DELETED_NODE)
8381       DCI.AddToWorklist(N);
8382     return true;
8383   };
8384 
8385   switch (N->getOpcode()) {
8386   default:
8387     break;
8388   case RISCVISD::SplitF64: {
8389     SDValue Op0 = N->getOperand(0);
8390     // If the input to SplitF64 is just BuildPairF64 then the operation is
8391     // redundant. Instead, use BuildPairF64's operands directly.
8392     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8393       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8394 
8395     if (Op0->isUndef()) {
8396       SDValue Lo = DAG.getUNDEF(MVT::i32);
8397       SDValue Hi = DAG.getUNDEF(MVT::i32);
8398       return DCI.CombineTo(N, Lo, Hi);
8399     }
8400 
8401     SDLoc DL(N);
8402 
8403     // It's cheaper to materialise two 32-bit integers than to load a double
8404     // from the constant pool and transfer it to integer registers through the
8405     // stack.
8406     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8407       APInt V = C->getValueAPF().bitcastToAPInt();
8408       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8409       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8410       return DCI.CombineTo(N, Lo, Hi);
8411     }
8412 
8413     // This is a target-specific version of a DAGCombine performed in
8414     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8415     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8416     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8417     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8418         !Op0.getNode()->hasOneUse())
8419       break;
8420     SDValue NewSplitF64 =
8421         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8422                     Op0.getOperand(0));
8423     SDValue Lo = NewSplitF64.getValue(0);
8424     SDValue Hi = NewSplitF64.getValue(1);
8425     APInt SignBit = APInt::getSignMask(32);
8426     if (Op0.getOpcode() == ISD::FNEG) {
8427       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8428                                   DAG.getConstant(SignBit, DL, MVT::i32));
8429       return DCI.CombineTo(N, Lo, NewHi);
8430     }
8431     assert(Op0.getOpcode() == ISD::FABS);
8432     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8433                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8434     return DCI.CombineTo(N, Lo, NewHi);
8435   }
8436   case RISCVISD::SLLW:
8437   case RISCVISD::SRAW:
8438   case RISCVISD::SRLW: {
8439     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8440     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8441         SimplifyDemandedLowBitsHelper(1, 5))
8442       return SDValue(N, 0);
8443 
8444     break;
8445   }
8446   case ISD::ROTR:
8447   case ISD::ROTL:
8448   case RISCVISD::RORW:
8449   case RISCVISD::ROLW: {
8450     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8451       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8452       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8453           SimplifyDemandedLowBitsHelper(1, 5))
8454         return SDValue(N, 0);
8455     }
8456 
8457     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8458   }
8459   case RISCVISD::CLZW:
8460   case RISCVISD::CTZW: {
8461     // Only the lower 32 bits of the first operand are read
8462     if (SimplifyDemandedLowBitsHelper(0, 32))
8463       return SDValue(N, 0);
8464     break;
8465   }
8466   case RISCVISD::GREV:
8467   case RISCVISD::GORC: {
8468     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8469     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8470     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8471     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8472       return SDValue(N, 0);
8473 
8474     return combineGREVI_GORCI(N, DAG);
8475   }
8476   case RISCVISD::GREVW:
8477   case RISCVISD::GORCW: {
8478     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8479     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8480         SimplifyDemandedLowBitsHelper(1, 5))
8481       return SDValue(N, 0);
8482 
8483     break;
8484   }
8485   case RISCVISD::SHFL:
8486   case RISCVISD::UNSHFL: {
8487     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8488     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8489     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8490     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8491       return SDValue(N, 0);
8492 
8493     break;
8494   }
8495   case RISCVISD::SHFLW:
8496   case RISCVISD::UNSHFLW: {
8497     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8498     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8499         SimplifyDemandedLowBitsHelper(1, 4))
8500       return SDValue(N, 0);
8501 
8502     break;
8503   }
8504   case RISCVISD::BCOMPRESSW:
8505   case RISCVISD::BDECOMPRESSW: {
8506     // Only the lower 32 bits of LHS and RHS are read.
8507     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8508         SimplifyDemandedLowBitsHelper(1, 32))
8509       return SDValue(N, 0);
8510 
8511     break;
8512   }
8513   case RISCVISD::FSR:
8514   case RISCVISD::FSL:
8515   case RISCVISD::FSRW:
8516   case RISCVISD::FSLW: {
8517     bool IsWInstruction =
8518         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8519     unsigned BitWidth =
8520         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8521     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8522     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8523     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8524       return SDValue(N, 0);
8525 
8526     break;
8527   }
8528   case RISCVISD::FMV_X_ANYEXTH:
8529   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8530     SDLoc DL(N);
8531     SDValue Op0 = N->getOperand(0);
8532     MVT VT = N->getSimpleValueType(0);
8533     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8534     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8535     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8536     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8537          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8538         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8539          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8540       assert(Op0.getOperand(0).getValueType() == VT &&
8541              "Unexpected value type!");
8542       return Op0.getOperand(0);
8543     }
8544 
8545     // This is a target-specific version of a DAGCombine performed in
8546     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8547     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8548     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8549     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8550         !Op0.getNode()->hasOneUse())
8551       break;
8552     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8553     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8554     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
8555     if (Op0.getOpcode() == ISD::FNEG)
8556       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8557                          DAG.getConstant(SignBit, DL, VT));
8558 
8559     assert(Op0.getOpcode() == ISD::FABS);
8560     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8561                        DAG.getConstant(~SignBit, DL, VT));
8562   }
8563   case ISD::ADD:
8564     return performADDCombine(N, DAG, Subtarget);
8565   case ISD::SUB:
8566     return performSUBCombine(N, DAG);
8567   case ISD::AND:
8568     return performANDCombine(N, DAG);
8569   case ISD::OR:
8570     return performORCombine(N, DAG, Subtarget);
8571   case ISD::XOR:
8572     return performXORCombine(N, DAG);
8573   case ISD::SIGN_EXTEND_INREG:
8574     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8575   case ISD::ZERO_EXTEND:
8576     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8577     // type legalization. This is safe because fp_to_uint produces poison if
8578     // it overflows.
8579     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8580       SDValue Src = N->getOperand(0);
8581       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8582           isTypeLegal(Src.getOperand(0).getValueType()))
8583         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8584                            Src.getOperand(0));
8585       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8586           isTypeLegal(Src.getOperand(1).getValueType())) {
8587         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8588         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8589                                   Src.getOperand(0), Src.getOperand(1));
8590         DCI.CombineTo(N, Res);
8591         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8592         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8593         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8594       }
8595     }
8596     return SDValue();
8597   case RISCVISD::SELECT_CC: {
8598     // Transform
8599     SDValue LHS = N->getOperand(0);
8600     SDValue RHS = N->getOperand(1);
8601     SDValue TrueV = N->getOperand(3);
8602     SDValue FalseV = N->getOperand(4);
8603 
8604     // If the True and False values are the same, we don't need a select_cc.
8605     if (TrueV == FalseV)
8606       return TrueV;
8607 
8608     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8609     if (!ISD::isIntEqualitySetCC(CCVal))
8610       break;
8611 
8612     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8613     //      (select_cc X, Y, lt, trueV, falseV)
8614     // Sometimes the setcc is introduced after select_cc has been formed.
8615     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8616         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8617       // If we're looking for eq 0 instead of ne 0, we need to invert the
8618       // condition.
8619       bool Invert = CCVal == ISD::SETEQ;
8620       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8621       if (Invert)
8622         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8623 
8624       SDLoc DL(N);
8625       RHS = LHS.getOperand(1);
8626       LHS = LHS.getOperand(0);
8627       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8628 
8629       SDValue TargetCC = DAG.getCondCode(CCVal);
8630       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8631                          {LHS, RHS, TargetCC, TrueV, FalseV});
8632     }
8633 
8634     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8635     //      (select_cc X, Y, eq/ne, trueV, falseV)
8636     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8637       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8638                          {LHS.getOperand(0), LHS.getOperand(1),
8639                           N->getOperand(2), TrueV, FalseV});
8640     // (select_cc X, 1, setne, trueV, falseV) ->
8641     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8642     // This can occur when legalizing some floating point comparisons.
8643     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8644     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8645       SDLoc DL(N);
8646       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8647       SDValue TargetCC = DAG.getCondCode(CCVal);
8648       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8649       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8650                          {LHS, RHS, TargetCC, TrueV, FalseV});
8651     }
8652 
8653     break;
8654   }
8655   case RISCVISD::BR_CC: {
8656     SDValue LHS = N->getOperand(1);
8657     SDValue RHS = N->getOperand(2);
8658     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8659     if (!ISD::isIntEqualitySetCC(CCVal))
8660       break;
8661 
8662     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8663     //      (br_cc X, Y, lt, dest)
8664     // Sometimes the setcc is introduced after br_cc has been formed.
8665     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8666         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8667       // If we're looking for eq 0 instead of ne 0, we need to invert the
8668       // condition.
8669       bool Invert = CCVal == ISD::SETEQ;
8670       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8671       if (Invert)
8672         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8673 
8674       SDLoc DL(N);
8675       RHS = LHS.getOperand(1);
8676       LHS = LHS.getOperand(0);
8677       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8678 
8679       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8680                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8681                          N->getOperand(4));
8682     }
8683 
8684     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8685     //      (br_cc X, Y, eq/ne, trueV, falseV)
8686     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8687       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8688                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8689                          N->getOperand(3), N->getOperand(4));
8690 
8691     // (br_cc X, 1, setne, br_cc) ->
8692     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8693     // This can occur when legalizing some floating point comparisons.
8694     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8695     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8696       SDLoc DL(N);
8697       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8698       SDValue TargetCC = DAG.getCondCode(CCVal);
8699       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8700       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8701                          N->getOperand(0), LHS, RHS, TargetCC,
8702                          N->getOperand(4));
8703     }
8704     break;
8705   }
8706   case ISD::BITREVERSE:
8707     return performBITREVERSECombine(N, DAG, Subtarget);
8708   case ISD::FP_TO_SINT:
8709   case ISD::FP_TO_UINT:
8710     return performFP_TO_INTCombine(N, DCI, Subtarget);
8711   case ISD::FP_TO_SINT_SAT:
8712   case ISD::FP_TO_UINT_SAT:
8713     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8714   case ISD::FCOPYSIGN: {
8715     EVT VT = N->getValueType(0);
8716     if (!VT.isVector())
8717       break;
8718     // There is a form of VFSGNJ which injects the negated sign of its second
8719     // operand. Try and bubble any FNEG up after the extend/round to produce
8720     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8721     // TRUNC=1.
8722     SDValue In2 = N->getOperand(1);
8723     // Avoid cases where the extend/round has multiple uses, as duplicating
8724     // those is typically more expensive than removing a fneg.
8725     if (!In2.hasOneUse())
8726       break;
8727     if (In2.getOpcode() != ISD::FP_EXTEND &&
8728         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8729       break;
8730     In2 = In2.getOperand(0);
8731     if (In2.getOpcode() != ISD::FNEG)
8732       break;
8733     SDLoc DL(N);
8734     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8735     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8736                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8737   }
8738   case ISD::MGATHER:
8739   case ISD::MSCATTER:
8740   case ISD::VP_GATHER:
8741   case ISD::VP_SCATTER: {
8742     if (!DCI.isBeforeLegalize())
8743       break;
8744     SDValue Index, ScaleOp;
8745     bool IsIndexScaled = false;
8746     bool IsIndexSigned = false;
8747     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8748       Index = VPGSN->getIndex();
8749       ScaleOp = VPGSN->getScale();
8750       IsIndexScaled = VPGSN->isIndexScaled();
8751       IsIndexSigned = VPGSN->isIndexSigned();
8752     } else {
8753       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8754       Index = MGSN->getIndex();
8755       ScaleOp = MGSN->getScale();
8756       IsIndexScaled = MGSN->isIndexScaled();
8757       IsIndexSigned = MGSN->isIndexSigned();
8758     }
8759     EVT IndexVT = Index.getValueType();
8760     MVT XLenVT = Subtarget.getXLenVT();
8761     // RISCV indexed loads only support the "unsigned unscaled" addressing
8762     // mode, so anything else must be manually legalized.
8763     bool NeedsIdxLegalization =
8764         IsIndexScaled ||
8765         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8766     if (!NeedsIdxLegalization)
8767       break;
8768 
8769     SDLoc DL(N);
8770 
8771     // Any index legalization should first promote to XLenVT, so we don't lose
8772     // bits when scaling. This may create an illegal index type so we let
8773     // LLVM's legalization take care of the splitting.
8774     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8775     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8776       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8777       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8778                           DL, IndexVT, Index);
8779     }
8780 
8781     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8782     if (IsIndexScaled && Scale != 1) {
8783       // Manually scale the indices by the element size.
8784       // TODO: Sanitize the scale operand here?
8785       // TODO: For VP nodes, should we use VP_SHL here?
8786       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8787       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8788       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8789     }
8790 
8791     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
8792     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8793       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8794                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8795                               VPGN->getScale(), VPGN->getMask(),
8796                               VPGN->getVectorLength()},
8797                              VPGN->getMemOperand(), NewIndexTy);
8798     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8799       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8800                               {VPSN->getChain(), VPSN->getValue(),
8801                                VPSN->getBasePtr(), Index, VPSN->getScale(),
8802                                VPSN->getMask(), VPSN->getVectorLength()},
8803                               VPSN->getMemOperand(), NewIndexTy);
8804     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8805       return DAG.getMaskedGather(
8806           N->getVTList(), MGN->getMemoryVT(), DL,
8807           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8808            MGN->getBasePtr(), Index, MGN->getScale()},
8809           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8810     const auto *MSN = cast<MaskedScatterSDNode>(N);
8811     return DAG.getMaskedScatter(
8812         N->getVTList(), MSN->getMemoryVT(), DL,
8813         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8814          Index, MSN->getScale()},
8815         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8816   }
8817   case RISCVISD::SRA_VL:
8818   case RISCVISD::SRL_VL:
8819   case RISCVISD::SHL_VL: {
8820     SDValue ShAmt = N->getOperand(1);
8821     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8822       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8823       SDLoc DL(N);
8824       SDValue VL = N->getOperand(3);
8825       EVT VT = N->getValueType(0);
8826       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8827                           ShAmt.getOperand(1), VL);
8828       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8829                          N->getOperand(2), N->getOperand(3));
8830     }
8831     break;
8832   }
8833   case ISD::SRA:
8834   case ISD::SRL:
8835   case ISD::SHL: {
8836     SDValue ShAmt = N->getOperand(1);
8837     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8838       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8839       SDLoc DL(N);
8840       EVT VT = N->getValueType(0);
8841       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8842                           ShAmt.getOperand(1),
8843                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8844       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8845     }
8846     break;
8847   }
8848   case RISCVISD::ADD_VL:
8849     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8850       return V;
8851     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8852   case RISCVISD::SUB_VL:
8853     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8854   case RISCVISD::VWADD_W_VL:
8855   case RISCVISD::VWADDU_W_VL:
8856   case RISCVISD::VWSUB_W_VL:
8857   case RISCVISD::VWSUBU_W_VL:
8858     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8859   case RISCVISD::MUL_VL:
8860     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8861       return V;
8862     // Mul is commutative.
8863     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8864   case ISD::STORE: {
8865     auto *Store = cast<StoreSDNode>(N);
8866     SDValue Val = Store->getValue();
8867     // Combine store of vmv.x.s to vse with VL of 1.
8868     // FIXME: Support FP.
8869     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8870       SDValue Src = Val.getOperand(0);
8871       EVT VecVT = Src.getValueType();
8872       EVT MemVT = Store->getMemoryVT();
8873       // The memory VT and the element type must match.
8874       if (VecVT.getVectorElementType() == MemVT) {
8875         SDLoc DL(N);
8876         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8877         return DAG.getStoreVP(
8878             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8879             DAG.getConstant(1, DL, MaskVT),
8880             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8881             Store->getMemOperand(), Store->getAddressingMode(),
8882             Store->isTruncatingStore(), /*IsCompress*/ false);
8883       }
8884     }
8885 
8886     break;
8887   }
8888   case ISD::SPLAT_VECTOR: {
8889     EVT VT = N->getValueType(0);
8890     // Only perform this combine on legal MVT types.
8891     if (!isTypeLegal(VT))
8892       break;
8893     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
8894                                          DAG, Subtarget))
8895       return Gather;
8896     break;
8897   }
8898   case RISCVISD::VMV_V_X_VL: {
8899     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
8900     // scalar input.
8901     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
8902     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
8903     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
8904       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
8905         return SDValue(N, 0);
8906 
8907     break;
8908   }
8909   case ISD::INTRINSIC_WO_CHAIN: {
8910     unsigned IntNo = N->getConstantOperandVal(0);
8911     switch (IntNo) {
8912       // By default we do not combine any intrinsic.
8913     default:
8914       return SDValue();
8915     case Intrinsic::riscv_vcpop:
8916     case Intrinsic::riscv_vcpop_mask:
8917     case Intrinsic::riscv_vfirst:
8918     case Intrinsic::riscv_vfirst_mask: {
8919       SDValue VL = N->getOperand(2);
8920       if (IntNo == Intrinsic::riscv_vcpop_mask ||
8921           IntNo == Intrinsic::riscv_vfirst_mask)
8922         VL = N->getOperand(3);
8923       if (!isNullConstant(VL))
8924         return SDValue();
8925       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
8926       SDLoc DL(N);
8927       EVT VT = N->getValueType(0);
8928       if (IntNo == Intrinsic::riscv_vfirst ||
8929           IntNo == Intrinsic::riscv_vfirst_mask)
8930         return DAG.getConstant(-1, DL, VT);
8931       return DAG.getConstant(0, DL, VT);
8932     }
8933     }
8934   }
8935   }
8936 
8937   return SDValue();
8938 }
8939 
8940 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8941     const SDNode *N, CombineLevel Level) const {
8942   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8943   // materialised in fewer instructions than `(OP _, c1)`:
8944   //
8945   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8946   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8947   SDValue N0 = N->getOperand(0);
8948   EVT Ty = N0.getValueType();
8949   if (Ty.isScalarInteger() &&
8950       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8951     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8952     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8953     if (C1 && C2) {
8954       const APInt &C1Int = C1->getAPIntValue();
8955       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8956 
8957       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8958       // and the combine should happen, to potentially allow further combines
8959       // later.
8960       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8961           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8962         return true;
8963 
8964       // We can materialise `c1` in an add immediate, so it's "free", and the
8965       // combine should be prevented.
8966       if (C1Int.getMinSignedBits() <= 64 &&
8967           isLegalAddImmediate(C1Int.getSExtValue()))
8968         return false;
8969 
8970       // Neither constant will fit into an immediate, so find materialisation
8971       // costs.
8972       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8973                                               Subtarget.getFeatureBits(),
8974                                               /*CompressionCost*/true);
8975       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8976           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8977           /*CompressionCost*/true);
8978 
8979       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8980       // combine should be prevented.
8981       if (C1Cost < ShiftedC1Cost)
8982         return false;
8983     }
8984   }
8985   return true;
8986 }
8987 
8988 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8989     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8990     TargetLoweringOpt &TLO) const {
8991   // Delay this optimization as late as possible.
8992   if (!TLO.LegalOps)
8993     return false;
8994 
8995   EVT VT = Op.getValueType();
8996   if (VT.isVector())
8997     return false;
8998 
8999   // Only handle AND for now.
9000   if (Op.getOpcode() != ISD::AND)
9001     return false;
9002 
9003   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9004   if (!C)
9005     return false;
9006 
9007   const APInt &Mask = C->getAPIntValue();
9008 
9009   // Clear all non-demanded bits initially.
9010   APInt ShrunkMask = Mask & DemandedBits;
9011 
9012   // Try to make a smaller immediate by setting undemanded bits.
9013 
9014   APInt ExpandedMask = Mask | ~DemandedBits;
9015 
9016   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
9017     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
9018   };
9019   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
9020     if (NewMask == Mask)
9021       return true;
9022     SDLoc DL(Op);
9023     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
9024     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
9025     return TLO.CombineTo(Op, NewOp);
9026   };
9027 
9028   // If the shrunk mask fits in sign extended 12 bits, let the target
9029   // independent code apply it.
9030   if (ShrunkMask.isSignedIntN(12))
9031     return false;
9032 
9033   // Preserve (and X, 0xffff) when zext.h is supported.
9034   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
9035     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
9036     if (IsLegalMask(NewMask))
9037       return UseMask(NewMask);
9038   }
9039 
9040   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
9041   if (VT == MVT::i64) {
9042     APInt NewMask = APInt(64, 0xffffffff);
9043     if (IsLegalMask(NewMask))
9044       return UseMask(NewMask);
9045   }
9046 
9047   // For the remaining optimizations, we need to be able to make a negative
9048   // number through a combination of mask and undemanded bits.
9049   if (!ExpandedMask.isNegative())
9050     return false;
9051 
9052   // What is the fewest number of bits we need to represent the negative number.
9053   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
9054 
9055   // Try to make a 12 bit negative immediate. If that fails try to make a 32
9056   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
9057   APInt NewMask = ShrunkMask;
9058   if (MinSignedBits <= 12)
9059     NewMask.setBitsFrom(11);
9060   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
9061     NewMask.setBitsFrom(31);
9062   else
9063     return false;
9064 
9065   // Check that our new mask is a subset of the demanded mask.
9066   assert(IsLegalMask(NewMask));
9067   return UseMask(NewMask);
9068 }
9069 
9070 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
9071   static const uint64_t GREVMasks[] = {
9072       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
9073       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
9074 
9075   for (unsigned Stage = 0; Stage != 6; ++Stage) {
9076     unsigned Shift = 1 << Stage;
9077     if (ShAmt & Shift) {
9078       uint64_t Mask = GREVMasks[Stage];
9079       uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
9080       if (IsGORC)
9081         Res |= x;
9082       x = Res;
9083     }
9084   }
9085 
9086   return x;
9087 }
9088 
9089 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9090                                                         KnownBits &Known,
9091                                                         const APInt &DemandedElts,
9092                                                         const SelectionDAG &DAG,
9093                                                         unsigned Depth) const {
9094   unsigned BitWidth = Known.getBitWidth();
9095   unsigned Opc = Op.getOpcode();
9096   assert((Opc >= ISD::BUILTIN_OP_END ||
9097           Opc == ISD::INTRINSIC_WO_CHAIN ||
9098           Opc == ISD::INTRINSIC_W_CHAIN ||
9099           Opc == ISD::INTRINSIC_VOID) &&
9100          "Should use MaskedValueIsZero if you don't know whether Op"
9101          " is a target node!");
9102 
9103   Known.resetAll();
9104   switch (Opc) {
9105   default: break;
9106   case RISCVISD::SELECT_CC: {
9107     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
9108     // If we don't know any bits, early out.
9109     if (Known.isUnknown())
9110       break;
9111     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
9112 
9113     // Only known if known in both the LHS and RHS.
9114     Known = KnownBits::commonBits(Known, Known2);
9115     break;
9116   }
9117   case RISCVISD::REMUW: {
9118     KnownBits Known2;
9119     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9120     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9121     // We only care about the lower 32 bits.
9122     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
9123     // Restore the original width by sign extending.
9124     Known = Known.sext(BitWidth);
9125     break;
9126   }
9127   case RISCVISD::DIVUW: {
9128     KnownBits Known2;
9129     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9130     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9131     // We only care about the lower 32 bits.
9132     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
9133     // Restore the original width by sign extending.
9134     Known = Known.sext(BitWidth);
9135     break;
9136   }
9137   case RISCVISD::CTZW: {
9138     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9139     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
9140     unsigned LowBits = Log2_32(PossibleTZ) + 1;
9141     Known.Zero.setBitsFrom(LowBits);
9142     break;
9143   }
9144   case RISCVISD::CLZW: {
9145     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9146     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
9147     unsigned LowBits = Log2_32(PossibleLZ) + 1;
9148     Known.Zero.setBitsFrom(LowBits);
9149     break;
9150   }
9151   case RISCVISD::GREV:
9152   case RISCVISD::GORC: {
9153     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9154       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9155       unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1);
9156       bool IsGORC = Op.getOpcode() == RISCVISD::GORC;
9157       // To compute zeros, we need to invert the value and invert it back after.
9158       Known.Zero =
9159           ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC);
9160       Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC);
9161     }
9162     break;
9163   }
9164   case RISCVISD::READ_VLENB: {
9165     // If we know the minimum VLen from Zvl extensions, we can use that to
9166     // determine the trailing zeros of VLENB.
9167     // FIXME: Limit to 128 bit vectors until we have more testing.
9168     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
9169     if (MinVLenB > 0)
9170       Known.Zero.setLowBits(Log2_32(MinVLenB));
9171     // We assume VLENB is no more than 65536 / 8 bytes.
9172     Known.Zero.setBitsFrom(14);
9173     break;
9174   }
9175   case ISD::INTRINSIC_W_CHAIN:
9176   case ISD::INTRINSIC_WO_CHAIN: {
9177     unsigned IntNo =
9178         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9179     switch (IntNo) {
9180     default:
9181       // We can't do anything for most intrinsics.
9182       break;
9183     case Intrinsic::riscv_vsetvli:
9184     case Intrinsic::riscv_vsetvlimax:
9185     case Intrinsic::riscv_vsetvli_opt:
9186     case Intrinsic::riscv_vsetvlimax_opt:
9187       // Assume that VL output is positive and would fit in an int32_t.
9188       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9189       if (BitWidth >= 32)
9190         Known.Zero.setBitsFrom(31);
9191       break;
9192     }
9193     break;
9194   }
9195   }
9196 }
9197 
9198 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9199     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9200     unsigned Depth) const {
9201   switch (Op.getOpcode()) {
9202   default:
9203     break;
9204   case RISCVISD::SELECT_CC: {
9205     unsigned Tmp =
9206         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9207     if (Tmp == 1) return 1;  // Early out.
9208     unsigned Tmp2 =
9209         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9210     return std::min(Tmp, Tmp2);
9211   }
9212   case RISCVISD::SLLW:
9213   case RISCVISD::SRAW:
9214   case RISCVISD::SRLW:
9215   case RISCVISD::DIVW:
9216   case RISCVISD::DIVUW:
9217   case RISCVISD::REMUW:
9218   case RISCVISD::ROLW:
9219   case RISCVISD::RORW:
9220   case RISCVISD::GREVW:
9221   case RISCVISD::GORCW:
9222   case RISCVISD::FSLW:
9223   case RISCVISD::FSRW:
9224   case RISCVISD::SHFLW:
9225   case RISCVISD::UNSHFLW:
9226   case RISCVISD::BCOMPRESSW:
9227   case RISCVISD::BDECOMPRESSW:
9228   case RISCVISD::BFPW:
9229   case RISCVISD::FCVT_W_RV64:
9230   case RISCVISD::FCVT_WU_RV64:
9231   case RISCVISD::STRICT_FCVT_W_RV64:
9232   case RISCVISD::STRICT_FCVT_WU_RV64:
9233     // TODO: As the result is sign-extended, this is conservatively correct. A
9234     // more precise answer could be calculated for SRAW depending on known
9235     // bits in the shift amount.
9236     return 33;
9237   case RISCVISD::SHFL:
9238   case RISCVISD::UNSHFL: {
9239     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9240     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9241     // will stay within the upper 32 bits. If there were more than 32 sign bits
9242     // before there will be at least 33 sign bits after.
9243     if (Op.getValueType() == MVT::i64 &&
9244         isa<ConstantSDNode>(Op.getOperand(1)) &&
9245         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9246       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9247       if (Tmp > 32)
9248         return 33;
9249     }
9250     break;
9251   }
9252   case RISCVISD::VMV_X_S: {
9253     // The number of sign bits of the scalar result is computed by obtaining the
9254     // element type of the input vector operand, subtracting its width from the
9255     // XLEN, and then adding one (sign bit within the element type). If the
9256     // element type is wider than XLen, the least-significant XLEN bits are
9257     // taken.
9258     unsigned XLen = Subtarget.getXLen();
9259     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9260     if (EltBits <= XLen)
9261       return XLen - EltBits + 1;
9262     break;
9263   }
9264   }
9265 
9266   return 1;
9267 }
9268 
9269 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9270                                                   MachineBasicBlock *BB) {
9271   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9272 
9273   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9274   // Should the count have wrapped while it was being read, we need to try
9275   // again.
9276   // ...
9277   // read:
9278   // rdcycleh x3 # load high word of cycle
9279   // rdcycle  x2 # load low word of cycle
9280   // rdcycleh x4 # load high word of cycle
9281   // bne x3, x4, read # check if high word reads match, otherwise try again
9282   // ...
9283 
9284   MachineFunction &MF = *BB->getParent();
9285   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9286   MachineFunction::iterator It = ++BB->getIterator();
9287 
9288   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9289   MF.insert(It, LoopMBB);
9290 
9291   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9292   MF.insert(It, DoneMBB);
9293 
9294   // Transfer the remainder of BB and its successor edges to DoneMBB.
9295   DoneMBB->splice(DoneMBB->begin(), BB,
9296                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9297   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9298 
9299   BB->addSuccessor(LoopMBB);
9300 
9301   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9302   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9303   Register LoReg = MI.getOperand(0).getReg();
9304   Register HiReg = MI.getOperand(1).getReg();
9305   DebugLoc DL = MI.getDebugLoc();
9306 
9307   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9308   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9309       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9310       .addReg(RISCV::X0);
9311   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9312       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9313       .addReg(RISCV::X0);
9314   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9315       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9316       .addReg(RISCV::X0);
9317 
9318   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9319       .addReg(HiReg)
9320       .addReg(ReadAgainReg)
9321       .addMBB(LoopMBB);
9322 
9323   LoopMBB->addSuccessor(LoopMBB);
9324   LoopMBB->addSuccessor(DoneMBB);
9325 
9326   MI.eraseFromParent();
9327 
9328   return DoneMBB;
9329 }
9330 
9331 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9332                                              MachineBasicBlock *BB) {
9333   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9334 
9335   MachineFunction &MF = *BB->getParent();
9336   DebugLoc DL = MI.getDebugLoc();
9337   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9338   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9339   Register LoReg = MI.getOperand(0).getReg();
9340   Register HiReg = MI.getOperand(1).getReg();
9341   Register SrcReg = MI.getOperand(2).getReg();
9342   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9343   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9344 
9345   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9346                           RI);
9347   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9348   MachineMemOperand *MMOLo =
9349       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9350   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9351       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9352   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9353       .addFrameIndex(FI)
9354       .addImm(0)
9355       .addMemOperand(MMOLo);
9356   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9357       .addFrameIndex(FI)
9358       .addImm(4)
9359       .addMemOperand(MMOHi);
9360   MI.eraseFromParent(); // The pseudo instruction is gone now.
9361   return BB;
9362 }
9363 
9364 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9365                                                  MachineBasicBlock *BB) {
9366   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9367          "Unexpected instruction");
9368 
9369   MachineFunction &MF = *BB->getParent();
9370   DebugLoc DL = MI.getDebugLoc();
9371   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9372   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9373   Register DstReg = MI.getOperand(0).getReg();
9374   Register LoReg = MI.getOperand(1).getReg();
9375   Register HiReg = MI.getOperand(2).getReg();
9376   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9377   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9378 
9379   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9380   MachineMemOperand *MMOLo =
9381       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9382   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9383       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9384   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9385       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9386       .addFrameIndex(FI)
9387       .addImm(0)
9388       .addMemOperand(MMOLo);
9389   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9390       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9391       .addFrameIndex(FI)
9392       .addImm(4)
9393       .addMemOperand(MMOHi);
9394   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9395   MI.eraseFromParent(); // The pseudo instruction is gone now.
9396   return BB;
9397 }
9398 
9399 static bool isSelectPseudo(MachineInstr &MI) {
9400   switch (MI.getOpcode()) {
9401   default:
9402     return false;
9403   case RISCV::Select_GPR_Using_CC_GPR:
9404   case RISCV::Select_FPR16_Using_CC_GPR:
9405   case RISCV::Select_FPR32_Using_CC_GPR:
9406   case RISCV::Select_FPR64_Using_CC_GPR:
9407     return true;
9408   }
9409 }
9410 
9411 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9412                                         unsigned RelOpcode, unsigned EqOpcode,
9413                                         const RISCVSubtarget &Subtarget) {
9414   DebugLoc DL = MI.getDebugLoc();
9415   Register DstReg = MI.getOperand(0).getReg();
9416   Register Src1Reg = MI.getOperand(1).getReg();
9417   Register Src2Reg = MI.getOperand(2).getReg();
9418   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9419   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9420   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9421 
9422   // Save the current FFLAGS.
9423   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9424 
9425   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9426                  .addReg(Src1Reg)
9427                  .addReg(Src2Reg);
9428   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9429     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9430 
9431   // Restore the FFLAGS.
9432   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9433       .addReg(SavedFFlags, RegState::Kill);
9434 
9435   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9436   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9437                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9438                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9439   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9440     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9441 
9442   // Erase the pseudoinstruction.
9443   MI.eraseFromParent();
9444   return BB;
9445 }
9446 
9447 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9448                                            MachineBasicBlock *BB,
9449                                            const RISCVSubtarget &Subtarget) {
9450   // To "insert" Select_* instructions, we actually have to insert the triangle
9451   // control-flow pattern.  The incoming instructions know the destination vreg
9452   // to set, the condition code register to branch on, the true/false values to
9453   // select between, and the condcode to use to select the appropriate branch.
9454   //
9455   // We produce the following control flow:
9456   //     HeadMBB
9457   //     |  \
9458   //     |  IfFalseMBB
9459   //     | /
9460   //    TailMBB
9461   //
9462   // When we find a sequence of selects we attempt to optimize their emission
9463   // by sharing the control flow. Currently we only handle cases where we have
9464   // multiple selects with the exact same condition (same LHS, RHS and CC).
9465   // The selects may be interleaved with other instructions if the other
9466   // instructions meet some requirements we deem safe:
9467   // - They are debug instructions. Otherwise,
9468   // - They do not have side-effects, do not access memory and their inputs do
9469   //   not depend on the results of the select pseudo-instructions.
9470   // The TrueV/FalseV operands of the selects cannot depend on the result of
9471   // previous selects in the sequence.
9472   // These conditions could be further relaxed. See the X86 target for a
9473   // related approach and more information.
9474   Register LHS = MI.getOperand(1).getReg();
9475   Register RHS = MI.getOperand(2).getReg();
9476   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9477 
9478   SmallVector<MachineInstr *, 4> SelectDebugValues;
9479   SmallSet<Register, 4> SelectDests;
9480   SelectDests.insert(MI.getOperand(0).getReg());
9481 
9482   MachineInstr *LastSelectPseudo = &MI;
9483 
9484   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9485        SequenceMBBI != E; ++SequenceMBBI) {
9486     if (SequenceMBBI->isDebugInstr())
9487       continue;
9488     else if (isSelectPseudo(*SequenceMBBI)) {
9489       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9490           SequenceMBBI->getOperand(2).getReg() != RHS ||
9491           SequenceMBBI->getOperand(3).getImm() != CC ||
9492           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9493           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9494         break;
9495       LastSelectPseudo = &*SequenceMBBI;
9496       SequenceMBBI->collectDebugValues(SelectDebugValues);
9497       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9498     } else {
9499       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9500           SequenceMBBI->mayLoadOrStore())
9501         break;
9502       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9503             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9504           }))
9505         break;
9506     }
9507   }
9508 
9509   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9510   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9511   DebugLoc DL = MI.getDebugLoc();
9512   MachineFunction::iterator I = ++BB->getIterator();
9513 
9514   MachineBasicBlock *HeadMBB = BB;
9515   MachineFunction *F = BB->getParent();
9516   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9517   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9518 
9519   F->insert(I, IfFalseMBB);
9520   F->insert(I, TailMBB);
9521 
9522   // Transfer debug instructions associated with the selects to TailMBB.
9523   for (MachineInstr *DebugInstr : SelectDebugValues) {
9524     TailMBB->push_back(DebugInstr->removeFromParent());
9525   }
9526 
9527   // Move all instructions after the sequence to TailMBB.
9528   TailMBB->splice(TailMBB->end(), HeadMBB,
9529                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9530   // Update machine-CFG edges by transferring all successors of the current
9531   // block to the new block which will contain the Phi nodes for the selects.
9532   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9533   // Set the successors for HeadMBB.
9534   HeadMBB->addSuccessor(IfFalseMBB);
9535   HeadMBB->addSuccessor(TailMBB);
9536 
9537   // Insert appropriate branch.
9538   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9539     .addReg(LHS)
9540     .addReg(RHS)
9541     .addMBB(TailMBB);
9542 
9543   // IfFalseMBB just falls through to TailMBB.
9544   IfFalseMBB->addSuccessor(TailMBB);
9545 
9546   // Create PHIs for all of the select pseudo-instructions.
9547   auto SelectMBBI = MI.getIterator();
9548   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9549   auto InsertionPoint = TailMBB->begin();
9550   while (SelectMBBI != SelectEnd) {
9551     auto Next = std::next(SelectMBBI);
9552     if (isSelectPseudo(*SelectMBBI)) {
9553       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9554       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9555               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9556           .addReg(SelectMBBI->getOperand(4).getReg())
9557           .addMBB(HeadMBB)
9558           .addReg(SelectMBBI->getOperand(5).getReg())
9559           .addMBB(IfFalseMBB);
9560       SelectMBBI->eraseFromParent();
9561     }
9562     SelectMBBI = Next;
9563   }
9564 
9565   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9566   return TailMBB;
9567 }
9568 
9569 MachineBasicBlock *
9570 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9571                                                  MachineBasicBlock *BB) const {
9572   switch (MI.getOpcode()) {
9573   default:
9574     llvm_unreachable("Unexpected instr type to insert");
9575   case RISCV::ReadCycleWide:
9576     assert(!Subtarget.is64Bit() &&
9577            "ReadCycleWrite is only to be used on riscv32");
9578     return emitReadCycleWidePseudo(MI, BB);
9579   case RISCV::Select_GPR_Using_CC_GPR:
9580   case RISCV::Select_FPR16_Using_CC_GPR:
9581   case RISCV::Select_FPR32_Using_CC_GPR:
9582   case RISCV::Select_FPR64_Using_CC_GPR:
9583     return emitSelectPseudo(MI, BB, Subtarget);
9584   case RISCV::BuildPairF64Pseudo:
9585     return emitBuildPairF64Pseudo(MI, BB);
9586   case RISCV::SplitF64Pseudo:
9587     return emitSplitF64Pseudo(MI, BB);
9588   case RISCV::PseudoQuietFLE_H:
9589     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9590   case RISCV::PseudoQuietFLT_H:
9591     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9592   case RISCV::PseudoQuietFLE_S:
9593     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9594   case RISCV::PseudoQuietFLT_S:
9595     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9596   case RISCV::PseudoQuietFLE_D:
9597     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9598   case RISCV::PseudoQuietFLT_D:
9599     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9600   }
9601 }
9602 
9603 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9604                                                         SDNode *Node) const {
9605   // Add FRM dependency to any instructions with dynamic rounding mode.
9606   unsigned Opc = MI.getOpcode();
9607   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9608   if (Idx < 0)
9609     return;
9610   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9611     return;
9612   // If the instruction already reads FRM, don't add another read.
9613   if (MI.readsRegister(RISCV::FRM))
9614     return;
9615   MI.addOperand(
9616       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9617 }
9618 
9619 // Calling Convention Implementation.
9620 // The expectations for frontend ABI lowering vary from target to target.
9621 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9622 // details, but this is a longer term goal. For now, we simply try to keep the
9623 // role of the frontend as simple and well-defined as possible. The rules can
9624 // be summarised as:
9625 // * Never split up large scalar arguments. We handle them here.
9626 // * If a hardfloat calling convention is being used, and the struct may be
9627 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9628 // available, then pass as two separate arguments. If either the GPRs or FPRs
9629 // are exhausted, then pass according to the rule below.
9630 // * If a struct could never be passed in registers or directly in a stack
9631 // slot (as it is larger than 2*XLEN and the floating point rules don't
9632 // apply), then pass it using a pointer with the byval attribute.
9633 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9634 // word-sized array or a 2*XLEN scalar (depending on alignment).
9635 // * The frontend can determine whether a struct is returned by reference or
9636 // not based on its size and fields. If it will be returned by reference, the
9637 // frontend must modify the prototype so a pointer with the sret annotation is
9638 // passed as the first argument. This is not necessary for large scalar
9639 // returns.
9640 // * Struct return values and varargs should be coerced to structs containing
9641 // register-size fields in the same situations they would be for fixed
9642 // arguments.
9643 
9644 static const MCPhysReg ArgGPRs[] = {
9645   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9646   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9647 };
9648 static const MCPhysReg ArgFPR16s[] = {
9649   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9650   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9651 };
9652 static const MCPhysReg ArgFPR32s[] = {
9653   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9654   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9655 };
9656 static const MCPhysReg ArgFPR64s[] = {
9657   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9658   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9659 };
9660 // This is an interim calling convention and it may be changed in the future.
9661 static const MCPhysReg ArgVRs[] = {
9662     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9663     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9664     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9665 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9666                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9667                                      RISCV::V20M2, RISCV::V22M2};
9668 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9669                                      RISCV::V20M4};
9670 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9671 
9672 // Pass a 2*XLEN argument that has been split into two XLEN values through
9673 // registers or the stack as necessary.
9674 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9675                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9676                                 MVT ValVT2, MVT LocVT2,
9677                                 ISD::ArgFlagsTy ArgFlags2) {
9678   unsigned XLenInBytes = XLen / 8;
9679   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9680     // At least one half can be passed via register.
9681     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9682                                      VA1.getLocVT(), CCValAssign::Full));
9683   } else {
9684     // Both halves must be passed on the stack, with proper alignment.
9685     Align StackAlign =
9686         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9687     State.addLoc(
9688         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9689                             State.AllocateStack(XLenInBytes, StackAlign),
9690                             VA1.getLocVT(), CCValAssign::Full));
9691     State.addLoc(CCValAssign::getMem(
9692         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9693         LocVT2, CCValAssign::Full));
9694     return false;
9695   }
9696 
9697   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9698     // The second half can also be passed via register.
9699     State.addLoc(
9700         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9701   } else {
9702     // The second half is passed via the stack, without additional alignment.
9703     State.addLoc(CCValAssign::getMem(
9704         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9705         LocVT2, CCValAssign::Full));
9706   }
9707 
9708   return false;
9709 }
9710 
9711 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9712                                Optional<unsigned> FirstMaskArgument,
9713                                CCState &State, const RISCVTargetLowering &TLI) {
9714   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9715   if (RC == &RISCV::VRRegClass) {
9716     // Assign the first mask argument to V0.
9717     // This is an interim calling convention and it may be changed in the
9718     // future.
9719     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
9720       return State.AllocateReg(RISCV::V0);
9721     return State.AllocateReg(ArgVRs);
9722   }
9723   if (RC == &RISCV::VRM2RegClass)
9724     return State.AllocateReg(ArgVRM2s);
9725   if (RC == &RISCV::VRM4RegClass)
9726     return State.AllocateReg(ArgVRM4s);
9727   if (RC == &RISCV::VRM8RegClass)
9728     return State.AllocateReg(ArgVRM8s);
9729   llvm_unreachable("Unhandled register class for ValueType");
9730 }
9731 
9732 // Implements the RISC-V calling convention. Returns true upon failure.
9733 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9734                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9735                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9736                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9737                      Optional<unsigned> FirstMaskArgument) {
9738   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9739   assert(XLen == 32 || XLen == 64);
9740   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9741 
9742   // Any return value split in to more than two values can't be returned
9743   // directly. Vectors are returned via the available vector registers.
9744   if (!LocVT.isVector() && IsRet && ValNo > 1)
9745     return true;
9746 
9747   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9748   // variadic argument, or if no F16/F32 argument registers are available.
9749   bool UseGPRForF16_F32 = true;
9750   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9751   // variadic argument, or if no F64 argument registers are available.
9752   bool UseGPRForF64 = true;
9753 
9754   switch (ABI) {
9755   default:
9756     llvm_unreachable("Unexpected ABI");
9757   case RISCVABI::ABI_ILP32:
9758   case RISCVABI::ABI_LP64:
9759     break;
9760   case RISCVABI::ABI_ILP32F:
9761   case RISCVABI::ABI_LP64F:
9762     UseGPRForF16_F32 = !IsFixed;
9763     break;
9764   case RISCVABI::ABI_ILP32D:
9765   case RISCVABI::ABI_LP64D:
9766     UseGPRForF16_F32 = !IsFixed;
9767     UseGPRForF64 = !IsFixed;
9768     break;
9769   }
9770 
9771   // FPR16, FPR32, and FPR64 alias each other.
9772   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9773     UseGPRForF16_F32 = true;
9774     UseGPRForF64 = true;
9775   }
9776 
9777   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9778   // similar local variables rather than directly checking against the target
9779   // ABI.
9780 
9781   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9782     LocVT = XLenVT;
9783     LocInfo = CCValAssign::BCvt;
9784   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9785     LocVT = MVT::i64;
9786     LocInfo = CCValAssign::BCvt;
9787   }
9788 
9789   // If this is a variadic argument, the RISC-V calling convention requires
9790   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9791   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9792   // be used regardless of whether the original argument was split during
9793   // legalisation or not. The argument will not be passed by registers if the
9794   // original type is larger than 2*XLEN, so the register alignment rule does
9795   // not apply.
9796   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9797   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9798       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9799     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9800     // Skip 'odd' register if necessary.
9801     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9802       State.AllocateReg(ArgGPRs);
9803   }
9804 
9805   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9806   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9807       State.getPendingArgFlags();
9808 
9809   assert(PendingLocs.size() == PendingArgFlags.size() &&
9810          "PendingLocs and PendingArgFlags out of sync");
9811 
9812   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9813   // registers are exhausted.
9814   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9815     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9816            "Can't lower f64 if it is split");
9817     // Depending on available argument GPRS, f64 may be passed in a pair of
9818     // GPRs, split between a GPR and the stack, or passed completely on the
9819     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9820     // cases.
9821     Register Reg = State.AllocateReg(ArgGPRs);
9822     LocVT = MVT::i32;
9823     if (!Reg) {
9824       unsigned StackOffset = State.AllocateStack(8, Align(8));
9825       State.addLoc(
9826           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9827       return false;
9828     }
9829     if (!State.AllocateReg(ArgGPRs))
9830       State.AllocateStack(4, Align(4));
9831     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9832     return false;
9833   }
9834 
9835   // Fixed-length vectors are located in the corresponding scalable-vector
9836   // container types.
9837   if (ValVT.isFixedLengthVector())
9838     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9839 
9840   // Split arguments might be passed indirectly, so keep track of the pending
9841   // values. Split vectors are passed via a mix of registers and indirectly, so
9842   // treat them as we would any other argument.
9843   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9844     LocVT = XLenVT;
9845     LocInfo = CCValAssign::Indirect;
9846     PendingLocs.push_back(
9847         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9848     PendingArgFlags.push_back(ArgFlags);
9849     if (!ArgFlags.isSplitEnd()) {
9850       return false;
9851     }
9852   }
9853 
9854   // If the split argument only had two elements, it should be passed directly
9855   // in registers or on the stack.
9856   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9857       PendingLocs.size() <= 2) {
9858     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9859     // Apply the normal calling convention rules to the first half of the
9860     // split argument.
9861     CCValAssign VA = PendingLocs[0];
9862     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9863     PendingLocs.clear();
9864     PendingArgFlags.clear();
9865     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9866                                ArgFlags);
9867   }
9868 
9869   // Allocate to a register if possible, or else a stack slot.
9870   Register Reg;
9871   unsigned StoreSizeBytes = XLen / 8;
9872   Align StackAlign = Align(XLen / 8);
9873 
9874   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9875     Reg = State.AllocateReg(ArgFPR16s);
9876   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9877     Reg = State.AllocateReg(ArgFPR32s);
9878   else if (ValVT == MVT::f64 && !UseGPRForF64)
9879     Reg = State.AllocateReg(ArgFPR64s);
9880   else if (ValVT.isVector()) {
9881     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9882     if (!Reg) {
9883       // For return values, the vector must be passed fully via registers or
9884       // via the stack.
9885       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9886       // but we're using all of them.
9887       if (IsRet)
9888         return true;
9889       // Try using a GPR to pass the address
9890       if ((Reg = State.AllocateReg(ArgGPRs))) {
9891         LocVT = XLenVT;
9892         LocInfo = CCValAssign::Indirect;
9893       } else if (ValVT.isScalableVector()) {
9894         LocVT = XLenVT;
9895         LocInfo = CCValAssign::Indirect;
9896       } else {
9897         // Pass fixed-length vectors on the stack.
9898         LocVT = ValVT;
9899         StoreSizeBytes = ValVT.getStoreSize();
9900         // Align vectors to their element sizes, being careful for vXi1
9901         // vectors.
9902         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9903       }
9904     }
9905   } else {
9906     Reg = State.AllocateReg(ArgGPRs);
9907   }
9908 
9909   unsigned StackOffset =
9910       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9911 
9912   // If we reach this point and PendingLocs is non-empty, we must be at the
9913   // end of a split argument that must be passed indirectly.
9914   if (!PendingLocs.empty()) {
9915     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9916     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9917 
9918     for (auto &It : PendingLocs) {
9919       if (Reg)
9920         It.convertToReg(Reg);
9921       else
9922         It.convertToMem(StackOffset);
9923       State.addLoc(It);
9924     }
9925     PendingLocs.clear();
9926     PendingArgFlags.clear();
9927     return false;
9928   }
9929 
9930   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9931           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9932          "Expected an XLenVT or vector types at this stage");
9933 
9934   if (Reg) {
9935     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9936     return false;
9937   }
9938 
9939   // When a floating-point value is passed on the stack, no bit-conversion is
9940   // needed.
9941   if (ValVT.isFloatingPoint()) {
9942     LocVT = ValVT;
9943     LocInfo = CCValAssign::Full;
9944   }
9945   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9946   return false;
9947 }
9948 
9949 template <typename ArgTy>
9950 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9951   for (const auto &ArgIdx : enumerate(Args)) {
9952     MVT ArgVT = ArgIdx.value().VT;
9953     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9954       return ArgIdx.index();
9955   }
9956   return None;
9957 }
9958 
9959 void RISCVTargetLowering::analyzeInputArgs(
9960     MachineFunction &MF, CCState &CCInfo,
9961     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9962     RISCVCCAssignFn Fn) const {
9963   unsigned NumArgs = Ins.size();
9964   FunctionType *FType = MF.getFunction().getFunctionType();
9965 
9966   Optional<unsigned> FirstMaskArgument;
9967   if (Subtarget.hasVInstructions())
9968     FirstMaskArgument = preAssignMask(Ins);
9969 
9970   for (unsigned i = 0; i != NumArgs; ++i) {
9971     MVT ArgVT = Ins[i].VT;
9972     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9973 
9974     Type *ArgTy = nullptr;
9975     if (IsRet)
9976       ArgTy = FType->getReturnType();
9977     else if (Ins[i].isOrigArg())
9978       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9979 
9980     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9981     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9982            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9983            FirstMaskArgument)) {
9984       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9985                         << EVT(ArgVT).getEVTString() << '\n');
9986       llvm_unreachable(nullptr);
9987     }
9988   }
9989 }
9990 
9991 void RISCVTargetLowering::analyzeOutputArgs(
9992     MachineFunction &MF, CCState &CCInfo,
9993     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9994     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9995   unsigned NumArgs = Outs.size();
9996 
9997   Optional<unsigned> FirstMaskArgument;
9998   if (Subtarget.hasVInstructions())
9999     FirstMaskArgument = preAssignMask(Outs);
10000 
10001   for (unsigned i = 0; i != NumArgs; i++) {
10002     MVT ArgVT = Outs[i].VT;
10003     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10004     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
10005 
10006     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10007     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
10008            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
10009            FirstMaskArgument)) {
10010       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
10011                         << EVT(ArgVT).getEVTString() << "\n");
10012       llvm_unreachable(nullptr);
10013     }
10014   }
10015 }
10016 
10017 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
10018 // values.
10019 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
10020                                    const CCValAssign &VA, const SDLoc &DL,
10021                                    const RISCVSubtarget &Subtarget) {
10022   switch (VA.getLocInfo()) {
10023   default:
10024     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10025   case CCValAssign::Full:
10026     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
10027       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
10028     break;
10029   case CCValAssign::BCvt:
10030     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10031       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
10032     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10033       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
10034     else
10035       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
10036     break;
10037   }
10038   return Val;
10039 }
10040 
10041 // The caller is responsible for loading the full value if the argument is
10042 // passed with CCValAssign::Indirect.
10043 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
10044                                 const CCValAssign &VA, const SDLoc &DL,
10045                                 const RISCVTargetLowering &TLI) {
10046   MachineFunction &MF = DAG.getMachineFunction();
10047   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10048   EVT LocVT = VA.getLocVT();
10049   SDValue Val;
10050   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
10051   Register VReg = RegInfo.createVirtualRegister(RC);
10052   RegInfo.addLiveIn(VA.getLocReg(), VReg);
10053   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
10054 
10055   if (VA.getLocInfo() == CCValAssign::Indirect)
10056     return Val;
10057 
10058   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
10059 }
10060 
10061 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
10062                                    const CCValAssign &VA, const SDLoc &DL,
10063                                    const RISCVSubtarget &Subtarget) {
10064   EVT LocVT = VA.getLocVT();
10065 
10066   switch (VA.getLocInfo()) {
10067   default:
10068     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10069   case CCValAssign::Full:
10070     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
10071       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
10072     break;
10073   case CCValAssign::BCvt:
10074     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10075       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
10076     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10077       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
10078     else
10079       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
10080     break;
10081   }
10082   return Val;
10083 }
10084 
10085 // The caller is responsible for loading the full value if the argument is
10086 // passed with CCValAssign::Indirect.
10087 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
10088                                 const CCValAssign &VA, const SDLoc &DL) {
10089   MachineFunction &MF = DAG.getMachineFunction();
10090   MachineFrameInfo &MFI = MF.getFrameInfo();
10091   EVT LocVT = VA.getLocVT();
10092   EVT ValVT = VA.getValVT();
10093   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
10094   if (ValVT.isScalableVector()) {
10095     // When the value is a scalable vector, we save the pointer which points to
10096     // the scalable vector value in the stack. The ValVT will be the pointer
10097     // type, instead of the scalable vector type.
10098     ValVT = LocVT;
10099   }
10100   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
10101                                  /*IsImmutable=*/true);
10102   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
10103   SDValue Val;
10104 
10105   ISD::LoadExtType ExtType;
10106   switch (VA.getLocInfo()) {
10107   default:
10108     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10109   case CCValAssign::Full:
10110   case CCValAssign::Indirect:
10111   case CCValAssign::BCvt:
10112     ExtType = ISD::NON_EXTLOAD;
10113     break;
10114   }
10115   Val = DAG.getExtLoad(
10116       ExtType, DL, LocVT, Chain, FIN,
10117       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
10118   return Val;
10119 }
10120 
10121 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
10122                                        const CCValAssign &VA, const SDLoc &DL) {
10123   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
10124          "Unexpected VA");
10125   MachineFunction &MF = DAG.getMachineFunction();
10126   MachineFrameInfo &MFI = MF.getFrameInfo();
10127   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10128 
10129   if (VA.isMemLoc()) {
10130     // f64 is passed on the stack.
10131     int FI =
10132         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
10133     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10134     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
10135                        MachinePointerInfo::getFixedStack(MF, FI));
10136   }
10137 
10138   assert(VA.isRegLoc() && "Expected register VA assignment");
10139 
10140   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10141   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
10142   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
10143   SDValue Hi;
10144   if (VA.getLocReg() == RISCV::X17) {
10145     // Second half of f64 is passed on the stack.
10146     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
10147     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10148     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10149                      MachinePointerInfo::getFixedStack(MF, FI));
10150   } else {
10151     // Second half of f64 is passed in another GPR.
10152     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10153     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10154     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10155   }
10156   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10157 }
10158 
10159 // FastCC has less than 1% performance improvement for some particular
10160 // benchmark. But theoretically, it may has benenfit for some cases.
10161 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10162                             unsigned ValNo, MVT ValVT, MVT LocVT,
10163                             CCValAssign::LocInfo LocInfo,
10164                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10165                             bool IsFixed, bool IsRet, Type *OrigTy,
10166                             const RISCVTargetLowering &TLI,
10167                             Optional<unsigned> FirstMaskArgument) {
10168 
10169   // X5 and X6 might be used for save-restore libcall.
10170   static const MCPhysReg GPRList[] = {
10171       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10172       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10173       RISCV::X29, RISCV::X30, RISCV::X31};
10174 
10175   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10176     if (unsigned Reg = State.AllocateReg(GPRList)) {
10177       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10178       return false;
10179     }
10180   }
10181 
10182   if (LocVT == MVT::f16) {
10183     static const MCPhysReg FPR16List[] = {
10184         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10185         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10186         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10187         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10188     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10189       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10190       return false;
10191     }
10192   }
10193 
10194   if (LocVT == MVT::f32) {
10195     static const MCPhysReg FPR32List[] = {
10196         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10197         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10198         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10199         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10200     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10201       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10202       return false;
10203     }
10204   }
10205 
10206   if (LocVT == MVT::f64) {
10207     static const MCPhysReg FPR64List[] = {
10208         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10209         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10210         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10211         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10212     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10213       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10214       return false;
10215     }
10216   }
10217 
10218   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10219     unsigned Offset4 = State.AllocateStack(4, Align(4));
10220     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10221     return false;
10222   }
10223 
10224   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10225     unsigned Offset5 = State.AllocateStack(8, Align(8));
10226     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10227     return false;
10228   }
10229 
10230   if (LocVT.isVector()) {
10231     if (unsigned Reg =
10232             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10233       // Fixed-length vectors are located in the corresponding scalable-vector
10234       // container types.
10235       if (ValVT.isFixedLengthVector())
10236         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10237       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10238     } else {
10239       // Try and pass the address via a "fast" GPR.
10240       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10241         LocInfo = CCValAssign::Indirect;
10242         LocVT = TLI.getSubtarget().getXLenVT();
10243         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10244       } else if (ValVT.isFixedLengthVector()) {
10245         auto StackAlign =
10246             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10247         unsigned StackOffset =
10248             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10249         State.addLoc(
10250             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10251       } else {
10252         // Can't pass scalable vectors on the stack.
10253         return true;
10254       }
10255     }
10256 
10257     return false;
10258   }
10259 
10260   return true; // CC didn't match.
10261 }
10262 
10263 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10264                          CCValAssign::LocInfo LocInfo,
10265                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10266 
10267   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10268     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10269     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10270     static const MCPhysReg GPRList[] = {
10271         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10272         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10273     if (unsigned Reg = State.AllocateReg(GPRList)) {
10274       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10275       return false;
10276     }
10277   }
10278 
10279   if (LocVT == MVT::f32) {
10280     // Pass in STG registers: F1, ..., F6
10281     //                        fs0 ... fs5
10282     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10283                                           RISCV::F18_F, RISCV::F19_F,
10284                                           RISCV::F20_F, RISCV::F21_F};
10285     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10286       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10287       return false;
10288     }
10289   }
10290 
10291   if (LocVT == MVT::f64) {
10292     // Pass in STG registers: D1, ..., D6
10293     //                        fs6 ... fs11
10294     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10295                                           RISCV::F24_D, RISCV::F25_D,
10296                                           RISCV::F26_D, RISCV::F27_D};
10297     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10298       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10299       return false;
10300     }
10301   }
10302 
10303   report_fatal_error("No registers left in GHC calling convention");
10304   return true;
10305 }
10306 
10307 // Transform physical registers into virtual registers.
10308 SDValue RISCVTargetLowering::LowerFormalArguments(
10309     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10310     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10311     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10312 
10313   MachineFunction &MF = DAG.getMachineFunction();
10314 
10315   switch (CallConv) {
10316   default:
10317     report_fatal_error("Unsupported calling convention");
10318   case CallingConv::C:
10319   case CallingConv::Fast:
10320     break;
10321   case CallingConv::GHC:
10322     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10323         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10324       report_fatal_error(
10325         "GHC calling convention requires the F and D instruction set extensions");
10326   }
10327 
10328   const Function &Func = MF.getFunction();
10329   if (Func.hasFnAttribute("interrupt")) {
10330     if (!Func.arg_empty())
10331       report_fatal_error(
10332         "Functions with the interrupt attribute cannot have arguments!");
10333 
10334     StringRef Kind =
10335       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10336 
10337     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10338       report_fatal_error(
10339         "Function interrupt attribute argument not supported!");
10340   }
10341 
10342   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10343   MVT XLenVT = Subtarget.getXLenVT();
10344   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10345   // Used with vargs to acumulate store chains.
10346   std::vector<SDValue> OutChains;
10347 
10348   // Assign locations to all of the incoming arguments.
10349   SmallVector<CCValAssign, 16> ArgLocs;
10350   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10351 
10352   if (CallConv == CallingConv::GHC)
10353     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10354   else
10355     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10356                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10357                                                    : CC_RISCV);
10358 
10359   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10360     CCValAssign &VA = ArgLocs[i];
10361     SDValue ArgValue;
10362     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10363     // case.
10364     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10365       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10366     else if (VA.isRegLoc())
10367       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10368     else
10369       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10370 
10371     if (VA.getLocInfo() == CCValAssign::Indirect) {
10372       // If the original argument was split and passed by reference (e.g. i128
10373       // on RV32), we need to load all parts of it here (using the same
10374       // address). Vectors may be partly split to registers and partly to the
10375       // stack, in which case the base address is partly offset and subsequent
10376       // stores are relative to that.
10377       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10378                                    MachinePointerInfo()));
10379       unsigned ArgIndex = Ins[i].OrigArgIndex;
10380       unsigned ArgPartOffset = Ins[i].PartOffset;
10381       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10382       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10383         CCValAssign &PartVA = ArgLocs[i + 1];
10384         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10385         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10386         if (PartVA.getValVT().isScalableVector())
10387           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10388         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10389         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10390                                      MachinePointerInfo()));
10391         ++i;
10392       }
10393       continue;
10394     }
10395     InVals.push_back(ArgValue);
10396   }
10397 
10398   if (IsVarArg) {
10399     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10400     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10401     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10402     MachineFrameInfo &MFI = MF.getFrameInfo();
10403     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10404     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10405 
10406     // Offset of the first variable argument from stack pointer, and size of
10407     // the vararg save area. For now, the varargs save area is either zero or
10408     // large enough to hold a0-a7.
10409     int VaArgOffset, VarArgsSaveSize;
10410 
10411     // If all registers are allocated, then all varargs must be passed on the
10412     // stack and we don't need to save any argregs.
10413     if (ArgRegs.size() == Idx) {
10414       VaArgOffset = CCInfo.getNextStackOffset();
10415       VarArgsSaveSize = 0;
10416     } else {
10417       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10418       VaArgOffset = -VarArgsSaveSize;
10419     }
10420 
10421     // Record the frame index of the first variable argument
10422     // which is a value necessary to VASTART.
10423     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10424     RVFI->setVarArgsFrameIndex(FI);
10425 
10426     // If saving an odd number of registers then create an extra stack slot to
10427     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10428     // offsets to even-numbered registered remain 2*XLEN-aligned.
10429     if (Idx % 2) {
10430       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10431       VarArgsSaveSize += XLenInBytes;
10432     }
10433 
10434     // Copy the integer registers that may have been used for passing varargs
10435     // to the vararg save area.
10436     for (unsigned I = Idx; I < ArgRegs.size();
10437          ++I, VaArgOffset += XLenInBytes) {
10438       const Register Reg = RegInfo.createVirtualRegister(RC);
10439       RegInfo.addLiveIn(ArgRegs[I], Reg);
10440       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10441       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10442       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10443       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10444                                    MachinePointerInfo::getFixedStack(MF, FI));
10445       cast<StoreSDNode>(Store.getNode())
10446           ->getMemOperand()
10447           ->setValue((Value *)nullptr);
10448       OutChains.push_back(Store);
10449     }
10450     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10451   }
10452 
10453   // All stores are grouped in one node to allow the matching between
10454   // the size of Ins and InVals. This only happens for vararg functions.
10455   if (!OutChains.empty()) {
10456     OutChains.push_back(Chain);
10457     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10458   }
10459 
10460   return Chain;
10461 }
10462 
10463 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10464 /// for tail call optimization.
10465 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10466 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10467     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10468     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10469 
10470   auto &Callee = CLI.Callee;
10471   auto CalleeCC = CLI.CallConv;
10472   auto &Outs = CLI.Outs;
10473   auto &Caller = MF.getFunction();
10474   auto CallerCC = Caller.getCallingConv();
10475 
10476   // Exception-handling functions need a special set of instructions to
10477   // indicate a return to the hardware. Tail-calling another function would
10478   // probably break this.
10479   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10480   // should be expanded as new function attributes are introduced.
10481   if (Caller.hasFnAttribute("interrupt"))
10482     return false;
10483 
10484   // Do not tail call opt if the stack is used to pass parameters.
10485   if (CCInfo.getNextStackOffset() != 0)
10486     return false;
10487 
10488   // Do not tail call opt if any parameters need to be passed indirectly.
10489   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10490   // passed indirectly. So the address of the value will be passed in a
10491   // register, or if not available, then the address is put on the stack. In
10492   // order to pass indirectly, space on the stack often needs to be allocated
10493   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10494   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10495   // are passed CCValAssign::Indirect.
10496   for (auto &VA : ArgLocs)
10497     if (VA.getLocInfo() == CCValAssign::Indirect)
10498       return false;
10499 
10500   // Do not tail call opt if either caller or callee uses struct return
10501   // semantics.
10502   auto IsCallerStructRet = Caller.hasStructRetAttr();
10503   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10504   if (IsCallerStructRet || IsCalleeStructRet)
10505     return false;
10506 
10507   // Externally-defined functions with weak linkage should not be
10508   // tail-called. The behaviour of branch instructions in this situation (as
10509   // used for tail calls) is implementation-defined, so we cannot rely on the
10510   // linker replacing the tail call with a return.
10511   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10512     const GlobalValue *GV = G->getGlobal();
10513     if (GV->hasExternalWeakLinkage())
10514       return false;
10515   }
10516 
10517   // The callee has to preserve all registers the caller needs to preserve.
10518   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10519   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10520   if (CalleeCC != CallerCC) {
10521     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10522     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10523       return false;
10524   }
10525 
10526   // Byval parameters hand the function a pointer directly into the stack area
10527   // we want to reuse during a tail call. Working around this *is* possible
10528   // but less efficient and uglier in LowerCall.
10529   for (auto &Arg : Outs)
10530     if (Arg.Flags.isByVal())
10531       return false;
10532 
10533   return true;
10534 }
10535 
10536 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10537   return DAG.getDataLayout().getPrefTypeAlign(
10538       VT.getTypeForEVT(*DAG.getContext()));
10539 }
10540 
10541 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10542 // and output parameter nodes.
10543 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10544                                        SmallVectorImpl<SDValue> &InVals) const {
10545   SelectionDAG &DAG = CLI.DAG;
10546   SDLoc &DL = CLI.DL;
10547   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10548   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10549   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10550   SDValue Chain = CLI.Chain;
10551   SDValue Callee = CLI.Callee;
10552   bool &IsTailCall = CLI.IsTailCall;
10553   CallingConv::ID CallConv = CLI.CallConv;
10554   bool IsVarArg = CLI.IsVarArg;
10555   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10556   MVT XLenVT = Subtarget.getXLenVT();
10557 
10558   MachineFunction &MF = DAG.getMachineFunction();
10559 
10560   // Analyze the operands of the call, assigning locations to each operand.
10561   SmallVector<CCValAssign, 16> ArgLocs;
10562   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10563 
10564   if (CallConv == CallingConv::GHC)
10565     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10566   else
10567     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10568                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10569                                                     : CC_RISCV);
10570 
10571   // Check if it's really possible to do a tail call.
10572   if (IsTailCall)
10573     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10574 
10575   if (IsTailCall)
10576     ++NumTailCalls;
10577   else if (CLI.CB && CLI.CB->isMustTailCall())
10578     report_fatal_error("failed to perform tail call elimination on a call "
10579                        "site marked musttail");
10580 
10581   // Get a count of how many bytes are to be pushed on the stack.
10582   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10583 
10584   // Create local copies for byval args
10585   SmallVector<SDValue, 8> ByValArgs;
10586   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10587     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10588     if (!Flags.isByVal())
10589       continue;
10590 
10591     SDValue Arg = OutVals[i];
10592     unsigned Size = Flags.getByValSize();
10593     Align Alignment = Flags.getNonZeroByValAlign();
10594 
10595     int FI =
10596         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10597     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10598     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10599 
10600     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10601                           /*IsVolatile=*/false,
10602                           /*AlwaysInline=*/false, IsTailCall,
10603                           MachinePointerInfo(), MachinePointerInfo());
10604     ByValArgs.push_back(FIPtr);
10605   }
10606 
10607   if (!IsTailCall)
10608     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10609 
10610   // Copy argument values to their designated locations.
10611   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10612   SmallVector<SDValue, 8> MemOpChains;
10613   SDValue StackPtr;
10614   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10615     CCValAssign &VA = ArgLocs[i];
10616     SDValue ArgValue = OutVals[i];
10617     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10618 
10619     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10620     bool IsF64OnRV32DSoftABI =
10621         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10622     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10623       SDValue SplitF64 = DAG.getNode(
10624           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10625       SDValue Lo = SplitF64.getValue(0);
10626       SDValue Hi = SplitF64.getValue(1);
10627 
10628       Register RegLo = VA.getLocReg();
10629       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10630 
10631       if (RegLo == RISCV::X17) {
10632         // Second half of f64 is passed on the stack.
10633         // Work out the address of the stack slot.
10634         if (!StackPtr.getNode())
10635           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10636         // Emit the store.
10637         MemOpChains.push_back(
10638             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10639       } else {
10640         // Second half of f64 is passed in another GPR.
10641         assert(RegLo < RISCV::X31 && "Invalid register pair");
10642         Register RegHigh = RegLo + 1;
10643         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10644       }
10645       continue;
10646     }
10647 
10648     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10649     // as any other MemLoc.
10650 
10651     // Promote the value if needed.
10652     // For now, only handle fully promoted and indirect arguments.
10653     if (VA.getLocInfo() == CCValAssign::Indirect) {
10654       // Store the argument in a stack slot and pass its address.
10655       Align StackAlign =
10656           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10657                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10658       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10659       // If the original argument was split (e.g. i128), we need
10660       // to store the required parts of it here (and pass just one address).
10661       // Vectors may be partly split to registers and partly to the stack, in
10662       // which case the base address is partly offset and subsequent stores are
10663       // relative to that.
10664       unsigned ArgIndex = Outs[i].OrigArgIndex;
10665       unsigned ArgPartOffset = Outs[i].PartOffset;
10666       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10667       // Calculate the total size to store. We don't have access to what we're
10668       // actually storing other than performing the loop and collecting the
10669       // info.
10670       SmallVector<std::pair<SDValue, SDValue>> Parts;
10671       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10672         SDValue PartValue = OutVals[i + 1];
10673         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10674         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10675         EVT PartVT = PartValue.getValueType();
10676         if (PartVT.isScalableVector())
10677           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10678         StoredSize += PartVT.getStoreSize();
10679         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10680         Parts.push_back(std::make_pair(PartValue, Offset));
10681         ++i;
10682       }
10683       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10684       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10685       MemOpChains.push_back(
10686           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10687                        MachinePointerInfo::getFixedStack(MF, FI)));
10688       for (const auto &Part : Parts) {
10689         SDValue PartValue = Part.first;
10690         SDValue PartOffset = Part.second;
10691         SDValue Address =
10692             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10693         MemOpChains.push_back(
10694             DAG.getStore(Chain, DL, PartValue, Address,
10695                          MachinePointerInfo::getFixedStack(MF, FI)));
10696       }
10697       ArgValue = SpillSlot;
10698     } else {
10699       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10700     }
10701 
10702     // Use local copy if it is a byval arg.
10703     if (Flags.isByVal())
10704       ArgValue = ByValArgs[j++];
10705 
10706     if (VA.isRegLoc()) {
10707       // Queue up the argument copies and emit them at the end.
10708       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10709     } else {
10710       assert(VA.isMemLoc() && "Argument not register or memory");
10711       assert(!IsTailCall && "Tail call not allowed if stack is used "
10712                             "for passing parameters");
10713 
10714       // Work out the address of the stack slot.
10715       if (!StackPtr.getNode())
10716         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10717       SDValue Address =
10718           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10719                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10720 
10721       // Emit the store.
10722       MemOpChains.push_back(
10723           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10724     }
10725   }
10726 
10727   // Join the stores, which are independent of one another.
10728   if (!MemOpChains.empty())
10729     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10730 
10731   SDValue Glue;
10732 
10733   // Build a sequence of copy-to-reg nodes, chained and glued together.
10734   for (auto &Reg : RegsToPass) {
10735     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10736     Glue = Chain.getValue(1);
10737   }
10738 
10739   // Validate that none of the argument registers have been marked as
10740   // reserved, if so report an error. Do the same for the return address if this
10741   // is not a tailcall.
10742   validateCCReservedRegs(RegsToPass, MF);
10743   if (!IsTailCall &&
10744       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10745     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10746         MF.getFunction(),
10747         "Return address register required, but has been reserved."});
10748 
10749   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10750   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10751   // split it and then direct call can be matched by PseudoCALL.
10752   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10753     const GlobalValue *GV = S->getGlobal();
10754 
10755     unsigned OpFlags = RISCVII::MO_CALL;
10756     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10757       OpFlags = RISCVII::MO_PLT;
10758 
10759     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10760   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10761     unsigned OpFlags = RISCVII::MO_CALL;
10762 
10763     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10764                                                  nullptr))
10765       OpFlags = RISCVII::MO_PLT;
10766 
10767     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10768   }
10769 
10770   // The first call operand is the chain and the second is the target address.
10771   SmallVector<SDValue, 8> Ops;
10772   Ops.push_back(Chain);
10773   Ops.push_back(Callee);
10774 
10775   // Add argument registers to the end of the list so that they are
10776   // known live into the call.
10777   for (auto &Reg : RegsToPass)
10778     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10779 
10780   if (!IsTailCall) {
10781     // Add a register mask operand representing the call-preserved registers.
10782     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10783     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10784     assert(Mask && "Missing call preserved mask for calling convention");
10785     Ops.push_back(DAG.getRegisterMask(Mask));
10786   }
10787 
10788   // Glue the call to the argument copies, if any.
10789   if (Glue.getNode())
10790     Ops.push_back(Glue);
10791 
10792   // Emit the call.
10793   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10794 
10795   if (IsTailCall) {
10796     MF.getFrameInfo().setHasTailCall();
10797     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10798   }
10799 
10800   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10801   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10802   Glue = Chain.getValue(1);
10803 
10804   // Mark the end of the call, which is glued to the call itself.
10805   Chain = DAG.getCALLSEQ_END(Chain,
10806                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10807                              DAG.getConstant(0, DL, PtrVT, true),
10808                              Glue, DL);
10809   Glue = Chain.getValue(1);
10810 
10811   // Assign locations to each value returned by this call.
10812   SmallVector<CCValAssign, 16> RVLocs;
10813   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10814   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10815 
10816   // Copy all of the result registers out of their specified physreg.
10817   for (auto &VA : RVLocs) {
10818     // Copy the value out
10819     SDValue RetValue =
10820         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10821     // Glue the RetValue to the end of the call sequence
10822     Chain = RetValue.getValue(1);
10823     Glue = RetValue.getValue(2);
10824 
10825     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10826       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10827       SDValue RetValue2 =
10828           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10829       Chain = RetValue2.getValue(1);
10830       Glue = RetValue2.getValue(2);
10831       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10832                              RetValue2);
10833     }
10834 
10835     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10836 
10837     InVals.push_back(RetValue);
10838   }
10839 
10840   return Chain;
10841 }
10842 
10843 bool RISCVTargetLowering::CanLowerReturn(
10844     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10845     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10846   SmallVector<CCValAssign, 16> RVLocs;
10847   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10848 
10849   Optional<unsigned> FirstMaskArgument;
10850   if (Subtarget.hasVInstructions())
10851     FirstMaskArgument = preAssignMask(Outs);
10852 
10853   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10854     MVT VT = Outs[i].VT;
10855     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10856     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10857     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10858                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10859                  *this, FirstMaskArgument))
10860       return false;
10861   }
10862   return true;
10863 }
10864 
10865 SDValue
10866 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10867                                  bool IsVarArg,
10868                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10869                                  const SmallVectorImpl<SDValue> &OutVals,
10870                                  const SDLoc &DL, SelectionDAG &DAG) const {
10871   const MachineFunction &MF = DAG.getMachineFunction();
10872   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10873 
10874   // Stores the assignment of the return value to a location.
10875   SmallVector<CCValAssign, 16> RVLocs;
10876 
10877   // Info about the registers and stack slot.
10878   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10879                  *DAG.getContext());
10880 
10881   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10882                     nullptr, CC_RISCV);
10883 
10884   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10885     report_fatal_error("GHC functions return void only");
10886 
10887   SDValue Glue;
10888   SmallVector<SDValue, 4> RetOps(1, Chain);
10889 
10890   // Copy the result values into the output registers.
10891   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10892     SDValue Val = OutVals[i];
10893     CCValAssign &VA = RVLocs[i];
10894     assert(VA.isRegLoc() && "Can only return in registers!");
10895 
10896     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10897       // Handle returning f64 on RV32D with a soft float ABI.
10898       assert(VA.isRegLoc() && "Expected return via registers");
10899       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10900                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10901       SDValue Lo = SplitF64.getValue(0);
10902       SDValue Hi = SplitF64.getValue(1);
10903       Register RegLo = VA.getLocReg();
10904       assert(RegLo < RISCV::X31 && "Invalid register pair");
10905       Register RegHi = RegLo + 1;
10906 
10907       if (STI.isRegisterReservedByUser(RegLo) ||
10908           STI.isRegisterReservedByUser(RegHi))
10909         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10910             MF.getFunction(),
10911             "Return value register required, but has been reserved."});
10912 
10913       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10914       Glue = Chain.getValue(1);
10915       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10916       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10917       Glue = Chain.getValue(1);
10918       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10919     } else {
10920       // Handle a 'normal' return.
10921       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10922       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10923 
10924       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10925         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10926             MF.getFunction(),
10927             "Return value register required, but has been reserved."});
10928 
10929       // Guarantee that all emitted copies are stuck together.
10930       Glue = Chain.getValue(1);
10931       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10932     }
10933   }
10934 
10935   RetOps[0] = Chain; // Update chain.
10936 
10937   // Add the glue node if we have it.
10938   if (Glue.getNode()) {
10939     RetOps.push_back(Glue);
10940   }
10941 
10942   unsigned RetOpc = RISCVISD::RET_FLAG;
10943   // Interrupt service routines use different return instructions.
10944   const Function &Func = DAG.getMachineFunction().getFunction();
10945   if (Func.hasFnAttribute("interrupt")) {
10946     if (!Func.getReturnType()->isVoidTy())
10947       report_fatal_error(
10948           "Functions with the interrupt attribute must have void return type!");
10949 
10950     MachineFunction &MF = DAG.getMachineFunction();
10951     StringRef Kind =
10952       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10953 
10954     if (Kind == "user")
10955       RetOpc = RISCVISD::URET_FLAG;
10956     else if (Kind == "supervisor")
10957       RetOpc = RISCVISD::SRET_FLAG;
10958     else
10959       RetOpc = RISCVISD::MRET_FLAG;
10960   }
10961 
10962   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10963 }
10964 
10965 void RISCVTargetLowering::validateCCReservedRegs(
10966     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10967     MachineFunction &MF) const {
10968   const Function &F = MF.getFunction();
10969   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10970 
10971   if (llvm::any_of(Regs, [&STI](auto Reg) {
10972         return STI.isRegisterReservedByUser(Reg.first);
10973       }))
10974     F.getContext().diagnose(DiagnosticInfoUnsupported{
10975         F, "Argument register required, but has been reserved."});
10976 }
10977 
10978 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10979   return CI->isTailCall();
10980 }
10981 
10982 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10983 #define NODE_NAME_CASE(NODE)                                                   \
10984   case RISCVISD::NODE:                                                         \
10985     return "RISCVISD::" #NODE;
10986   // clang-format off
10987   switch ((RISCVISD::NodeType)Opcode) {
10988   case RISCVISD::FIRST_NUMBER:
10989     break;
10990   NODE_NAME_CASE(RET_FLAG)
10991   NODE_NAME_CASE(URET_FLAG)
10992   NODE_NAME_CASE(SRET_FLAG)
10993   NODE_NAME_CASE(MRET_FLAG)
10994   NODE_NAME_CASE(CALL)
10995   NODE_NAME_CASE(SELECT_CC)
10996   NODE_NAME_CASE(BR_CC)
10997   NODE_NAME_CASE(BuildPairF64)
10998   NODE_NAME_CASE(SplitF64)
10999   NODE_NAME_CASE(TAIL)
11000   NODE_NAME_CASE(MULHSU)
11001   NODE_NAME_CASE(SLLW)
11002   NODE_NAME_CASE(SRAW)
11003   NODE_NAME_CASE(SRLW)
11004   NODE_NAME_CASE(DIVW)
11005   NODE_NAME_CASE(DIVUW)
11006   NODE_NAME_CASE(REMUW)
11007   NODE_NAME_CASE(ROLW)
11008   NODE_NAME_CASE(RORW)
11009   NODE_NAME_CASE(CLZW)
11010   NODE_NAME_CASE(CTZW)
11011   NODE_NAME_CASE(FSLW)
11012   NODE_NAME_CASE(FSRW)
11013   NODE_NAME_CASE(FSL)
11014   NODE_NAME_CASE(FSR)
11015   NODE_NAME_CASE(FMV_H_X)
11016   NODE_NAME_CASE(FMV_X_ANYEXTH)
11017   NODE_NAME_CASE(FMV_X_SIGNEXTH)
11018   NODE_NAME_CASE(FMV_W_X_RV64)
11019   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
11020   NODE_NAME_CASE(FCVT_X)
11021   NODE_NAME_CASE(FCVT_XU)
11022   NODE_NAME_CASE(FCVT_W_RV64)
11023   NODE_NAME_CASE(FCVT_WU_RV64)
11024   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
11025   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
11026   NODE_NAME_CASE(READ_CYCLE_WIDE)
11027   NODE_NAME_CASE(GREV)
11028   NODE_NAME_CASE(GREVW)
11029   NODE_NAME_CASE(GORC)
11030   NODE_NAME_CASE(GORCW)
11031   NODE_NAME_CASE(SHFL)
11032   NODE_NAME_CASE(SHFLW)
11033   NODE_NAME_CASE(UNSHFL)
11034   NODE_NAME_CASE(UNSHFLW)
11035   NODE_NAME_CASE(BFP)
11036   NODE_NAME_CASE(BFPW)
11037   NODE_NAME_CASE(BCOMPRESS)
11038   NODE_NAME_CASE(BCOMPRESSW)
11039   NODE_NAME_CASE(BDECOMPRESS)
11040   NODE_NAME_CASE(BDECOMPRESSW)
11041   NODE_NAME_CASE(VMV_V_X_VL)
11042   NODE_NAME_CASE(VFMV_V_F_VL)
11043   NODE_NAME_CASE(VMV_X_S)
11044   NODE_NAME_CASE(VMV_S_X_VL)
11045   NODE_NAME_CASE(VFMV_S_F_VL)
11046   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
11047   NODE_NAME_CASE(READ_VLENB)
11048   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
11049   NODE_NAME_CASE(VSLIDEUP_VL)
11050   NODE_NAME_CASE(VSLIDE1UP_VL)
11051   NODE_NAME_CASE(VSLIDEDOWN_VL)
11052   NODE_NAME_CASE(VSLIDE1DOWN_VL)
11053   NODE_NAME_CASE(VID_VL)
11054   NODE_NAME_CASE(VFNCVT_ROD_VL)
11055   NODE_NAME_CASE(VECREDUCE_ADD_VL)
11056   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
11057   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
11058   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
11059   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
11060   NODE_NAME_CASE(VECREDUCE_AND_VL)
11061   NODE_NAME_CASE(VECREDUCE_OR_VL)
11062   NODE_NAME_CASE(VECREDUCE_XOR_VL)
11063   NODE_NAME_CASE(VECREDUCE_FADD_VL)
11064   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
11065   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
11066   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
11067   NODE_NAME_CASE(ADD_VL)
11068   NODE_NAME_CASE(AND_VL)
11069   NODE_NAME_CASE(MUL_VL)
11070   NODE_NAME_CASE(OR_VL)
11071   NODE_NAME_CASE(SDIV_VL)
11072   NODE_NAME_CASE(SHL_VL)
11073   NODE_NAME_CASE(SREM_VL)
11074   NODE_NAME_CASE(SRA_VL)
11075   NODE_NAME_CASE(SRL_VL)
11076   NODE_NAME_CASE(SUB_VL)
11077   NODE_NAME_CASE(UDIV_VL)
11078   NODE_NAME_CASE(UREM_VL)
11079   NODE_NAME_CASE(XOR_VL)
11080   NODE_NAME_CASE(SADDSAT_VL)
11081   NODE_NAME_CASE(UADDSAT_VL)
11082   NODE_NAME_CASE(SSUBSAT_VL)
11083   NODE_NAME_CASE(USUBSAT_VL)
11084   NODE_NAME_CASE(FADD_VL)
11085   NODE_NAME_CASE(FSUB_VL)
11086   NODE_NAME_CASE(FMUL_VL)
11087   NODE_NAME_CASE(FDIV_VL)
11088   NODE_NAME_CASE(FNEG_VL)
11089   NODE_NAME_CASE(FABS_VL)
11090   NODE_NAME_CASE(FSQRT_VL)
11091   NODE_NAME_CASE(FMA_VL)
11092   NODE_NAME_CASE(FCOPYSIGN_VL)
11093   NODE_NAME_CASE(SMIN_VL)
11094   NODE_NAME_CASE(SMAX_VL)
11095   NODE_NAME_CASE(UMIN_VL)
11096   NODE_NAME_CASE(UMAX_VL)
11097   NODE_NAME_CASE(FMINNUM_VL)
11098   NODE_NAME_CASE(FMAXNUM_VL)
11099   NODE_NAME_CASE(MULHS_VL)
11100   NODE_NAME_CASE(MULHU_VL)
11101   NODE_NAME_CASE(FP_TO_SINT_VL)
11102   NODE_NAME_CASE(FP_TO_UINT_VL)
11103   NODE_NAME_CASE(SINT_TO_FP_VL)
11104   NODE_NAME_CASE(UINT_TO_FP_VL)
11105   NODE_NAME_CASE(FP_EXTEND_VL)
11106   NODE_NAME_CASE(FP_ROUND_VL)
11107   NODE_NAME_CASE(VWMUL_VL)
11108   NODE_NAME_CASE(VWMULU_VL)
11109   NODE_NAME_CASE(VWMULSU_VL)
11110   NODE_NAME_CASE(VWADD_VL)
11111   NODE_NAME_CASE(VWADDU_VL)
11112   NODE_NAME_CASE(VWSUB_VL)
11113   NODE_NAME_CASE(VWSUBU_VL)
11114   NODE_NAME_CASE(VWADD_W_VL)
11115   NODE_NAME_CASE(VWADDU_W_VL)
11116   NODE_NAME_CASE(VWSUB_W_VL)
11117   NODE_NAME_CASE(VWSUBU_W_VL)
11118   NODE_NAME_CASE(SETCC_VL)
11119   NODE_NAME_CASE(VSELECT_VL)
11120   NODE_NAME_CASE(VP_MERGE_VL)
11121   NODE_NAME_CASE(VMAND_VL)
11122   NODE_NAME_CASE(VMOR_VL)
11123   NODE_NAME_CASE(VMXOR_VL)
11124   NODE_NAME_CASE(VMCLR_VL)
11125   NODE_NAME_CASE(VMSET_VL)
11126   NODE_NAME_CASE(VRGATHER_VX_VL)
11127   NODE_NAME_CASE(VRGATHER_VV_VL)
11128   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
11129   NODE_NAME_CASE(VSEXT_VL)
11130   NODE_NAME_CASE(VZEXT_VL)
11131   NODE_NAME_CASE(VCPOP_VL)
11132   NODE_NAME_CASE(READ_CSR)
11133   NODE_NAME_CASE(WRITE_CSR)
11134   NODE_NAME_CASE(SWAP_CSR)
11135   }
11136   // clang-format on
11137   return nullptr;
11138 #undef NODE_NAME_CASE
11139 }
11140 
11141 /// getConstraintType - Given a constraint letter, return the type of
11142 /// constraint it is for this target.
11143 RISCVTargetLowering::ConstraintType
11144 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
11145   if (Constraint.size() == 1) {
11146     switch (Constraint[0]) {
11147     default:
11148       break;
11149     case 'f':
11150       return C_RegisterClass;
11151     case 'I':
11152     case 'J':
11153     case 'K':
11154       return C_Immediate;
11155     case 'A':
11156       return C_Memory;
11157     case 'S': // A symbolic address
11158       return C_Other;
11159     }
11160   } else {
11161     if (Constraint == "vr" || Constraint == "vm")
11162       return C_RegisterClass;
11163   }
11164   return TargetLowering::getConstraintType(Constraint);
11165 }
11166 
11167 std::pair<unsigned, const TargetRegisterClass *>
11168 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11169                                                   StringRef Constraint,
11170                                                   MVT VT) const {
11171   // First, see if this is a constraint that directly corresponds to a
11172   // RISCV register class.
11173   if (Constraint.size() == 1) {
11174     switch (Constraint[0]) {
11175     case 'r':
11176       // TODO: Support fixed vectors up to XLen for P extension?
11177       if (VT.isVector())
11178         break;
11179       return std::make_pair(0U, &RISCV::GPRRegClass);
11180     case 'f':
11181       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11182         return std::make_pair(0U, &RISCV::FPR16RegClass);
11183       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11184         return std::make_pair(0U, &RISCV::FPR32RegClass);
11185       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11186         return std::make_pair(0U, &RISCV::FPR64RegClass);
11187       break;
11188     default:
11189       break;
11190     }
11191   } else if (Constraint == "vr") {
11192     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11193                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11194       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11195         return std::make_pair(0U, RC);
11196     }
11197   } else if (Constraint == "vm") {
11198     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11199       return std::make_pair(0U, &RISCV::VMV0RegClass);
11200   }
11201 
11202   // Clang will correctly decode the usage of register name aliases into their
11203   // official names. However, other frontends like `rustc` do not. This allows
11204   // users of these frontends to use the ABI names for registers in LLVM-style
11205   // register constraints.
11206   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11207                                .Case("{zero}", RISCV::X0)
11208                                .Case("{ra}", RISCV::X1)
11209                                .Case("{sp}", RISCV::X2)
11210                                .Case("{gp}", RISCV::X3)
11211                                .Case("{tp}", RISCV::X4)
11212                                .Case("{t0}", RISCV::X5)
11213                                .Case("{t1}", RISCV::X6)
11214                                .Case("{t2}", RISCV::X7)
11215                                .Cases("{s0}", "{fp}", RISCV::X8)
11216                                .Case("{s1}", RISCV::X9)
11217                                .Case("{a0}", RISCV::X10)
11218                                .Case("{a1}", RISCV::X11)
11219                                .Case("{a2}", RISCV::X12)
11220                                .Case("{a3}", RISCV::X13)
11221                                .Case("{a4}", RISCV::X14)
11222                                .Case("{a5}", RISCV::X15)
11223                                .Case("{a6}", RISCV::X16)
11224                                .Case("{a7}", RISCV::X17)
11225                                .Case("{s2}", RISCV::X18)
11226                                .Case("{s3}", RISCV::X19)
11227                                .Case("{s4}", RISCV::X20)
11228                                .Case("{s5}", RISCV::X21)
11229                                .Case("{s6}", RISCV::X22)
11230                                .Case("{s7}", RISCV::X23)
11231                                .Case("{s8}", RISCV::X24)
11232                                .Case("{s9}", RISCV::X25)
11233                                .Case("{s10}", RISCV::X26)
11234                                .Case("{s11}", RISCV::X27)
11235                                .Case("{t3}", RISCV::X28)
11236                                .Case("{t4}", RISCV::X29)
11237                                .Case("{t5}", RISCV::X30)
11238                                .Case("{t6}", RISCV::X31)
11239                                .Default(RISCV::NoRegister);
11240   if (XRegFromAlias != RISCV::NoRegister)
11241     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11242 
11243   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11244   // TableGen record rather than the AsmName to choose registers for InlineAsm
11245   // constraints, plus we want to match those names to the widest floating point
11246   // register type available, manually select floating point registers here.
11247   //
11248   // The second case is the ABI name of the register, so that frontends can also
11249   // use the ABI names in register constraint lists.
11250   if (Subtarget.hasStdExtF()) {
11251     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11252                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11253                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11254                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11255                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11256                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11257                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11258                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11259                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11260                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11261                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11262                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11263                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11264                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11265                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11266                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11267                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11268                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11269                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11270                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11271                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11272                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11273                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11274                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11275                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11276                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11277                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11278                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11279                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11280                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11281                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11282                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11283                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11284                         .Default(RISCV::NoRegister);
11285     if (FReg != RISCV::NoRegister) {
11286       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11287       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11288         unsigned RegNo = FReg - RISCV::F0_F;
11289         unsigned DReg = RISCV::F0_D + RegNo;
11290         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11291       }
11292       if (VT == MVT::f32 || VT == MVT::Other)
11293         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11294       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11295         unsigned RegNo = FReg - RISCV::F0_F;
11296         unsigned HReg = RISCV::F0_H + RegNo;
11297         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11298       }
11299     }
11300   }
11301 
11302   if (Subtarget.hasVInstructions()) {
11303     Register VReg = StringSwitch<Register>(Constraint.lower())
11304                         .Case("{v0}", RISCV::V0)
11305                         .Case("{v1}", RISCV::V1)
11306                         .Case("{v2}", RISCV::V2)
11307                         .Case("{v3}", RISCV::V3)
11308                         .Case("{v4}", RISCV::V4)
11309                         .Case("{v5}", RISCV::V5)
11310                         .Case("{v6}", RISCV::V6)
11311                         .Case("{v7}", RISCV::V7)
11312                         .Case("{v8}", RISCV::V8)
11313                         .Case("{v9}", RISCV::V9)
11314                         .Case("{v10}", RISCV::V10)
11315                         .Case("{v11}", RISCV::V11)
11316                         .Case("{v12}", RISCV::V12)
11317                         .Case("{v13}", RISCV::V13)
11318                         .Case("{v14}", RISCV::V14)
11319                         .Case("{v15}", RISCV::V15)
11320                         .Case("{v16}", RISCV::V16)
11321                         .Case("{v17}", RISCV::V17)
11322                         .Case("{v18}", RISCV::V18)
11323                         .Case("{v19}", RISCV::V19)
11324                         .Case("{v20}", RISCV::V20)
11325                         .Case("{v21}", RISCV::V21)
11326                         .Case("{v22}", RISCV::V22)
11327                         .Case("{v23}", RISCV::V23)
11328                         .Case("{v24}", RISCV::V24)
11329                         .Case("{v25}", RISCV::V25)
11330                         .Case("{v26}", RISCV::V26)
11331                         .Case("{v27}", RISCV::V27)
11332                         .Case("{v28}", RISCV::V28)
11333                         .Case("{v29}", RISCV::V29)
11334                         .Case("{v30}", RISCV::V30)
11335                         .Case("{v31}", RISCV::V31)
11336                         .Default(RISCV::NoRegister);
11337     if (VReg != RISCV::NoRegister) {
11338       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11339         return std::make_pair(VReg, &RISCV::VMRegClass);
11340       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11341         return std::make_pair(VReg, &RISCV::VRRegClass);
11342       for (const auto *RC :
11343            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11344         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11345           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11346           return std::make_pair(VReg, RC);
11347         }
11348       }
11349     }
11350   }
11351 
11352   std::pair<Register, const TargetRegisterClass *> Res =
11353       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11354 
11355   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11356   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11357   // Subtarget into account.
11358   if (Res.second == &RISCV::GPRF16RegClass ||
11359       Res.second == &RISCV::GPRF32RegClass ||
11360       Res.second == &RISCV::GPRF64RegClass)
11361     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11362 
11363   return Res;
11364 }
11365 
11366 unsigned
11367 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11368   // Currently only support length 1 constraints.
11369   if (ConstraintCode.size() == 1) {
11370     switch (ConstraintCode[0]) {
11371     case 'A':
11372       return InlineAsm::Constraint_A;
11373     default:
11374       break;
11375     }
11376   }
11377 
11378   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11379 }
11380 
11381 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11382     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11383     SelectionDAG &DAG) const {
11384   // Currently only support length 1 constraints.
11385   if (Constraint.length() == 1) {
11386     switch (Constraint[0]) {
11387     case 'I':
11388       // Validate & create a 12-bit signed immediate operand.
11389       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11390         uint64_t CVal = C->getSExtValue();
11391         if (isInt<12>(CVal))
11392           Ops.push_back(
11393               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11394       }
11395       return;
11396     case 'J':
11397       // Validate & create an integer zero operand.
11398       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11399         if (C->getZExtValue() == 0)
11400           Ops.push_back(
11401               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11402       return;
11403     case 'K':
11404       // Validate & create a 5-bit unsigned immediate operand.
11405       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11406         uint64_t CVal = C->getZExtValue();
11407         if (isUInt<5>(CVal))
11408           Ops.push_back(
11409               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11410       }
11411       return;
11412     case 'S':
11413       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11414         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11415                                                  GA->getValueType(0)));
11416       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11417         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11418                                                 BA->getValueType(0)));
11419       }
11420       return;
11421     default:
11422       break;
11423     }
11424   }
11425   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11426 }
11427 
11428 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11429                                                    Instruction *Inst,
11430                                                    AtomicOrdering Ord) const {
11431   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11432     return Builder.CreateFence(Ord);
11433   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11434     return Builder.CreateFence(AtomicOrdering::Release);
11435   return nullptr;
11436 }
11437 
11438 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11439                                                     Instruction *Inst,
11440                                                     AtomicOrdering Ord) const {
11441   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11442     return Builder.CreateFence(AtomicOrdering::Acquire);
11443   return nullptr;
11444 }
11445 
11446 TargetLowering::AtomicExpansionKind
11447 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11448   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11449   // point operations can't be used in an lr/sc sequence without breaking the
11450   // forward-progress guarantee.
11451   if (AI->isFloatingPointOperation())
11452     return AtomicExpansionKind::CmpXChg;
11453 
11454   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11455   if (Size == 8 || Size == 16)
11456     return AtomicExpansionKind::MaskedIntrinsic;
11457   return AtomicExpansionKind::None;
11458 }
11459 
11460 static Intrinsic::ID
11461 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11462   if (XLen == 32) {
11463     switch (BinOp) {
11464     default:
11465       llvm_unreachable("Unexpected AtomicRMW BinOp");
11466     case AtomicRMWInst::Xchg:
11467       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11468     case AtomicRMWInst::Add:
11469       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11470     case AtomicRMWInst::Sub:
11471       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11472     case AtomicRMWInst::Nand:
11473       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11474     case AtomicRMWInst::Max:
11475       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11476     case AtomicRMWInst::Min:
11477       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11478     case AtomicRMWInst::UMax:
11479       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11480     case AtomicRMWInst::UMin:
11481       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11482     }
11483   }
11484 
11485   if (XLen == 64) {
11486     switch (BinOp) {
11487     default:
11488       llvm_unreachable("Unexpected AtomicRMW BinOp");
11489     case AtomicRMWInst::Xchg:
11490       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11491     case AtomicRMWInst::Add:
11492       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11493     case AtomicRMWInst::Sub:
11494       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11495     case AtomicRMWInst::Nand:
11496       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11497     case AtomicRMWInst::Max:
11498       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11499     case AtomicRMWInst::Min:
11500       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11501     case AtomicRMWInst::UMax:
11502       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11503     case AtomicRMWInst::UMin:
11504       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11505     }
11506   }
11507 
11508   llvm_unreachable("Unexpected XLen\n");
11509 }
11510 
11511 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11512     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11513     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11514   unsigned XLen = Subtarget.getXLen();
11515   Value *Ordering =
11516       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11517   Type *Tys[] = {AlignedAddr->getType()};
11518   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11519       AI->getModule(),
11520       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11521 
11522   if (XLen == 64) {
11523     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11524     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11525     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11526   }
11527 
11528   Value *Result;
11529 
11530   // Must pass the shift amount needed to sign extend the loaded value prior
11531   // to performing a signed comparison for min/max. ShiftAmt is the number of
11532   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11533   // is the number of bits to left+right shift the value in order to
11534   // sign-extend.
11535   if (AI->getOperation() == AtomicRMWInst::Min ||
11536       AI->getOperation() == AtomicRMWInst::Max) {
11537     const DataLayout &DL = AI->getModule()->getDataLayout();
11538     unsigned ValWidth =
11539         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11540     Value *SextShamt =
11541         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11542     Result = Builder.CreateCall(LrwOpScwLoop,
11543                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11544   } else {
11545     Result =
11546         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11547   }
11548 
11549   if (XLen == 64)
11550     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11551   return Result;
11552 }
11553 
11554 TargetLowering::AtomicExpansionKind
11555 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11556     AtomicCmpXchgInst *CI) const {
11557   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11558   if (Size == 8 || Size == 16)
11559     return AtomicExpansionKind::MaskedIntrinsic;
11560   return AtomicExpansionKind::None;
11561 }
11562 
11563 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11564     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11565     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11566   unsigned XLen = Subtarget.getXLen();
11567   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11568   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11569   if (XLen == 64) {
11570     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11571     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11572     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11573     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11574   }
11575   Type *Tys[] = {AlignedAddr->getType()};
11576   Function *MaskedCmpXchg =
11577       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11578   Value *Result = Builder.CreateCall(
11579       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11580   if (XLen == 64)
11581     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11582   return Result;
11583 }
11584 
11585 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
11586   return false;
11587 }
11588 
11589 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11590                                                EVT VT) const {
11591   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11592     return false;
11593 
11594   switch (FPVT.getSimpleVT().SimpleTy) {
11595   case MVT::f16:
11596     return Subtarget.hasStdExtZfh();
11597   case MVT::f32:
11598     return Subtarget.hasStdExtF();
11599   case MVT::f64:
11600     return Subtarget.hasStdExtD();
11601   default:
11602     return false;
11603   }
11604 }
11605 
11606 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11607   // If we are using the small code model, we can reduce size of jump table
11608   // entry to 4 bytes.
11609   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11610       getTargetMachine().getCodeModel() == CodeModel::Small) {
11611     return MachineJumpTableInfo::EK_Custom32;
11612   }
11613   return TargetLowering::getJumpTableEncoding();
11614 }
11615 
11616 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11617     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11618     unsigned uid, MCContext &Ctx) const {
11619   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11620          getTargetMachine().getCodeModel() == CodeModel::Small);
11621   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11622 }
11623 
11624 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11625                                                      EVT VT) const {
11626   VT = VT.getScalarType();
11627 
11628   if (!VT.isSimple())
11629     return false;
11630 
11631   switch (VT.getSimpleVT().SimpleTy) {
11632   case MVT::f16:
11633     return Subtarget.hasStdExtZfh();
11634   case MVT::f32:
11635     return Subtarget.hasStdExtF();
11636   case MVT::f64:
11637     return Subtarget.hasStdExtD();
11638   default:
11639     break;
11640   }
11641 
11642   return false;
11643 }
11644 
11645 Register RISCVTargetLowering::getExceptionPointerRegister(
11646     const Constant *PersonalityFn) const {
11647   return RISCV::X10;
11648 }
11649 
11650 Register RISCVTargetLowering::getExceptionSelectorRegister(
11651     const Constant *PersonalityFn) const {
11652   return RISCV::X11;
11653 }
11654 
11655 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11656   // Return false to suppress the unnecessary extensions if the LibCall
11657   // arguments or return value is f32 type for LP64 ABI.
11658   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11659   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11660     return false;
11661 
11662   return true;
11663 }
11664 
11665 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11666   if (Subtarget.is64Bit() && Type == MVT::i32)
11667     return true;
11668 
11669   return IsSigned;
11670 }
11671 
11672 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11673                                                  SDValue C) const {
11674   // Check integral scalar types.
11675   if (VT.isScalarInteger()) {
11676     // Omit the optimization if the sub target has the M extension and the data
11677     // size exceeds XLen.
11678     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11679       return false;
11680     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11681       // Break the MUL to a SLLI and an ADD/SUB.
11682       const APInt &Imm = ConstNode->getAPIntValue();
11683       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11684           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11685         return true;
11686       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11687       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11688           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11689            (Imm - 8).isPowerOf2()))
11690         return true;
11691       // Omit the following optimization if the sub target has the M extension
11692       // and the data size >= XLen.
11693       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11694         return false;
11695       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11696       // a pair of LUI/ADDI.
11697       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11698         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11699         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11700             (1 - ImmS).isPowerOf2())
11701         return true;
11702       }
11703     }
11704   }
11705 
11706   return false;
11707 }
11708 
11709 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
11710                                                       SDValue ConstNode) const {
11711   // Let the DAGCombiner decide for vectors.
11712   EVT VT = AddNode.getValueType();
11713   if (VT.isVector())
11714     return true;
11715 
11716   // Let the DAGCombiner decide for larger types.
11717   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11718     return true;
11719 
11720   // It is worse if c1 is simm12 while c1*c2 is not.
11721   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11722   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11723   const APInt &C1 = C1Node->getAPIntValue();
11724   const APInt &C2 = C2Node->getAPIntValue();
11725   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11726     return false;
11727 
11728   // Default to true and let the DAGCombiner decide.
11729   return true;
11730 }
11731 
11732 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11733     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11734     bool *Fast) const {
11735   if (!VT.isVector())
11736     return false;
11737 
11738   EVT ElemVT = VT.getVectorElementType();
11739   if (Alignment >= ElemVT.getStoreSize()) {
11740     if (Fast)
11741       *Fast = true;
11742     return true;
11743   }
11744 
11745   return false;
11746 }
11747 
11748 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11749     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11750     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11751   bool IsABIRegCopy = CC.hasValue();
11752   EVT ValueVT = Val.getValueType();
11753   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11754     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11755     // and cast to f32.
11756     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11757     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11758     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11759                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11760     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11761     Parts[0] = Val;
11762     return true;
11763   }
11764 
11765   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11766     LLVMContext &Context = *DAG.getContext();
11767     EVT ValueEltVT = ValueVT.getVectorElementType();
11768     EVT PartEltVT = PartVT.getVectorElementType();
11769     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11770     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11771     if (PartVTBitSize % ValueVTBitSize == 0) {
11772       assert(PartVTBitSize >= ValueVTBitSize);
11773       // If the element types are different, bitcast to the same element type of
11774       // PartVT first.
11775       // Give an example here, we want copy a <vscale x 1 x i8> value to
11776       // <vscale x 4 x i16>.
11777       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11778       // subvector, then we can bitcast to <vscale x 4 x i16>.
11779       if (ValueEltVT != PartEltVT) {
11780         if (PartVTBitSize > ValueVTBitSize) {
11781           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11782           assert(Count != 0 && "The number of element should not be zero.");
11783           EVT SameEltTypeVT =
11784               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11785           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11786                             DAG.getUNDEF(SameEltTypeVT), Val,
11787                             DAG.getVectorIdxConstant(0, DL));
11788         }
11789         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11790       } else {
11791         Val =
11792             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11793                         Val, DAG.getVectorIdxConstant(0, DL));
11794       }
11795       Parts[0] = Val;
11796       return true;
11797     }
11798   }
11799   return false;
11800 }
11801 
11802 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11803     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11804     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11805   bool IsABIRegCopy = CC.hasValue();
11806   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11807     SDValue Val = Parts[0];
11808 
11809     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11810     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11811     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11812     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11813     return Val;
11814   }
11815 
11816   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11817     LLVMContext &Context = *DAG.getContext();
11818     SDValue Val = Parts[0];
11819     EVT ValueEltVT = ValueVT.getVectorElementType();
11820     EVT PartEltVT = PartVT.getVectorElementType();
11821     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11822     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11823     if (PartVTBitSize % ValueVTBitSize == 0) {
11824       assert(PartVTBitSize >= ValueVTBitSize);
11825       EVT SameEltTypeVT = ValueVT;
11826       // If the element types are different, convert it to the same element type
11827       // of PartVT.
11828       // Give an example here, we want copy a <vscale x 1 x i8> value from
11829       // <vscale x 4 x i16>.
11830       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11831       // then we can extract <vscale x 1 x i8>.
11832       if (ValueEltVT != PartEltVT) {
11833         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11834         assert(Count != 0 && "The number of element should not be zero.");
11835         SameEltTypeVT =
11836             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11837         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11838       }
11839       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11840                         DAG.getVectorIdxConstant(0, DL));
11841       return Val;
11842     }
11843   }
11844   return SDValue();
11845 }
11846 
11847 SDValue
11848 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11849                                    SelectionDAG &DAG,
11850                                    SmallVectorImpl<SDNode *> &Created) const {
11851   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11852   if (isIntDivCheap(N->getValueType(0), Attr))
11853     return SDValue(N, 0); // Lower SDIV as SDIV
11854 
11855   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11856          "Unexpected divisor!");
11857 
11858   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11859   if (!Subtarget.hasStdExtZbt())
11860     return SDValue();
11861 
11862   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11863   // Besides, more critical path instructions will be generated when dividing
11864   // by 2. So we keep using the original DAGs for these cases.
11865   unsigned Lg2 = Divisor.countTrailingZeros();
11866   if (Lg2 == 1 || Lg2 >= 12)
11867     return SDValue();
11868 
11869   // fold (sdiv X, pow2)
11870   EVT VT = N->getValueType(0);
11871   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11872     return SDValue();
11873 
11874   SDLoc DL(N);
11875   SDValue N0 = N->getOperand(0);
11876   SDValue Zero = DAG.getConstant(0, DL, VT);
11877   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11878 
11879   // Add (N0 < 0) ? Pow2 - 1 : 0;
11880   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
11881   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11882   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11883 
11884   Created.push_back(Cmp.getNode());
11885   Created.push_back(Add.getNode());
11886   Created.push_back(Sel.getNode());
11887 
11888   // Divide by pow2.
11889   SDValue SRA =
11890       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11891 
11892   // If we're dividing by a positive value, we're done.  Otherwise, we must
11893   // negate the result.
11894   if (Divisor.isNonNegative())
11895     return SRA;
11896 
11897   Created.push_back(SRA.getNode());
11898   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11899 }
11900 
11901 #define GET_REGISTER_MATCHER
11902 #include "RISCVGenAsmMatcher.inc"
11903 
11904 Register
11905 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11906                                        const MachineFunction &MF) const {
11907   Register Reg = MatchRegisterAltName(RegName);
11908   if (Reg == RISCV::NoRegister)
11909     Reg = MatchRegisterName(RegName);
11910   if (Reg == RISCV::NoRegister)
11911     report_fatal_error(
11912         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11913   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11914   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11915     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11916                              StringRef(RegName) + "\"."));
11917   return Reg;
11918 }
11919 
11920 namespace llvm {
11921 namespace RISCVVIntrinsicsTable {
11922 
11923 #define GET_RISCVVIntrinsicsTable_IMPL
11924 #include "RISCVGenSearchableTables.inc"
11925 
11926 } // namespace RISCVVIntrinsicsTable
11927 
11928 } // namespace llvm
11929