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};
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};
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     }
583 
584     for (MVT VT : IntVecVTs) {
585       if (VT.getVectorElementType() == MVT::i64 &&
586           !Subtarget.hasVInstructionsI64())
587         continue;
588 
589       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
590       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
591 
592       // Vectors implement MULHS/MULHU.
593       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
594       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
595 
596       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
597       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) {
598         setOperationAction(ISD::MULHU, VT, Expand);
599         setOperationAction(ISD::MULHS, VT, Expand);
600       }
601 
602       setOperationAction(ISD::SMIN, VT, Legal);
603       setOperationAction(ISD::SMAX, VT, Legal);
604       setOperationAction(ISD::UMIN, VT, Legal);
605       setOperationAction(ISD::UMAX, VT, Legal);
606 
607       setOperationAction(ISD::ROTL, VT, Expand);
608       setOperationAction(ISD::ROTR, VT, Expand);
609 
610       setOperationAction(ISD::CTTZ, VT, Expand);
611       setOperationAction(ISD::CTLZ, VT, Expand);
612       setOperationAction(ISD::CTPOP, VT, Expand);
613 
614       setOperationAction(ISD::BSWAP, VT, Expand);
615 
616       // Custom-lower extensions and truncations from/to mask types.
617       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
618       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
619       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
620 
621       // RVV has native int->float & float->int conversions where the
622       // element type sizes are within one power-of-two of each other. Any
623       // wider distances between type sizes have to be lowered as sequences
624       // which progressively narrow the gap in stages.
625       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
626       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
627       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
628       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
629 
630       setOperationAction(ISD::SADDSAT, VT, Legal);
631       setOperationAction(ISD::UADDSAT, VT, Legal);
632       setOperationAction(ISD::SSUBSAT, VT, Legal);
633       setOperationAction(ISD::USUBSAT, VT, Legal);
634 
635       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
636       // nodes which truncate by one power of two at a time.
637       setOperationAction(ISD::TRUNCATE, VT, Custom);
638 
639       // Custom-lower insert/extract operations to simplify patterns.
640       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
641       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
642 
643       // Custom-lower reduction operations to set up the corresponding custom
644       // nodes' operands.
645       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
646       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
647       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
648       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
649       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
650       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
651       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
652       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
653 
654       for (unsigned VPOpc : IntegerVPOps)
655         setOperationAction(VPOpc, VT, Custom);
656 
657       setOperationAction(ISD::LOAD, VT, Custom);
658       setOperationAction(ISD::STORE, VT, Custom);
659 
660       setOperationAction(ISD::MLOAD, VT, Custom);
661       setOperationAction(ISD::MSTORE, VT, Custom);
662       setOperationAction(ISD::MGATHER, VT, Custom);
663       setOperationAction(ISD::MSCATTER, VT, Custom);
664 
665       setOperationAction(ISD::VP_LOAD, VT, Custom);
666       setOperationAction(ISD::VP_STORE, VT, Custom);
667       setOperationAction(ISD::VP_GATHER, VT, Custom);
668       setOperationAction(ISD::VP_SCATTER, VT, Custom);
669 
670       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
671       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
672       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
673 
674       setOperationAction(ISD::SELECT, VT, Custom);
675       setOperationAction(ISD::SELECT_CC, VT, Expand);
676 
677       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
678       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
679 
680       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
681         setTruncStoreAction(VT, OtherVT, Expand);
682         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
683         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
684         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
685       }
686 
687       // Splice
688       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
689 
690       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
691       // type that can represent the value exactly.
692       if (VT.getVectorElementType() != MVT::i64) {
693         MVT FloatEltVT =
694             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
695         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
696         if (isTypeLegal(FloatVT)) {
697           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
698           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
699         }
700       }
701     }
702 
703     // Expand various CCs to best match the RVV ISA, which natively supports UNE
704     // but no other unordered comparisons, and supports all ordered comparisons
705     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
706     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
707     // and we pattern-match those back to the "original", swapping operands once
708     // more. This way we catch both operations and both "vf" and "fv" forms with
709     // fewer patterns.
710     static const ISD::CondCode VFPCCToExpand[] = {
711         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
712         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
713         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
714     };
715 
716     // Sets common operation actions on RVV floating-point vector types.
717     const auto SetCommonVFPActions = [&](MVT VT) {
718       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
719       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
720       // sizes are within one power-of-two of each other. Therefore conversions
721       // between vXf16 and vXf64 must be lowered as sequences which convert via
722       // vXf32.
723       setOperationAction(ISD::FP_ROUND, VT, Custom);
724       setOperationAction(ISD::FP_EXTEND, VT, Custom);
725       // Custom-lower insert/extract operations to simplify patterns.
726       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
727       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
728       // Expand various condition codes (explained above).
729       for (auto CC : VFPCCToExpand)
730         setCondCodeAction(CC, VT, Expand);
731 
732       setOperationAction(ISD::FMINNUM, VT, Legal);
733       setOperationAction(ISD::FMAXNUM, VT, Legal);
734 
735       setOperationAction(ISD::FTRUNC, VT, Custom);
736       setOperationAction(ISD::FCEIL, VT, Custom);
737       setOperationAction(ISD::FFLOOR, VT, Custom);
738       setOperationAction(ISD::FROUND, VT, Custom);
739 
740       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
741       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
742       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
743       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
744 
745       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
746 
747       setOperationAction(ISD::LOAD, VT, Custom);
748       setOperationAction(ISD::STORE, VT, Custom);
749 
750       setOperationAction(ISD::MLOAD, VT, Custom);
751       setOperationAction(ISD::MSTORE, VT, Custom);
752       setOperationAction(ISD::MGATHER, VT, Custom);
753       setOperationAction(ISD::MSCATTER, VT, Custom);
754 
755       setOperationAction(ISD::VP_LOAD, VT, Custom);
756       setOperationAction(ISD::VP_STORE, VT, Custom);
757       setOperationAction(ISD::VP_GATHER, VT, Custom);
758       setOperationAction(ISD::VP_SCATTER, VT, Custom);
759 
760       setOperationAction(ISD::SELECT, VT, Custom);
761       setOperationAction(ISD::SELECT_CC, VT, Expand);
762 
763       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
764       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
765       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
766 
767       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
768       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
769 
770       for (unsigned VPOpc : FloatingPointVPOps)
771         setOperationAction(VPOpc, VT, Custom);
772     };
773 
774     // Sets common extload/truncstore actions on RVV floating-point vector
775     // types.
776     const auto SetCommonVFPExtLoadTruncStoreActions =
777         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
778           for (auto SmallVT : SmallerVTs) {
779             setTruncStoreAction(VT, SmallVT, Expand);
780             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
781           }
782         };
783 
784     if (Subtarget.hasVInstructionsF16())
785       for (MVT VT : F16VecVTs)
786         SetCommonVFPActions(VT);
787 
788     for (MVT VT : F32VecVTs) {
789       if (Subtarget.hasVInstructionsF32())
790         SetCommonVFPActions(VT);
791       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
792     }
793 
794     for (MVT VT : F64VecVTs) {
795       if (Subtarget.hasVInstructionsF64())
796         SetCommonVFPActions(VT);
797       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
798       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
799     }
800 
801     if (Subtarget.useRVVForFixedLengthVectors()) {
802       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
803         if (!useRVVForFixedLengthVectorVT(VT))
804           continue;
805 
806         // By default everything must be expanded.
807         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
808           setOperationAction(Op, VT, Expand);
809         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
810           setTruncStoreAction(VT, OtherVT, Expand);
811           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
812           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
813           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
814         }
815 
816         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
817         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
818         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
819 
820         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
821         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
822 
823         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
824         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
825 
826         setOperationAction(ISD::LOAD, VT, Custom);
827         setOperationAction(ISD::STORE, VT, Custom);
828 
829         setOperationAction(ISD::SETCC, VT, Custom);
830 
831         setOperationAction(ISD::SELECT, VT, Custom);
832 
833         setOperationAction(ISD::TRUNCATE, VT, Custom);
834 
835         setOperationAction(ISD::BITCAST, VT, Custom);
836 
837         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
838         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
839         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
840 
841         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
842         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
843         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
844 
845         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
846         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
847         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
848         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
849 
850         // Operations below are different for between masks and other vectors.
851         if (VT.getVectorElementType() == MVT::i1) {
852           setOperationAction(ISD::VP_AND, VT, Custom);
853           setOperationAction(ISD::VP_OR, VT, Custom);
854           setOperationAction(ISD::VP_XOR, VT, Custom);
855           setOperationAction(ISD::AND, VT, Custom);
856           setOperationAction(ISD::OR, VT, Custom);
857           setOperationAction(ISD::XOR, VT, Custom);
858 
859           setOperationAction(ISD::VP_FPTOSI, VT, Custom);
860           setOperationAction(ISD::VP_FPTOUI, VT, Custom);
861           setOperationAction(ISD::VP_SETCC, VT, Custom);
862           continue;
863         }
864 
865         // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
866         // it before type legalization for i64 vectors on RV32. It will then be
867         // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
868         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
869         // improvements first.
870         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
871           setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
872           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
873         }
874 
875         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
876         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
877 
878         setOperationAction(ISD::MLOAD, VT, Custom);
879         setOperationAction(ISD::MSTORE, VT, Custom);
880         setOperationAction(ISD::MGATHER, VT, Custom);
881         setOperationAction(ISD::MSCATTER, VT, Custom);
882 
883         setOperationAction(ISD::VP_LOAD, VT, Custom);
884         setOperationAction(ISD::VP_STORE, VT, Custom);
885         setOperationAction(ISD::VP_GATHER, VT, Custom);
886         setOperationAction(ISD::VP_SCATTER, VT, Custom);
887 
888         setOperationAction(ISD::ADD, VT, Custom);
889         setOperationAction(ISD::MUL, VT, Custom);
890         setOperationAction(ISD::SUB, VT, Custom);
891         setOperationAction(ISD::AND, VT, Custom);
892         setOperationAction(ISD::OR, VT, Custom);
893         setOperationAction(ISD::XOR, VT, Custom);
894         setOperationAction(ISD::SDIV, VT, Custom);
895         setOperationAction(ISD::SREM, VT, Custom);
896         setOperationAction(ISD::UDIV, VT, Custom);
897         setOperationAction(ISD::UREM, VT, Custom);
898         setOperationAction(ISD::SHL, VT, Custom);
899         setOperationAction(ISD::SRA, VT, Custom);
900         setOperationAction(ISD::SRL, VT, Custom);
901 
902         setOperationAction(ISD::SMIN, VT, Custom);
903         setOperationAction(ISD::SMAX, VT, Custom);
904         setOperationAction(ISD::UMIN, VT, Custom);
905         setOperationAction(ISD::UMAX, VT, Custom);
906         setOperationAction(ISD::ABS,  VT, Custom);
907 
908         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
909         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) {
910           setOperationAction(ISD::MULHS, VT, Custom);
911           setOperationAction(ISD::MULHU, VT, Custom);
912         }
913 
914         setOperationAction(ISD::SADDSAT, VT, Custom);
915         setOperationAction(ISD::UADDSAT, VT, Custom);
916         setOperationAction(ISD::SSUBSAT, VT, Custom);
917         setOperationAction(ISD::USUBSAT, VT, Custom);
918 
919         setOperationAction(ISD::VSELECT, VT, Custom);
920         setOperationAction(ISD::SELECT_CC, VT, Expand);
921 
922         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
923         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
924         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
925 
926         // Custom-lower reduction operations to set up the corresponding custom
927         // nodes' operands.
928         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
929         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
930         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
931         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
932         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
933 
934         for (unsigned VPOpc : IntegerVPOps)
935           setOperationAction(VPOpc, VT, Custom);
936 
937         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
938         // type that can represent the value exactly.
939         if (VT.getVectorElementType() != MVT::i64) {
940           MVT FloatEltVT =
941               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
942           EVT FloatVT =
943               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
944           if (isTypeLegal(FloatVT)) {
945             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
946             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
947           }
948         }
949       }
950 
951       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
952         if (!useRVVForFixedLengthVectorVT(VT))
953           continue;
954 
955         // By default everything must be expanded.
956         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
957           setOperationAction(Op, VT, Expand);
958         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
959           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
960           setTruncStoreAction(VT, OtherVT, Expand);
961         }
962 
963         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
964         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
965         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
966 
967         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
968         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
969         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
970         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
971         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
972 
973         setOperationAction(ISD::LOAD, VT, Custom);
974         setOperationAction(ISD::STORE, VT, Custom);
975         setOperationAction(ISD::MLOAD, VT, Custom);
976         setOperationAction(ISD::MSTORE, VT, Custom);
977         setOperationAction(ISD::MGATHER, VT, Custom);
978         setOperationAction(ISD::MSCATTER, VT, Custom);
979 
980         setOperationAction(ISD::VP_LOAD, VT, Custom);
981         setOperationAction(ISD::VP_STORE, VT, Custom);
982         setOperationAction(ISD::VP_GATHER, VT, Custom);
983         setOperationAction(ISD::VP_SCATTER, VT, Custom);
984 
985         setOperationAction(ISD::FADD, VT, Custom);
986         setOperationAction(ISD::FSUB, VT, Custom);
987         setOperationAction(ISD::FMUL, VT, Custom);
988         setOperationAction(ISD::FDIV, VT, Custom);
989         setOperationAction(ISD::FNEG, VT, Custom);
990         setOperationAction(ISD::FABS, VT, Custom);
991         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
992         setOperationAction(ISD::FSQRT, VT, Custom);
993         setOperationAction(ISD::FMA, VT, Custom);
994         setOperationAction(ISD::FMINNUM, VT, Custom);
995         setOperationAction(ISD::FMAXNUM, VT, Custom);
996 
997         setOperationAction(ISD::FP_ROUND, VT, Custom);
998         setOperationAction(ISD::FP_EXTEND, VT, Custom);
999 
1000         setOperationAction(ISD::FTRUNC, VT, Custom);
1001         setOperationAction(ISD::FCEIL, VT, Custom);
1002         setOperationAction(ISD::FFLOOR, VT, Custom);
1003         setOperationAction(ISD::FROUND, VT, Custom);
1004 
1005         for (auto CC : VFPCCToExpand)
1006           setCondCodeAction(CC, VT, Expand);
1007 
1008         setOperationAction(ISD::VSELECT, VT, Custom);
1009         setOperationAction(ISD::SELECT, VT, Custom);
1010         setOperationAction(ISD::SELECT_CC, VT, Expand);
1011 
1012         setOperationAction(ISD::BITCAST, VT, Custom);
1013 
1014         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1015         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1016         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1017         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1018 
1019         for (unsigned VPOpc : FloatingPointVPOps)
1020           setOperationAction(VPOpc, VT, Custom);
1021       }
1022 
1023       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1024       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1025       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1026       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
1027       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1028       if (Subtarget.hasStdExtZfh())
1029         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
1030       if (Subtarget.hasStdExtF())
1031         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
1032       if (Subtarget.hasStdExtD())
1033         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
1034     }
1035   }
1036 
1037   // Function alignments.
1038   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
1039   setMinFunctionAlignment(FunctionAlignment);
1040   setPrefFunctionAlignment(FunctionAlignment);
1041 
1042   setMinimumJumpTableEntries(5);
1043 
1044   // Jumps are expensive, compared to logic
1045   setJumpIsExpensive();
1046 
1047   setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND,
1048                        ISD::OR, ISD::XOR});
1049 
1050   if (Subtarget.hasStdExtZbp())
1051     setTargetDAGCombine({ISD::ROTL, ISD::ROTR});
1052   if (Subtarget.hasStdExtZbkb())
1053     setTargetDAGCombine(ISD::BITREVERSE);
1054   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
1055     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1056   if (Subtarget.hasStdExtF())
1057     setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
1058                          ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT});
1059   if (Subtarget.hasVInstructions())
1060     setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER,
1061                          ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL,
1062                          ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR});
1063 
1064   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
1065   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
1066 }
1067 
1068 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1069                                             LLVMContext &Context,
1070                                             EVT VT) const {
1071   if (!VT.isVector())
1072     return getPointerTy(DL);
1073   if (Subtarget.hasVInstructions() &&
1074       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1075     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1076   return VT.changeVectorElementTypeToInteger();
1077 }
1078 
1079 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1080   return Subtarget.getXLenVT();
1081 }
1082 
1083 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1084                                              const CallInst &I,
1085                                              MachineFunction &MF,
1086                                              unsigned Intrinsic) const {
1087   auto &DL = I.getModule()->getDataLayout();
1088   switch (Intrinsic) {
1089   default:
1090     return false;
1091   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1092   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1093   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1094   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1095   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1096   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1097   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1098   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1099   case Intrinsic::riscv_masked_cmpxchg_i32:
1100     Info.opc = ISD::INTRINSIC_W_CHAIN;
1101     Info.memVT = MVT::i32;
1102     Info.ptrVal = I.getArgOperand(0);
1103     Info.offset = 0;
1104     Info.align = Align(4);
1105     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1106                  MachineMemOperand::MOVolatile;
1107     return true;
1108   case Intrinsic::riscv_masked_strided_load:
1109     Info.opc = ISD::INTRINSIC_W_CHAIN;
1110     Info.ptrVal = I.getArgOperand(1);
1111     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1112     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1113     Info.size = MemoryLocation::UnknownSize;
1114     Info.flags |= MachineMemOperand::MOLoad;
1115     return true;
1116   case Intrinsic::riscv_masked_strided_store:
1117     Info.opc = ISD::INTRINSIC_VOID;
1118     Info.ptrVal = I.getArgOperand(1);
1119     Info.memVT =
1120         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1121     Info.align = Align(
1122         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1123         8);
1124     Info.size = MemoryLocation::UnknownSize;
1125     Info.flags |= MachineMemOperand::MOStore;
1126     return true;
1127   case Intrinsic::riscv_seg2_load:
1128   case Intrinsic::riscv_seg3_load:
1129   case Intrinsic::riscv_seg4_load:
1130   case Intrinsic::riscv_seg5_load:
1131   case Intrinsic::riscv_seg6_load:
1132   case Intrinsic::riscv_seg7_load:
1133   case Intrinsic::riscv_seg8_load:
1134     Info.opc = ISD::INTRINSIC_W_CHAIN;
1135     Info.ptrVal = I.getArgOperand(0);
1136     Info.memVT =
1137         getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
1138     Info.align =
1139         Align(DL.getTypeSizeInBits(
1140                   I.getType()->getStructElementType(0)->getScalarType()) /
1141               8);
1142     Info.size = MemoryLocation::UnknownSize;
1143     Info.flags |= MachineMemOperand::MOLoad;
1144     return true;
1145   }
1146 }
1147 
1148 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1149                                                 const AddrMode &AM, Type *Ty,
1150                                                 unsigned AS,
1151                                                 Instruction *I) const {
1152   // No global is ever allowed as a base.
1153   if (AM.BaseGV)
1154     return false;
1155 
1156   // Require a 12-bit signed offset.
1157   if (!isInt<12>(AM.BaseOffs))
1158     return false;
1159 
1160   switch (AM.Scale) {
1161   case 0: // "r+i" or just "i", depending on HasBaseReg.
1162     break;
1163   case 1:
1164     if (!AM.HasBaseReg) // allow "r+i".
1165       break;
1166     return false; // disallow "r+r" or "r+r+i".
1167   default:
1168     return false;
1169   }
1170 
1171   return true;
1172 }
1173 
1174 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1175   return isInt<12>(Imm);
1176 }
1177 
1178 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1179   return isInt<12>(Imm);
1180 }
1181 
1182 // On RV32, 64-bit integers are split into their high and low parts and held
1183 // in two different registers, so the trunc is free since the low register can
1184 // just be used.
1185 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1186   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1187     return false;
1188   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1189   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1190   return (SrcBits == 64 && DestBits == 32);
1191 }
1192 
1193 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1194   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1195       !SrcVT.isInteger() || !DstVT.isInteger())
1196     return false;
1197   unsigned SrcBits = SrcVT.getSizeInBits();
1198   unsigned DestBits = DstVT.getSizeInBits();
1199   return (SrcBits == 64 && DestBits == 32);
1200 }
1201 
1202 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1203   // Zexts are free if they can be combined with a load.
1204   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1205   // poorly with type legalization of compares preferring sext.
1206   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1207     EVT MemVT = LD->getMemoryVT();
1208     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1209         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1210          LD->getExtensionType() == ISD::ZEXTLOAD))
1211       return true;
1212   }
1213 
1214   return TargetLowering::isZExtFree(Val, VT2);
1215 }
1216 
1217 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1218   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1219 }
1220 
1221 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const {
1222   return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
1223 }
1224 
1225 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1226   return Subtarget.hasStdExtZbb();
1227 }
1228 
1229 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1230   return Subtarget.hasStdExtZbb();
1231 }
1232 
1233 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1234   EVT VT = Y.getValueType();
1235 
1236   // FIXME: Support vectors once we have tests.
1237   if (VT.isVector())
1238     return false;
1239 
1240   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1241           Subtarget.hasStdExtZbkb()) &&
1242          !isa<ConstantSDNode>(Y);
1243 }
1244 
1245 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
1246   // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
1247   auto *C = dyn_cast<ConstantSDNode>(Y);
1248   return C && C->getAPIntValue().ule(10);
1249 }
1250 
1251 /// Check if sinking \p I's operands to I's basic block is profitable, because
1252 /// the operands can be folded into a target instruction, e.g.
1253 /// splats of scalars can fold into vector instructions.
1254 bool RISCVTargetLowering::shouldSinkOperands(
1255     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1256   using namespace llvm::PatternMatch;
1257 
1258   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1259     return false;
1260 
1261   auto IsSinker = [&](Instruction *I, int Operand) {
1262     switch (I->getOpcode()) {
1263     case Instruction::Add:
1264     case Instruction::Sub:
1265     case Instruction::Mul:
1266     case Instruction::And:
1267     case Instruction::Or:
1268     case Instruction::Xor:
1269     case Instruction::FAdd:
1270     case Instruction::FSub:
1271     case Instruction::FMul:
1272     case Instruction::FDiv:
1273     case Instruction::ICmp:
1274     case Instruction::FCmp:
1275       return true;
1276     case Instruction::Shl:
1277     case Instruction::LShr:
1278     case Instruction::AShr:
1279     case Instruction::UDiv:
1280     case Instruction::SDiv:
1281     case Instruction::URem:
1282     case Instruction::SRem:
1283       return Operand == 1;
1284     case Instruction::Call:
1285       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1286         switch (II->getIntrinsicID()) {
1287         case Intrinsic::fma:
1288         case Intrinsic::vp_fma:
1289           return Operand == 0 || Operand == 1;
1290         // FIXME: Our patterns can only match vx/vf instructions when the splat
1291         // it on the RHS, because TableGen doesn't recognize our VP operations
1292         // as commutative.
1293         case Intrinsic::vp_add:
1294         case Intrinsic::vp_mul:
1295         case Intrinsic::vp_and:
1296         case Intrinsic::vp_or:
1297         case Intrinsic::vp_xor:
1298         case Intrinsic::vp_fadd:
1299         case Intrinsic::vp_fmul:
1300         case Intrinsic::vp_shl:
1301         case Intrinsic::vp_lshr:
1302         case Intrinsic::vp_ashr:
1303         case Intrinsic::vp_udiv:
1304         case Intrinsic::vp_sdiv:
1305         case Intrinsic::vp_urem:
1306         case Intrinsic::vp_srem:
1307           return Operand == 1;
1308         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1309         // explicit patterns for both LHS and RHS (as 'vr' versions).
1310         case Intrinsic::vp_sub:
1311         case Intrinsic::vp_fsub:
1312         case Intrinsic::vp_fdiv:
1313           return Operand == 0 || Operand == 1;
1314         default:
1315           return false;
1316         }
1317       }
1318       return false;
1319     default:
1320       return false;
1321     }
1322   };
1323 
1324   for (auto OpIdx : enumerate(I->operands())) {
1325     if (!IsSinker(I, OpIdx.index()))
1326       continue;
1327 
1328     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1329     // Make sure we are not already sinking this operand
1330     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1331       continue;
1332 
1333     // We are looking for a splat that can be sunk.
1334     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1335                              m_Undef(), m_ZeroMask())))
1336       continue;
1337 
1338     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1339     // and vector registers
1340     for (Use &U : Op->uses()) {
1341       Instruction *Insn = cast<Instruction>(U.getUser());
1342       if (!IsSinker(Insn, U.getOperandNo()))
1343         return false;
1344     }
1345 
1346     Ops.push_back(&Op->getOperandUse(0));
1347     Ops.push_back(&OpIdx.value());
1348   }
1349   return true;
1350 }
1351 
1352 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1353                                        bool ForCodeSize) const {
1354   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1355   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1356     return false;
1357   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1358     return false;
1359   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1360     return false;
1361   return Imm.isZero();
1362 }
1363 
1364 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1365   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1366          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1367          (VT == MVT::f64 && Subtarget.hasStdExtD());
1368 }
1369 
1370 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1371                                                       CallingConv::ID CC,
1372                                                       EVT VT) const {
1373   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1374   // We might still end up using a GPR but that will be decided based on ABI.
1375   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1376   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1377     return MVT::f32;
1378 
1379   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1380 }
1381 
1382 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1383                                                            CallingConv::ID CC,
1384                                                            EVT VT) const {
1385   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1386   // We might still end up using a GPR but that will be decided based on ABI.
1387   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1388   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1389     return 1;
1390 
1391   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1392 }
1393 
1394 // Changes the condition code and swaps operands if necessary, so the SetCC
1395 // operation matches one of the comparisons supported directly by branches
1396 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1397 // with 1/-1.
1398 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1399                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1400   // Convert X > -1 to X >= 0.
1401   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1402     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1403     CC = ISD::SETGE;
1404     return;
1405   }
1406   // Convert X < 1 to 0 >= X.
1407   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1408     RHS = LHS;
1409     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1410     CC = ISD::SETGE;
1411     return;
1412   }
1413 
1414   switch (CC) {
1415   default:
1416     break;
1417   case ISD::SETGT:
1418   case ISD::SETLE:
1419   case ISD::SETUGT:
1420   case ISD::SETULE:
1421     CC = ISD::getSetCCSwappedOperands(CC);
1422     std::swap(LHS, RHS);
1423     break;
1424   }
1425 }
1426 
1427 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1428   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1429   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1430   if (VT.getVectorElementType() == MVT::i1)
1431     KnownSize *= 8;
1432 
1433   switch (KnownSize) {
1434   default:
1435     llvm_unreachable("Invalid LMUL.");
1436   case 8:
1437     return RISCVII::VLMUL::LMUL_F8;
1438   case 16:
1439     return RISCVII::VLMUL::LMUL_F4;
1440   case 32:
1441     return RISCVII::VLMUL::LMUL_F2;
1442   case 64:
1443     return RISCVII::VLMUL::LMUL_1;
1444   case 128:
1445     return RISCVII::VLMUL::LMUL_2;
1446   case 256:
1447     return RISCVII::VLMUL::LMUL_4;
1448   case 512:
1449     return RISCVII::VLMUL::LMUL_8;
1450   }
1451 }
1452 
1453 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1454   switch (LMul) {
1455   default:
1456     llvm_unreachable("Invalid LMUL.");
1457   case RISCVII::VLMUL::LMUL_F8:
1458   case RISCVII::VLMUL::LMUL_F4:
1459   case RISCVII::VLMUL::LMUL_F2:
1460   case RISCVII::VLMUL::LMUL_1:
1461     return RISCV::VRRegClassID;
1462   case RISCVII::VLMUL::LMUL_2:
1463     return RISCV::VRM2RegClassID;
1464   case RISCVII::VLMUL::LMUL_4:
1465     return RISCV::VRM4RegClassID;
1466   case RISCVII::VLMUL::LMUL_8:
1467     return RISCV::VRM8RegClassID;
1468   }
1469 }
1470 
1471 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1472   RISCVII::VLMUL LMUL = getLMUL(VT);
1473   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1474       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1475       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1476       LMUL == RISCVII::VLMUL::LMUL_1) {
1477     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1478                   "Unexpected subreg numbering");
1479     return RISCV::sub_vrm1_0 + Index;
1480   }
1481   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1482     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1483                   "Unexpected subreg numbering");
1484     return RISCV::sub_vrm2_0 + Index;
1485   }
1486   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1487     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1488                   "Unexpected subreg numbering");
1489     return RISCV::sub_vrm4_0 + Index;
1490   }
1491   llvm_unreachable("Invalid vector type.");
1492 }
1493 
1494 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1495   if (VT.getVectorElementType() == MVT::i1)
1496     return RISCV::VRRegClassID;
1497   return getRegClassIDForLMUL(getLMUL(VT));
1498 }
1499 
1500 // Attempt to decompose a subvector insert/extract between VecVT and
1501 // SubVecVT via subregister indices. Returns the subregister index that
1502 // can perform the subvector insert/extract with the given element index, as
1503 // well as the index corresponding to any leftover subvectors that must be
1504 // further inserted/extracted within the register class for SubVecVT.
1505 std::pair<unsigned, unsigned>
1506 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1507     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1508     const RISCVRegisterInfo *TRI) {
1509   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1510                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1511                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1512                 "Register classes not ordered");
1513   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1514   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1515   // Try to compose a subregister index that takes us from the incoming
1516   // LMUL>1 register class down to the outgoing one. At each step we half
1517   // the LMUL:
1518   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1519   // Note that this is not guaranteed to find a subregister index, such as
1520   // when we are extracting from one VR type to another.
1521   unsigned SubRegIdx = RISCV::NoSubRegister;
1522   for (const unsigned RCID :
1523        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1524     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1525       VecVT = VecVT.getHalfNumVectorElementsVT();
1526       bool IsHi =
1527           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1528       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1529                                             getSubregIndexByMVT(VecVT, IsHi));
1530       if (IsHi)
1531         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1532     }
1533   return {SubRegIdx, InsertExtractIdx};
1534 }
1535 
1536 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1537 // stores for those types.
1538 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1539   return !Subtarget.useRVVForFixedLengthVectors() ||
1540          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1541 }
1542 
1543 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1544   if (ScalarTy->isPointerTy())
1545     return true;
1546 
1547   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1548       ScalarTy->isIntegerTy(32))
1549     return true;
1550 
1551   if (ScalarTy->isIntegerTy(64))
1552     return Subtarget.hasVInstructionsI64();
1553 
1554   if (ScalarTy->isHalfTy())
1555     return Subtarget.hasVInstructionsF16();
1556   if (ScalarTy->isFloatTy())
1557     return Subtarget.hasVInstructionsF32();
1558   if (ScalarTy->isDoubleTy())
1559     return Subtarget.hasVInstructionsF64();
1560 
1561   return false;
1562 }
1563 
1564 static SDValue getVLOperand(SDValue Op) {
1565   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1566           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1567          "Unexpected opcode");
1568   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1569   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1570   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1571       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1572   if (!II)
1573     return SDValue();
1574   return Op.getOperand(II->VLOperand + 1 + HasChain);
1575 }
1576 
1577 static bool useRVVForFixedLengthVectorVT(MVT VT,
1578                                          const RISCVSubtarget &Subtarget) {
1579   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1580   if (!Subtarget.useRVVForFixedLengthVectors())
1581     return false;
1582 
1583   // We only support a set of vector types with a consistent maximum fixed size
1584   // across all supported vector element types to avoid legalization issues.
1585   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1586   // fixed-length vector type we support is 1024 bytes.
1587   if (VT.getFixedSizeInBits() > 1024 * 8)
1588     return false;
1589 
1590   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1591 
1592   MVT EltVT = VT.getVectorElementType();
1593 
1594   // Don't use RVV for vectors we cannot scalarize if required.
1595   switch (EltVT.SimpleTy) {
1596   // i1 is supported but has different rules.
1597   default:
1598     return false;
1599   case MVT::i1:
1600     // Masks can only use a single register.
1601     if (VT.getVectorNumElements() > MinVLen)
1602       return false;
1603     MinVLen /= 8;
1604     break;
1605   case MVT::i8:
1606   case MVT::i16:
1607   case MVT::i32:
1608     break;
1609   case MVT::i64:
1610     if (!Subtarget.hasVInstructionsI64())
1611       return false;
1612     break;
1613   case MVT::f16:
1614     if (!Subtarget.hasVInstructionsF16())
1615       return false;
1616     break;
1617   case MVT::f32:
1618     if (!Subtarget.hasVInstructionsF32())
1619       return false;
1620     break;
1621   case MVT::f64:
1622     if (!Subtarget.hasVInstructionsF64())
1623       return false;
1624     break;
1625   }
1626 
1627   // Reject elements larger than ELEN.
1628   if (EltVT.getSizeInBits() > Subtarget.getELEN())
1629     return false;
1630 
1631   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1632   // Don't use RVV for types that don't fit.
1633   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1634     return false;
1635 
1636   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1637   // the base fixed length RVV support in place.
1638   if (!VT.isPow2VectorType())
1639     return false;
1640 
1641   return true;
1642 }
1643 
1644 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1645   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1646 }
1647 
1648 // Return the largest legal scalable vector type that matches VT's element type.
1649 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1650                                             const RISCVSubtarget &Subtarget) {
1651   // This may be called before legal types are setup.
1652   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1653           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1654          "Expected legal fixed length vector!");
1655 
1656   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1657   unsigned MaxELen = Subtarget.getELEN();
1658 
1659   MVT EltVT = VT.getVectorElementType();
1660   switch (EltVT.SimpleTy) {
1661   default:
1662     llvm_unreachable("unexpected element type for RVV container");
1663   case MVT::i1:
1664   case MVT::i8:
1665   case MVT::i16:
1666   case MVT::i32:
1667   case MVT::i64:
1668   case MVT::f16:
1669   case MVT::f32:
1670   case MVT::f64: {
1671     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1672     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1673     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1674     unsigned NumElts =
1675         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1676     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1677     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1678     return MVT::getScalableVectorVT(EltVT, NumElts);
1679   }
1680   }
1681 }
1682 
1683 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1684                                             const RISCVSubtarget &Subtarget) {
1685   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1686                                           Subtarget);
1687 }
1688 
1689 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1690   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1691 }
1692 
1693 // Grow V to consume an entire RVV register.
1694 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1695                                        const RISCVSubtarget &Subtarget) {
1696   assert(VT.isScalableVector() &&
1697          "Expected to convert into a scalable vector!");
1698   assert(V.getValueType().isFixedLengthVector() &&
1699          "Expected a fixed length vector operand!");
1700   SDLoc DL(V);
1701   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1702   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1703 }
1704 
1705 // Shrink V so it's just big enough to maintain a VT's worth of data.
1706 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1707                                          const RISCVSubtarget &Subtarget) {
1708   assert(VT.isFixedLengthVector() &&
1709          "Expected to convert into a fixed length vector!");
1710   assert(V.getValueType().isScalableVector() &&
1711          "Expected a scalable vector operand!");
1712   SDLoc DL(V);
1713   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1714   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1715 }
1716 
1717 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1718 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1719 // the vector type that it is contained in.
1720 static std::pair<SDValue, SDValue>
1721 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1722                 const RISCVSubtarget &Subtarget) {
1723   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1724   MVT XLenVT = Subtarget.getXLenVT();
1725   SDValue VL = VecVT.isFixedLengthVector()
1726                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1727                    : DAG.getRegister(RISCV::X0, XLenVT);
1728   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1729   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1730   return {Mask, VL};
1731 }
1732 
1733 // As above but assuming the given type is a scalable vector type.
1734 static std::pair<SDValue, SDValue>
1735 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1736                         const RISCVSubtarget &Subtarget) {
1737   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1738   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1739 }
1740 
1741 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1742 // of either is (currently) supported. This can get us into an infinite loop
1743 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1744 // as a ..., etc.
1745 // Until either (or both) of these can reliably lower any node, reporting that
1746 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1747 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1748 // which is not desirable.
1749 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1750     EVT VT, unsigned DefinedValues) const {
1751   return false;
1752 }
1753 
1754 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1755                                   const RISCVSubtarget &Subtarget) {
1756   // RISCV FP-to-int conversions saturate to the destination register size, but
1757   // don't produce 0 for nan. We can use a conversion instruction and fix the
1758   // nan case with a compare and a select.
1759   SDValue Src = Op.getOperand(0);
1760 
1761   EVT DstVT = Op.getValueType();
1762   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1763 
1764   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1765   unsigned Opc;
1766   if (SatVT == DstVT)
1767     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1768   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1769     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1770   else
1771     return SDValue();
1772   // FIXME: Support other SatVTs by clamping before or after the conversion.
1773 
1774   SDLoc DL(Op);
1775   SDValue FpToInt = DAG.getNode(
1776       Opc, DL, DstVT, Src,
1777       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1778 
1779   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1780   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1781 }
1782 
1783 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1784 // and back. Taking care to avoid converting values that are nan or already
1785 // correct.
1786 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1787 // have FRM dependencies modeled yet.
1788 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1789   MVT VT = Op.getSimpleValueType();
1790   assert(VT.isVector() && "Unexpected type");
1791 
1792   SDLoc DL(Op);
1793 
1794   // Freeze the source since we are increasing the number of uses.
1795   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1796 
1797   // Truncate to integer and convert back to FP.
1798   MVT IntVT = VT.changeVectorElementTypeToInteger();
1799   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1800   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1801 
1802   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1803 
1804   if (Op.getOpcode() == ISD::FCEIL) {
1805     // If the truncated value is the greater than or equal to the original
1806     // value, we've computed the ceil. Otherwise, we went the wrong way and
1807     // need to increase by 1.
1808     // FIXME: This should use a masked operation. Handle here or in isel?
1809     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1810                                  DAG.getConstantFP(1.0, DL, VT));
1811     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1812     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1813   } else if (Op.getOpcode() == ISD::FFLOOR) {
1814     // If the truncated value is the less than or equal to the original value,
1815     // we've computed the floor. Otherwise, we went the wrong way and need to
1816     // decrease by 1.
1817     // FIXME: This should use a masked operation. Handle here or in isel?
1818     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1819                                  DAG.getConstantFP(1.0, DL, VT));
1820     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1821     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1822   }
1823 
1824   // Restore the original sign so that -0.0 is preserved.
1825   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1826 
1827   // Determine the largest integer that can be represented exactly. This and
1828   // values larger than it don't have any fractional bits so don't need to
1829   // be converted.
1830   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1831   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1832   APFloat MaxVal = APFloat(FltSem);
1833   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1834                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1835   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1836 
1837   // If abs(Src) was larger than MaxVal or nan, keep it.
1838   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1839   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1840   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1841 }
1842 
1843 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1844 // This mode isn't supported in vector hardware on RISCV. But as long as we
1845 // aren't compiling with trapping math, we can emulate this with
1846 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1847 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1848 // dependencies modeled yet.
1849 // FIXME: Use masked operations to avoid final merge.
1850 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1851   MVT VT = Op.getSimpleValueType();
1852   assert(VT.isVector() && "Unexpected type");
1853 
1854   SDLoc DL(Op);
1855 
1856   // Freeze the source since we are increasing the number of uses.
1857   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1858 
1859   // We do the conversion on the absolute value and fix the sign at the end.
1860   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1861 
1862   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1863   bool Ignored;
1864   APFloat Point5Pred = APFloat(0.5f);
1865   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1866   Point5Pred.next(/*nextDown*/ true);
1867 
1868   // Add the adjustment.
1869   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1870                                DAG.getConstantFP(Point5Pred, DL, VT));
1871 
1872   // Truncate to integer and convert back to fp.
1873   MVT IntVT = VT.changeVectorElementTypeToInteger();
1874   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1875   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1876 
1877   // Restore the original sign.
1878   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1879 
1880   // Determine the largest integer that can be represented exactly. This and
1881   // values larger than it don't have any fractional bits so don't need to
1882   // be converted.
1883   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1884   APFloat MaxVal = APFloat(FltSem);
1885   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1886                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1887   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1888 
1889   // If abs(Src) was larger than MaxVal or nan, keep it.
1890   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1891   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1892   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1893 }
1894 
1895 struct VIDSequence {
1896   int64_t StepNumerator;
1897   unsigned StepDenominator;
1898   int64_t Addend;
1899 };
1900 
1901 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1902 // to the (non-zero) step S and start value X. This can be then lowered as the
1903 // RVV sequence (VID * S) + X, for example.
1904 // The step S is represented as an integer numerator divided by a positive
1905 // denominator. Note that the implementation currently only identifies
1906 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1907 // cannot detect 2/3, for example.
1908 // Note that this method will also match potentially unappealing index
1909 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1910 // determine whether this is worth generating code for.
1911 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1912   unsigned NumElts = Op.getNumOperands();
1913   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1914   if (!Op.getValueType().isInteger())
1915     return None;
1916 
1917   Optional<unsigned> SeqStepDenom;
1918   Optional<int64_t> SeqStepNum, SeqAddend;
1919   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1920   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1921   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1922     // Assume undef elements match the sequence; we just have to be careful
1923     // when interpolating across them.
1924     if (Op.getOperand(Idx).isUndef())
1925       continue;
1926     // The BUILD_VECTOR must be all constants.
1927     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1928       return None;
1929 
1930     uint64_t Val = Op.getConstantOperandVal(Idx) &
1931                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1932 
1933     if (PrevElt) {
1934       // Calculate the step since the last non-undef element, and ensure
1935       // it's consistent across the entire sequence.
1936       unsigned IdxDiff = Idx - PrevElt->second;
1937       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1938 
1939       // A zero-value value difference means that we're somewhere in the middle
1940       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1941       // step change before evaluating the sequence.
1942       if (ValDiff != 0) {
1943         int64_t Remainder = ValDiff % IdxDiff;
1944         // Normalize the step if it's greater than 1.
1945         if (Remainder != ValDiff) {
1946           // The difference must cleanly divide the element span.
1947           if (Remainder != 0)
1948             return None;
1949           ValDiff /= IdxDiff;
1950           IdxDiff = 1;
1951         }
1952 
1953         if (!SeqStepNum)
1954           SeqStepNum = ValDiff;
1955         else if (ValDiff != SeqStepNum)
1956           return None;
1957 
1958         if (!SeqStepDenom)
1959           SeqStepDenom = IdxDiff;
1960         else if (IdxDiff != *SeqStepDenom)
1961           return None;
1962       }
1963     }
1964 
1965     // Record and/or check any addend.
1966     if (SeqStepNum && SeqStepDenom) {
1967       uint64_t ExpectedVal =
1968           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1969       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1970       if (!SeqAddend)
1971         SeqAddend = Addend;
1972       else if (SeqAddend != Addend)
1973         return None;
1974     }
1975 
1976     // Record this non-undef element for later.
1977     if (!PrevElt || PrevElt->first != Val)
1978       PrevElt = std::make_pair(Val, Idx);
1979   }
1980   // We need to have logged both a step and an addend for this to count as
1981   // a legal index sequence.
1982   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1983     return None;
1984 
1985   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1986 }
1987 
1988 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1989 // and lower it as a VRGATHER_VX_VL from the source vector.
1990 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
1991                                   SelectionDAG &DAG,
1992                                   const RISCVSubtarget &Subtarget) {
1993   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1994     return SDValue();
1995   SDValue Vec = SplatVal.getOperand(0);
1996   // Only perform this optimization on vectors of the same size for simplicity.
1997   if (Vec.getValueType() != VT)
1998     return SDValue();
1999   SDValue Idx = SplatVal.getOperand(1);
2000   // The index must be a legal type.
2001   if (Idx.getValueType() != Subtarget.getXLenVT())
2002     return SDValue();
2003 
2004   MVT ContainerVT = VT;
2005   if (VT.isFixedLengthVector()) {
2006     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2007     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2008   }
2009 
2010   SDValue Mask, VL;
2011   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2012 
2013   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
2014                                Idx, Mask, VL);
2015 
2016   if (!VT.isFixedLengthVector())
2017     return Gather;
2018 
2019   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2020 }
2021 
2022 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
2023                                  const RISCVSubtarget &Subtarget) {
2024   MVT VT = Op.getSimpleValueType();
2025   assert(VT.isFixedLengthVector() && "Unexpected vector!");
2026 
2027   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2028 
2029   SDLoc DL(Op);
2030   SDValue Mask, VL;
2031   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2032 
2033   MVT XLenVT = Subtarget.getXLenVT();
2034   unsigned NumElts = Op.getNumOperands();
2035 
2036   if (VT.getVectorElementType() == MVT::i1) {
2037     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
2038       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
2039       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
2040     }
2041 
2042     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
2043       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
2044       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
2045     }
2046 
2047     // Lower constant mask BUILD_VECTORs via an integer vector type, in
2048     // scalar integer chunks whose bit-width depends on the number of mask
2049     // bits and XLEN.
2050     // First, determine the most appropriate scalar integer type to use. This
2051     // is at most XLenVT, but may be shrunk to a smaller vector element type
2052     // according to the size of the final vector - use i8 chunks rather than
2053     // XLenVT if we're producing a v8i1. This results in more consistent
2054     // codegen across RV32 and RV64.
2055     unsigned NumViaIntegerBits =
2056         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2057     NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN());
2058     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2059       // If we have to use more than one INSERT_VECTOR_ELT then this
2060       // optimization is likely to increase code size; avoid peforming it in
2061       // such a case. We can use a load from a constant pool in this case.
2062       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2063         return SDValue();
2064       // Now we can create our integer vector type. Note that it may be larger
2065       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2066       MVT IntegerViaVecVT =
2067           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2068                            divideCeil(NumElts, NumViaIntegerBits));
2069 
2070       uint64_t Bits = 0;
2071       unsigned BitPos = 0, IntegerEltIdx = 0;
2072       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2073 
2074       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2075         // Once we accumulate enough bits to fill our scalar type, insert into
2076         // our vector and clear our accumulated data.
2077         if (I != 0 && I % NumViaIntegerBits == 0) {
2078           if (NumViaIntegerBits <= 32)
2079             Bits = SignExtend64(Bits, 32);
2080           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2081           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2082                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2083           Bits = 0;
2084           BitPos = 0;
2085           IntegerEltIdx++;
2086         }
2087         SDValue V = Op.getOperand(I);
2088         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2089         Bits |= ((uint64_t)BitValue << BitPos);
2090       }
2091 
2092       // Insert the (remaining) scalar value into position in our integer
2093       // vector type.
2094       if (NumViaIntegerBits <= 32)
2095         Bits = SignExtend64(Bits, 32);
2096       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2097       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2098                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2099 
2100       if (NumElts < NumViaIntegerBits) {
2101         // If we're producing a smaller vector than our minimum legal integer
2102         // type, bitcast to the equivalent (known-legal) mask type, and extract
2103         // our final mask.
2104         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2105         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2106         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2107                           DAG.getConstant(0, DL, XLenVT));
2108       } else {
2109         // Else we must have produced an integer type with the same size as the
2110         // mask type; bitcast for the final result.
2111         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2112         Vec = DAG.getBitcast(VT, Vec);
2113       }
2114 
2115       return Vec;
2116     }
2117 
2118     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2119     // vector type, we have a legal equivalently-sized i8 type, so we can use
2120     // that.
2121     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2122     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2123 
2124     SDValue WideVec;
2125     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2126       // For a splat, perform a scalar truncate before creating the wider
2127       // vector.
2128       assert(Splat.getValueType() == XLenVT &&
2129              "Unexpected type for i1 splat value");
2130       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2131                           DAG.getConstant(1, DL, XLenVT));
2132       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2133     } else {
2134       SmallVector<SDValue, 8> Ops(Op->op_values());
2135       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2136       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2137       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2138     }
2139 
2140     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2141   }
2142 
2143   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2144     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2145       return Gather;
2146     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2147                                         : RISCVISD::VMV_V_X_VL;
2148     Splat =
2149         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2150     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2151   }
2152 
2153   // Try and match index sequences, which we can lower to the vid instruction
2154   // with optional modifications. An all-undef vector is matched by
2155   // getSplatValue, above.
2156   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2157     int64_t StepNumerator = SimpleVID->StepNumerator;
2158     unsigned StepDenominator = SimpleVID->StepDenominator;
2159     int64_t Addend = SimpleVID->Addend;
2160 
2161     assert(StepNumerator != 0 && "Invalid step");
2162     bool Negate = false;
2163     int64_t SplatStepVal = StepNumerator;
2164     unsigned StepOpcode = ISD::MUL;
2165     if (StepNumerator != 1) {
2166       if (isPowerOf2_64(std::abs(StepNumerator))) {
2167         Negate = StepNumerator < 0;
2168         StepOpcode = ISD::SHL;
2169         SplatStepVal = Log2_64(std::abs(StepNumerator));
2170       }
2171     }
2172 
2173     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2174     // threshold since it's the immediate value many RVV instructions accept.
2175     // There is no vmul.vi instruction so ensure multiply constant can fit in
2176     // a single addi instruction.
2177     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2178          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2179         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2180       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2181       // Convert right out of the scalable type so we can use standard ISD
2182       // nodes for the rest of the computation. If we used scalable types with
2183       // these, we'd lose the fixed-length vector info and generate worse
2184       // vsetvli code.
2185       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2186       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2187           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2188         SDValue SplatStep = DAG.getSplatBuildVector(
2189             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2190         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2191       }
2192       if (StepDenominator != 1) {
2193         SDValue SplatStep = DAG.getSplatBuildVector(
2194             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2195         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2196       }
2197       if (Addend != 0 || Negate) {
2198         SDValue SplatAddend = DAG.getSplatBuildVector(
2199             VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2200         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2201       }
2202       return VID;
2203     }
2204   }
2205 
2206   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2207   // when re-interpreted as a vector with a larger element type. For example,
2208   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2209   // could be instead splat as
2210   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2211   // TODO: This optimization could also work on non-constant splats, but it
2212   // would require bit-manipulation instructions to construct the splat value.
2213   SmallVector<SDValue> Sequence;
2214   unsigned EltBitSize = VT.getScalarSizeInBits();
2215   const auto *BV = cast<BuildVectorSDNode>(Op);
2216   if (VT.isInteger() && EltBitSize < 64 &&
2217       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2218       BV->getRepeatedSequence(Sequence) &&
2219       (Sequence.size() * EltBitSize) <= 64) {
2220     unsigned SeqLen = Sequence.size();
2221     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2222     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2223     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2224             ViaIntVT == MVT::i64) &&
2225            "Unexpected sequence type");
2226 
2227     unsigned EltIdx = 0;
2228     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2229     uint64_t SplatValue = 0;
2230     // Construct the amalgamated value which can be splatted as this larger
2231     // vector type.
2232     for (const auto &SeqV : Sequence) {
2233       if (!SeqV.isUndef())
2234         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2235                        << (EltIdx * EltBitSize));
2236       EltIdx++;
2237     }
2238 
2239     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2240     // achieve better constant materializion.
2241     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2242       SplatValue = SignExtend64(SplatValue, 32);
2243 
2244     // Since we can't introduce illegal i64 types at this stage, we can only
2245     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2246     // way we can use RVV instructions to splat.
2247     assert((ViaIntVT.bitsLE(XLenVT) ||
2248             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2249            "Unexpected bitcast sequence");
2250     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2251       SDValue ViaVL =
2252           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2253       MVT ViaContainerVT =
2254           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2255       SDValue Splat =
2256           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2257                       DAG.getUNDEF(ViaContainerVT),
2258                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2259       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2260       return DAG.getBitcast(VT, Splat);
2261     }
2262   }
2263 
2264   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2265   // which constitute a large proportion of the elements. In such cases we can
2266   // splat a vector with the dominant element and make up the shortfall with
2267   // INSERT_VECTOR_ELTs.
2268   // Note that this includes vectors of 2 elements by association. The
2269   // upper-most element is the "dominant" one, allowing us to use a splat to
2270   // "insert" the upper element, and an insert of the lower element at position
2271   // 0, which improves codegen.
2272   SDValue DominantValue;
2273   unsigned MostCommonCount = 0;
2274   DenseMap<SDValue, unsigned> ValueCounts;
2275   unsigned NumUndefElts =
2276       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2277 
2278   // Track the number of scalar loads we know we'd be inserting, estimated as
2279   // any non-zero floating-point constant. Other kinds of element are either
2280   // already in registers or are materialized on demand. The threshold at which
2281   // a vector load is more desirable than several scalar materializion and
2282   // vector-insertion instructions is not known.
2283   unsigned NumScalarLoads = 0;
2284 
2285   for (SDValue V : Op->op_values()) {
2286     if (V.isUndef())
2287       continue;
2288 
2289     ValueCounts.insert(std::make_pair(V, 0));
2290     unsigned &Count = ValueCounts[V];
2291 
2292     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2293       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2294 
2295     // Is this value dominant? In case of a tie, prefer the highest element as
2296     // it's cheaper to insert near the beginning of a vector than it is at the
2297     // end.
2298     if (++Count >= MostCommonCount) {
2299       DominantValue = V;
2300       MostCommonCount = Count;
2301     }
2302   }
2303 
2304   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2305   unsigned NumDefElts = NumElts - NumUndefElts;
2306   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2307 
2308   // Don't perform this optimization when optimizing for size, since
2309   // materializing elements and inserting them tends to cause code bloat.
2310   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2311       ((MostCommonCount > DominantValueCountThreshold) ||
2312        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2313     // Start by splatting the most common element.
2314     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2315 
2316     DenseSet<SDValue> Processed{DominantValue};
2317     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2318     for (const auto &OpIdx : enumerate(Op->ops())) {
2319       const SDValue &V = OpIdx.value();
2320       if (V.isUndef() || !Processed.insert(V).second)
2321         continue;
2322       if (ValueCounts[V] == 1) {
2323         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2324                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2325       } else {
2326         // Blend in all instances of this value using a VSELECT, using a
2327         // mask where each bit signals whether that element is the one
2328         // we're after.
2329         SmallVector<SDValue> Ops;
2330         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2331           return DAG.getConstant(V == V1, DL, XLenVT);
2332         });
2333         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2334                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2335                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2336       }
2337     }
2338 
2339     return Vec;
2340   }
2341 
2342   return SDValue();
2343 }
2344 
2345 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2346                                    SDValue Lo, SDValue Hi, SDValue VL,
2347                                    SelectionDAG &DAG) {
2348   if (!Passthru)
2349     Passthru = DAG.getUNDEF(VT);
2350   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2351     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2352     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2353     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2354     // node in order to try and match RVV vector/scalar instructions.
2355     if ((LoC >> 31) == HiC)
2356       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2357 
2358     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2359     // vmv.v.x whose EEW = 32 to lower it.
2360     auto *Const = dyn_cast<ConstantSDNode>(VL);
2361     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2362       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2363       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2364       // access the subtarget here now.
2365       auto InterVec = DAG.getNode(
2366           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2367                                   DAG.getRegister(RISCV::X0, MVT::i32));
2368       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2369     }
2370   }
2371 
2372   // Fall back to a stack store and stride x0 vector load.
2373   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2374                      Hi, VL);
2375 }
2376 
2377 // Called by type legalization to handle splat of i64 on RV32.
2378 // FIXME: We can optimize this when the type has sign or zero bits in one
2379 // of the halves.
2380 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2381                                    SDValue Scalar, SDValue VL,
2382                                    SelectionDAG &DAG) {
2383   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2384   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2385                            DAG.getConstant(0, DL, MVT::i32));
2386   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2387                            DAG.getConstant(1, DL, MVT::i32));
2388   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2389 }
2390 
2391 // This function lowers a splat of a scalar operand Splat with the vector
2392 // length VL. It ensures the final sequence is type legal, which is useful when
2393 // lowering a splat after type legalization.
2394 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2395                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2396                                 const RISCVSubtarget &Subtarget) {
2397   bool HasPassthru = Passthru && !Passthru.isUndef();
2398   if (!HasPassthru && !Passthru)
2399     Passthru = DAG.getUNDEF(VT);
2400   if (VT.isFloatingPoint()) {
2401     // If VL is 1, we could use vfmv.s.f.
2402     if (isOneConstant(VL))
2403       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2404     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2405   }
2406 
2407   MVT XLenVT = Subtarget.getXLenVT();
2408 
2409   // Simplest case is that the operand needs to be promoted to XLenVT.
2410   if (Scalar.getValueType().bitsLE(XLenVT)) {
2411     // If the operand is a constant, sign extend to increase our chances
2412     // of being able to use a .vi instruction. ANY_EXTEND would become a
2413     // a zero extend and the simm5 check in isel would fail.
2414     // FIXME: Should we ignore the upper bits in isel instead?
2415     unsigned ExtOpc =
2416         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2417     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2418     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2419     // If VL is 1 and the scalar value won't benefit from immediate, we could
2420     // use vmv.s.x.
2421     if (isOneConstant(VL) &&
2422         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2423       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2424     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2425   }
2426 
2427   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2428          "Unexpected scalar for splat lowering!");
2429 
2430   if (isOneConstant(VL) && isNullConstant(Scalar))
2431     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2432                        DAG.getConstant(0, DL, XLenVT), VL);
2433 
2434   // Otherwise use the more complicated splatting algorithm.
2435   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2436 }
2437 
2438 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2439                                 const RISCVSubtarget &Subtarget) {
2440   // We need to be able to widen elements to the next larger integer type.
2441   if (VT.getScalarSizeInBits() >= Subtarget.getELEN())
2442     return false;
2443 
2444   int Size = Mask.size();
2445   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2446 
2447   int Srcs[] = {-1, -1};
2448   for (int i = 0; i != Size; ++i) {
2449     // Ignore undef elements.
2450     if (Mask[i] < 0)
2451       continue;
2452 
2453     // Is this an even or odd element.
2454     int Pol = i % 2;
2455 
2456     // Ensure we consistently use the same source for this element polarity.
2457     int Src = Mask[i] / Size;
2458     if (Srcs[Pol] < 0)
2459       Srcs[Pol] = Src;
2460     if (Srcs[Pol] != Src)
2461       return false;
2462 
2463     // Make sure the element within the source is appropriate for this element
2464     // in the destination.
2465     int Elt = Mask[i] % Size;
2466     if (Elt != i / 2)
2467       return false;
2468   }
2469 
2470   // We need to find a source for each polarity and they can't be the same.
2471   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2472     return false;
2473 
2474   // Swap the sources if the second source was in the even polarity.
2475   SwapSources = Srcs[0] > Srcs[1];
2476 
2477   return true;
2478 }
2479 
2480 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2481 /// and then extract the original number of elements from the rotated result.
2482 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2483 /// returned rotation amount is for a rotate right, where elements move from
2484 /// higher elements to lower elements. \p LoSrc indicates the first source
2485 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2486 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2487 /// 0 or 1 if a rotation is found.
2488 ///
2489 /// NOTE: We talk about rotate to the right which matches how bit shift and
2490 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2491 /// and the table below write vectors with the lowest elements on the left.
2492 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2493   int Size = Mask.size();
2494 
2495   // We need to detect various ways of spelling a rotation:
2496   //   [11, 12, 13, 14, 15,  0,  1,  2]
2497   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2498   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2499   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2500   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2501   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2502   int Rotation = 0;
2503   LoSrc = -1;
2504   HiSrc = -1;
2505   for (int i = 0; i != Size; ++i) {
2506     int M = Mask[i];
2507     if (M < 0)
2508       continue;
2509 
2510     // Determine where a rotate vector would have started.
2511     int StartIdx = i - (M % Size);
2512     // The identity rotation isn't interesting, stop.
2513     if (StartIdx == 0)
2514       return -1;
2515 
2516     // If we found the tail of a vector the rotation must be the missing
2517     // front. If we found the head of a vector, it must be how much of the
2518     // head.
2519     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2520 
2521     if (Rotation == 0)
2522       Rotation = CandidateRotation;
2523     else if (Rotation != CandidateRotation)
2524       // The rotations don't match, so we can't match this mask.
2525       return -1;
2526 
2527     // Compute which value this mask is pointing at.
2528     int MaskSrc = M < Size ? 0 : 1;
2529 
2530     // Compute which of the two target values this index should be assigned to.
2531     // This reflects whether the high elements are remaining or the low elemnts
2532     // are remaining.
2533     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2534 
2535     // Either set up this value if we've not encountered it before, or check
2536     // that it remains consistent.
2537     if (TargetSrc < 0)
2538       TargetSrc = MaskSrc;
2539     else if (TargetSrc != MaskSrc)
2540       // This may be a rotation, but it pulls from the inputs in some
2541       // unsupported interleaving.
2542       return -1;
2543   }
2544 
2545   // Check that we successfully analyzed the mask, and normalize the results.
2546   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2547   assert((LoSrc >= 0 || HiSrc >= 0) &&
2548          "Failed to find a rotated input vector!");
2549 
2550   return Rotation;
2551 }
2552 
2553 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2554                                    const RISCVSubtarget &Subtarget) {
2555   SDValue V1 = Op.getOperand(0);
2556   SDValue V2 = Op.getOperand(1);
2557   SDLoc DL(Op);
2558   MVT XLenVT = Subtarget.getXLenVT();
2559   MVT VT = Op.getSimpleValueType();
2560   unsigned NumElts = VT.getVectorNumElements();
2561   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2562 
2563   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2564 
2565   SDValue TrueMask, VL;
2566   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2567 
2568   if (SVN->isSplat()) {
2569     const int Lane = SVN->getSplatIndex();
2570     if (Lane >= 0) {
2571       MVT SVT = VT.getVectorElementType();
2572 
2573       // Turn splatted vector load into a strided load with an X0 stride.
2574       SDValue V = V1;
2575       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2576       // with undef.
2577       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2578       int Offset = Lane;
2579       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2580         int OpElements =
2581             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2582         V = V.getOperand(Offset / OpElements);
2583         Offset %= OpElements;
2584       }
2585 
2586       // We need to ensure the load isn't atomic or volatile.
2587       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2588         auto *Ld = cast<LoadSDNode>(V);
2589         Offset *= SVT.getStoreSize();
2590         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2591                                                    TypeSize::Fixed(Offset), DL);
2592 
2593         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2594         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2595           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2596           SDValue IntID =
2597               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2598           SDValue Ops[] = {Ld->getChain(),
2599                            IntID,
2600                            DAG.getUNDEF(ContainerVT),
2601                            NewAddr,
2602                            DAG.getRegister(RISCV::X0, XLenVT),
2603                            VL};
2604           SDValue NewLoad = DAG.getMemIntrinsicNode(
2605               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2606               DAG.getMachineFunction().getMachineMemOperand(
2607                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2608           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2609           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2610         }
2611 
2612         // Otherwise use a scalar load and splat. This will give the best
2613         // opportunity to fold a splat into the operation. ISel can turn it into
2614         // the x0 strided load if we aren't able to fold away the select.
2615         if (SVT.isFloatingPoint())
2616           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2617                           Ld->getPointerInfo().getWithOffset(Offset),
2618                           Ld->getOriginalAlign(),
2619                           Ld->getMemOperand()->getFlags());
2620         else
2621           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2622                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2623                              Ld->getOriginalAlign(),
2624                              Ld->getMemOperand()->getFlags());
2625         DAG.makeEquivalentMemoryOrdering(Ld, V);
2626 
2627         unsigned Opc =
2628             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2629         SDValue Splat =
2630             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2631         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2632       }
2633 
2634       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2635       assert(Lane < (int)NumElts && "Unexpected lane!");
2636       SDValue Gather =
2637           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2638                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2639       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2640     }
2641   }
2642 
2643   ArrayRef<int> Mask = SVN->getMask();
2644 
2645   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2646   // be undef which can be handled with a single SLIDEDOWN/UP.
2647   int LoSrc, HiSrc;
2648   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2649   if (Rotation > 0) {
2650     SDValue LoV, HiV;
2651     if (LoSrc >= 0) {
2652       LoV = LoSrc == 0 ? V1 : V2;
2653       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2654     }
2655     if (HiSrc >= 0) {
2656       HiV = HiSrc == 0 ? V1 : V2;
2657       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2658     }
2659 
2660     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2661     // to slide LoV up by (NumElts - Rotation).
2662     unsigned InvRotate = NumElts - Rotation;
2663 
2664     SDValue Res = DAG.getUNDEF(ContainerVT);
2665     if (HiV) {
2666       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2667       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2668       // causes multiple vsetvlis in some test cases such as lowering
2669       // reduce.mul
2670       SDValue DownVL = VL;
2671       if (LoV)
2672         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2673       Res =
2674           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2675                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2676     }
2677     if (LoV)
2678       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2679                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2680 
2681     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2682   }
2683 
2684   // Detect an interleave shuffle and lower to
2685   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2686   bool SwapSources;
2687   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2688     // Swap sources if needed.
2689     if (SwapSources)
2690       std::swap(V1, V2);
2691 
2692     // Extract the lower half of the vectors.
2693     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2694     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2695                      DAG.getConstant(0, DL, XLenVT));
2696     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2697                      DAG.getConstant(0, DL, XLenVT));
2698 
2699     // Double the element width and halve the number of elements in an int type.
2700     unsigned EltBits = VT.getScalarSizeInBits();
2701     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2702     MVT WideIntVT =
2703         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2704     // Convert this to a scalable vector. We need to base this on the
2705     // destination size to ensure there's always a type with a smaller LMUL.
2706     MVT WideIntContainerVT =
2707         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2708 
2709     // Convert sources to scalable vectors with the same element count as the
2710     // larger type.
2711     MVT HalfContainerVT = MVT::getVectorVT(
2712         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2713     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2714     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2715 
2716     // Cast sources to integer.
2717     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2718     MVT IntHalfVT =
2719         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2720     V1 = DAG.getBitcast(IntHalfVT, V1);
2721     V2 = DAG.getBitcast(IntHalfVT, V2);
2722 
2723     // Freeze V2 since we use it twice and we need to be sure that the add and
2724     // multiply see the same value.
2725     V2 = DAG.getFreeze(V2);
2726 
2727     // Recreate TrueMask using the widened type's element count.
2728     MVT MaskVT =
2729         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2730     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2731 
2732     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2733     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2734                               V2, TrueMask, VL);
2735     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2736     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2737                                      DAG.getUNDEF(IntHalfVT),
2738                                      DAG.getAllOnesConstant(DL, XLenVT));
2739     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2740                                    V2, Multiplier, TrueMask, VL);
2741     // Add the new copies to our previous addition giving us 2^eltbits copies of
2742     // V2. This is equivalent to shifting V2 left by eltbits. This should
2743     // combine with the vwmulu.vv above to form vwmaccu.vv.
2744     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2745                       TrueMask, VL);
2746     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2747     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2748     // vector VT.
2749     ContainerVT =
2750         MVT::getVectorVT(VT.getVectorElementType(),
2751                          WideIntContainerVT.getVectorElementCount() * 2);
2752     Add = DAG.getBitcast(ContainerVT, Add);
2753     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2754   }
2755 
2756   // Detect shuffles which can be re-expressed as vector selects; these are
2757   // shuffles in which each element in the destination is taken from an element
2758   // at the corresponding index in either source vectors.
2759   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2760     int MaskIndex = MaskIdx.value();
2761     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2762   });
2763 
2764   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2765 
2766   SmallVector<SDValue> MaskVals;
2767   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2768   // merged with a second vrgather.
2769   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2770 
2771   // By default we preserve the original operand order, and use a mask to
2772   // select LHS as true and RHS as false. However, since RVV vector selects may
2773   // feature splats but only on the LHS, we may choose to invert our mask and
2774   // instead select between RHS and LHS.
2775   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2776   bool InvertMask = IsSelect == SwapOps;
2777 
2778   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2779   // half.
2780   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2781 
2782   // Now construct the mask that will be used by the vselect or blended
2783   // vrgather operation. For vrgathers, construct the appropriate indices into
2784   // each vector.
2785   for (int MaskIndex : Mask) {
2786     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2787     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2788     if (!IsSelect) {
2789       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2790       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2791                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2792                                      : DAG.getUNDEF(XLenVT));
2793       GatherIndicesRHS.push_back(
2794           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2795                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2796       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2797         ++LHSIndexCounts[MaskIndex];
2798       if (!IsLHSOrUndefIndex)
2799         ++RHSIndexCounts[MaskIndex - NumElts];
2800     }
2801   }
2802 
2803   if (SwapOps) {
2804     std::swap(V1, V2);
2805     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2806   }
2807 
2808   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2809   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2810   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2811 
2812   if (IsSelect)
2813     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2814 
2815   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2816     // On such a large vector we're unable to use i8 as the index type.
2817     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2818     // may involve vector splitting if we're already at LMUL=8, or our
2819     // user-supplied maximum fixed-length LMUL.
2820     return SDValue();
2821   }
2822 
2823   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2824   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2825   MVT IndexVT = VT.changeTypeToInteger();
2826   // Since we can't introduce illegal index types at this stage, use i16 and
2827   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2828   // than XLenVT.
2829   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2830     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2831     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2832   }
2833 
2834   MVT IndexContainerVT =
2835       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2836 
2837   SDValue Gather;
2838   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2839   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2840   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2841     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2842                               Subtarget);
2843   } else {
2844     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2845     // If only one index is used, we can use a "splat" vrgather.
2846     // TODO: We can splat the most-common index and fix-up any stragglers, if
2847     // that's beneficial.
2848     if (LHSIndexCounts.size() == 1) {
2849       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2850       Gather =
2851           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2852                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2853     } else {
2854       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2855       LHSIndices =
2856           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2857 
2858       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2859                            TrueMask, VL);
2860     }
2861   }
2862 
2863   // If a second vector operand is used by this shuffle, blend it in with an
2864   // additional vrgather.
2865   if (!V2.isUndef()) {
2866     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2867     // If only one index is used, we can use a "splat" vrgather.
2868     // TODO: We can splat the most-common index and fix-up any stragglers, if
2869     // that's beneficial.
2870     if (RHSIndexCounts.size() == 1) {
2871       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2872       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2873                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2874     } else {
2875       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2876       RHSIndices =
2877           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2878       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2879                        VL);
2880     }
2881 
2882     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2883     SelectMask =
2884         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2885 
2886     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2887                          Gather, VL);
2888   }
2889 
2890   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2891 }
2892 
2893 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2894   // Support splats for any type. These should type legalize well.
2895   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2896     return true;
2897 
2898   // Only support legal VTs for other shuffles for now.
2899   if (!isTypeLegal(VT))
2900     return false;
2901 
2902   MVT SVT = VT.getSimpleVT();
2903 
2904   bool SwapSources;
2905   int LoSrc, HiSrc;
2906   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2907          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2908 }
2909 
2910 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2911                                      SDLoc DL, SelectionDAG &DAG,
2912                                      const RISCVSubtarget &Subtarget) {
2913   if (VT.isScalableVector())
2914     return DAG.getFPExtendOrRound(Op, DL, VT);
2915   assert(VT.isFixedLengthVector() &&
2916          "Unexpected value type for RVV FP extend/round lowering");
2917   SDValue Mask, VL;
2918   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2919   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2920                         ? RISCVISD::FP_EXTEND_VL
2921                         : RISCVISD::FP_ROUND_VL;
2922   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2923 }
2924 
2925 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2926 // the exponent.
2927 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2928   MVT VT = Op.getSimpleValueType();
2929   unsigned EltSize = VT.getScalarSizeInBits();
2930   SDValue Src = Op.getOperand(0);
2931   SDLoc DL(Op);
2932 
2933   // We need a FP type that can represent the value.
2934   // TODO: Use f16 for i8 when possible?
2935   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2936   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2937 
2938   // Legal types should have been checked in the RISCVTargetLowering
2939   // constructor.
2940   // TODO: Splitting may make sense in some cases.
2941   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2942          "Expected legal float type!");
2943 
2944   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2945   // The trailing zero count is equal to log2 of this single bit value.
2946   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2947     SDValue Neg =
2948         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2949     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2950   }
2951 
2952   // We have a legal FP type, convert to it.
2953   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2954   // Bitcast to integer and shift the exponent to the LSB.
2955   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2956   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2957   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2958   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2959                               DAG.getConstant(ShiftAmt, DL, IntVT));
2960   // Truncate back to original type to allow vnsrl.
2961   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2962   // The exponent contains log2 of the value in biased form.
2963   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2964 
2965   // For trailing zeros, we just need to subtract the bias.
2966   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2967     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2968                        DAG.getConstant(ExponentBias, DL, VT));
2969 
2970   // For leading zeros, we need to remove the bias and convert from log2 to
2971   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2972   unsigned Adjust = ExponentBias + (EltSize - 1);
2973   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2974 }
2975 
2976 // While RVV has alignment restrictions, we should always be able to load as a
2977 // legal equivalently-sized byte-typed vector instead. This method is
2978 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2979 // the load is already correctly-aligned, it returns SDValue().
2980 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2981                                                     SelectionDAG &DAG) const {
2982   auto *Load = cast<LoadSDNode>(Op);
2983   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2984 
2985   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2986                                      Load->getMemoryVT(),
2987                                      *Load->getMemOperand()))
2988     return SDValue();
2989 
2990   SDLoc DL(Op);
2991   MVT VT = Op.getSimpleValueType();
2992   unsigned EltSizeBits = VT.getScalarSizeInBits();
2993   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2994          "Unexpected unaligned RVV load type");
2995   MVT NewVT =
2996       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2997   assert(NewVT.isValid() &&
2998          "Expecting equally-sized RVV vector types to be legal");
2999   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
3000                           Load->getPointerInfo(), Load->getOriginalAlign(),
3001                           Load->getMemOperand()->getFlags());
3002   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
3003 }
3004 
3005 // While RVV has alignment restrictions, we should always be able to store as a
3006 // legal equivalently-sized byte-typed vector instead. This method is
3007 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
3008 // returns SDValue() if the store is already correctly aligned.
3009 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
3010                                                      SelectionDAG &DAG) const {
3011   auto *Store = cast<StoreSDNode>(Op);
3012   assert(Store && Store->getValue().getValueType().isVector() &&
3013          "Expected vector store");
3014 
3015   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3016                                      Store->getMemoryVT(),
3017                                      *Store->getMemOperand()))
3018     return SDValue();
3019 
3020   SDLoc DL(Op);
3021   SDValue StoredVal = Store->getValue();
3022   MVT VT = StoredVal.getSimpleValueType();
3023   unsigned EltSizeBits = VT.getScalarSizeInBits();
3024   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3025          "Unexpected unaligned RVV store type");
3026   MVT NewVT =
3027       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3028   assert(NewVT.isValid() &&
3029          "Expecting equally-sized RVV vector types to be legal");
3030   StoredVal = DAG.getBitcast(NewVT, StoredVal);
3031   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
3032                       Store->getPointerInfo(), Store->getOriginalAlign(),
3033                       Store->getMemOperand()->getFlags());
3034 }
3035 
3036 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
3037                                             SelectionDAG &DAG) const {
3038   switch (Op.getOpcode()) {
3039   default:
3040     report_fatal_error("unimplemented operand");
3041   case ISD::GlobalAddress:
3042     return lowerGlobalAddress(Op, DAG);
3043   case ISD::BlockAddress:
3044     return lowerBlockAddress(Op, DAG);
3045   case ISD::ConstantPool:
3046     return lowerConstantPool(Op, DAG);
3047   case ISD::JumpTable:
3048     return lowerJumpTable(Op, DAG);
3049   case ISD::GlobalTLSAddress:
3050     return lowerGlobalTLSAddress(Op, DAG);
3051   case ISD::SELECT:
3052     return lowerSELECT(Op, DAG);
3053   case ISD::BRCOND:
3054     return lowerBRCOND(Op, DAG);
3055   case ISD::VASTART:
3056     return lowerVASTART(Op, DAG);
3057   case ISD::FRAMEADDR:
3058     return lowerFRAMEADDR(Op, DAG);
3059   case ISD::RETURNADDR:
3060     return lowerRETURNADDR(Op, DAG);
3061   case ISD::SHL_PARTS:
3062     return lowerShiftLeftParts(Op, DAG);
3063   case ISD::SRA_PARTS:
3064     return lowerShiftRightParts(Op, DAG, true);
3065   case ISD::SRL_PARTS:
3066     return lowerShiftRightParts(Op, DAG, false);
3067   case ISD::BITCAST: {
3068     SDLoc DL(Op);
3069     EVT VT = Op.getValueType();
3070     SDValue Op0 = Op.getOperand(0);
3071     EVT Op0VT = Op0.getValueType();
3072     MVT XLenVT = Subtarget.getXLenVT();
3073     if (VT.isFixedLengthVector()) {
3074       // We can handle fixed length vector bitcasts with a simple replacement
3075       // in isel.
3076       if (Op0VT.isFixedLengthVector())
3077         return Op;
3078       // When bitcasting from scalar to fixed-length vector, insert the scalar
3079       // into a one-element vector of the result type, and perform a vector
3080       // bitcast.
3081       if (!Op0VT.isVector()) {
3082         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3083         if (!isTypeLegal(BVT))
3084           return SDValue();
3085         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3086                                               DAG.getUNDEF(BVT), Op0,
3087                                               DAG.getConstant(0, DL, XLenVT)));
3088       }
3089       return SDValue();
3090     }
3091     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3092     // thus: bitcast the vector to a one-element vector type whose element type
3093     // is the same as the result type, and extract the first element.
3094     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3095       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3096       if (!isTypeLegal(BVT))
3097         return SDValue();
3098       SDValue BVec = DAG.getBitcast(BVT, Op0);
3099       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3100                          DAG.getConstant(0, DL, XLenVT));
3101     }
3102     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3103       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3104       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3105       return FPConv;
3106     }
3107     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3108         Subtarget.hasStdExtF()) {
3109       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3110       SDValue FPConv =
3111           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3112       return FPConv;
3113     }
3114     return SDValue();
3115   }
3116   case ISD::INTRINSIC_WO_CHAIN:
3117     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3118   case ISD::INTRINSIC_W_CHAIN:
3119     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3120   case ISD::INTRINSIC_VOID:
3121     return LowerINTRINSIC_VOID(Op, DAG);
3122   case ISD::BSWAP:
3123   case ISD::BITREVERSE: {
3124     MVT VT = Op.getSimpleValueType();
3125     SDLoc DL(Op);
3126     if (Subtarget.hasStdExtZbp()) {
3127       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3128       // Start with the maximum immediate value which is the bitwidth - 1.
3129       unsigned Imm = VT.getSizeInBits() - 1;
3130       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3131       if (Op.getOpcode() == ISD::BSWAP)
3132         Imm &= ~0x7U;
3133       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3134                          DAG.getConstant(Imm, DL, VT));
3135     }
3136     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3137     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3138     // Expand bitreverse to a bswap(rev8) followed by brev8.
3139     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3140     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3141     // as brev8 by an isel pattern.
3142     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3143                        DAG.getConstant(7, DL, VT));
3144   }
3145   case ISD::FSHL:
3146   case ISD::FSHR: {
3147     MVT VT = Op.getSimpleValueType();
3148     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3149     SDLoc DL(Op);
3150     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3151     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3152     // accidentally setting the extra bit.
3153     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3154     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3155                                 DAG.getConstant(ShAmtWidth, DL, VT));
3156     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3157     // instruction use different orders. fshl will return its first operand for
3158     // shift of zero, fshr will return its second operand. fsl and fsr both
3159     // return rs1 so the ISD nodes need to have different operand orders.
3160     // Shift amount is in rs2.
3161     SDValue Op0 = Op.getOperand(0);
3162     SDValue Op1 = Op.getOperand(1);
3163     unsigned Opc = RISCVISD::FSL;
3164     if (Op.getOpcode() == ISD::FSHR) {
3165       std::swap(Op0, Op1);
3166       Opc = RISCVISD::FSR;
3167     }
3168     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3169   }
3170   case ISD::TRUNCATE: {
3171     SDLoc DL(Op);
3172     MVT VT = Op.getSimpleValueType();
3173     // Only custom-lower vector truncates
3174     if (!VT.isVector())
3175       return Op;
3176 
3177     // Truncates to mask types are handled differently
3178     if (VT.getVectorElementType() == MVT::i1)
3179       return lowerVectorMaskTrunc(Op, DAG);
3180 
3181     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
3182     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
3183     // truncate by one power of two at a time.
3184     MVT DstEltVT = VT.getVectorElementType();
3185 
3186     SDValue Src = Op.getOperand(0);
3187     MVT SrcVT = Src.getSimpleValueType();
3188     MVT SrcEltVT = SrcVT.getVectorElementType();
3189 
3190     assert(DstEltVT.bitsLT(SrcEltVT) &&
3191            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
3192            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
3193            "Unexpected vector truncate lowering");
3194 
3195     MVT ContainerVT = SrcVT;
3196     if (SrcVT.isFixedLengthVector()) {
3197       ContainerVT = getContainerForFixedLengthVector(SrcVT);
3198       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3199     }
3200 
3201     SDValue Result = Src;
3202     SDValue Mask, VL;
3203     std::tie(Mask, VL) =
3204         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
3205     LLVMContext &Context = *DAG.getContext();
3206     const ElementCount Count = ContainerVT.getVectorElementCount();
3207     do {
3208       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
3209       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
3210       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
3211                            Mask, VL);
3212     } while (SrcEltVT != DstEltVT);
3213 
3214     if (SrcVT.isFixedLengthVector())
3215       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3216 
3217     return Result;
3218   }
3219   case ISD::ANY_EXTEND:
3220   case ISD::ZERO_EXTEND:
3221     if (Op.getOperand(0).getValueType().isVector() &&
3222         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3223       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3224     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3225   case ISD::SIGN_EXTEND:
3226     if (Op.getOperand(0).getValueType().isVector() &&
3227         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3228       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3229     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3230   case ISD::SPLAT_VECTOR_PARTS:
3231     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3232   case ISD::INSERT_VECTOR_ELT:
3233     return lowerINSERT_VECTOR_ELT(Op, DAG);
3234   case ISD::EXTRACT_VECTOR_ELT:
3235     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3236   case ISD::VSCALE: {
3237     MVT VT = Op.getSimpleValueType();
3238     SDLoc DL(Op);
3239     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3240     // We define our scalable vector types for lmul=1 to use a 64 bit known
3241     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3242     // vscale as VLENB / 8.
3243     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3244     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3245       report_fatal_error("Support for VLEN==32 is incomplete.");
3246     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3247       // We assume VLENB is a multiple of 8. We manually choose the best shift
3248       // here because SimplifyDemandedBits isn't always able to simplify it.
3249       uint64_t Val = Op.getConstantOperandVal(0);
3250       if (isPowerOf2_64(Val)) {
3251         uint64_t Log2 = Log2_64(Val);
3252         if (Log2 < 3)
3253           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3254                              DAG.getConstant(3 - Log2, DL, VT));
3255         if (Log2 > 3)
3256           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3257                              DAG.getConstant(Log2 - 3, DL, VT));
3258         return VLENB;
3259       }
3260       // If the multiplier is a multiple of 8, scale it down to avoid needing
3261       // to shift the VLENB value.
3262       if ((Val % 8) == 0)
3263         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3264                            DAG.getConstant(Val / 8, DL, VT));
3265     }
3266 
3267     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3268                                  DAG.getConstant(3, DL, VT));
3269     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3270   }
3271   case ISD::FPOWI: {
3272     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3273     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3274     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3275         Op.getOperand(1).getValueType() == MVT::i32) {
3276       SDLoc DL(Op);
3277       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3278       SDValue Powi =
3279           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3280       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3281                          DAG.getIntPtrConstant(0, DL));
3282     }
3283     return SDValue();
3284   }
3285   case ISD::FP_EXTEND: {
3286     // RVV can only do fp_extend to types double the size as the source. We
3287     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3288     // via f32.
3289     SDLoc DL(Op);
3290     MVT VT = Op.getSimpleValueType();
3291     SDValue Src = Op.getOperand(0);
3292     MVT SrcVT = Src.getSimpleValueType();
3293 
3294     // Prepare any fixed-length vector operands.
3295     MVT ContainerVT = VT;
3296     if (SrcVT.isFixedLengthVector()) {
3297       ContainerVT = getContainerForFixedLengthVector(VT);
3298       MVT SrcContainerVT =
3299           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3300       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3301     }
3302 
3303     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3304         SrcVT.getVectorElementType() != MVT::f16) {
3305       // For scalable vectors, we only need to close the gap between
3306       // vXf16->vXf64.
3307       if (!VT.isFixedLengthVector())
3308         return Op;
3309       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3310       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3311       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3312     }
3313 
3314     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3315     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3316     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3317         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3318 
3319     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3320                                            DL, DAG, Subtarget);
3321     if (VT.isFixedLengthVector())
3322       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3323     return Extend;
3324   }
3325   case ISD::FP_ROUND: {
3326     // RVV can only do fp_round to types half the size as the source. We
3327     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3328     // conversion instruction.
3329     SDLoc DL(Op);
3330     MVT VT = Op.getSimpleValueType();
3331     SDValue Src = Op.getOperand(0);
3332     MVT SrcVT = Src.getSimpleValueType();
3333 
3334     // Prepare any fixed-length vector operands.
3335     MVT ContainerVT = VT;
3336     if (VT.isFixedLengthVector()) {
3337       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3338       ContainerVT =
3339           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3340       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3341     }
3342 
3343     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3344         SrcVT.getVectorElementType() != MVT::f64) {
3345       // For scalable vectors, we only need to close the gap between
3346       // vXf64<->vXf16.
3347       if (!VT.isFixedLengthVector())
3348         return Op;
3349       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3350       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3351       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3352     }
3353 
3354     SDValue Mask, VL;
3355     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3356 
3357     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3358     SDValue IntermediateRound =
3359         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3360     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3361                                           DL, DAG, Subtarget);
3362 
3363     if (VT.isFixedLengthVector())
3364       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3365     return Round;
3366   }
3367   case ISD::FP_TO_SINT:
3368   case ISD::FP_TO_UINT:
3369   case ISD::SINT_TO_FP:
3370   case ISD::UINT_TO_FP: {
3371     // RVV can only do fp<->int conversions to types half/double the size as
3372     // the source. We custom-lower any conversions that do two hops into
3373     // sequences.
3374     MVT VT = Op.getSimpleValueType();
3375     if (!VT.isVector())
3376       return Op;
3377     SDLoc DL(Op);
3378     SDValue Src = Op.getOperand(0);
3379     MVT EltVT = VT.getVectorElementType();
3380     MVT SrcVT = Src.getSimpleValueType();
3381     MVT SrcEltVT = SrcVT.getVectorElementType();
3382     unsigned EltSize = EltVT.getSizeInBits();
3383     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3384     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3385            "Unexpected vector element types");
3386 
3387     bool IsInt2FP = SrcEltVT.isInteger();
3388     // Widening conversions
3389     if (EltSize > (2 * SrcEltSize)) {
3390       if (IsInt2FP) {
3391         // Do a regular integer sign/zero extension then convert to float.
3392         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize),
3393                                       VT.getVectorElementCount());
3394         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3395                                  ? ISD::ZERO_EXTEND
3396                                  : ISD::SIGN_EXTEND;
3397         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3398         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3399       }
3400       // FP2Int
3401       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3402       // Do one doubling fp_extend then complete the operation by converting
3403       // to int.
3404       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3405       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3406       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3407     }
3408 
3409     // Narrowing conversions
3410     if (SrcEltSize > (2 * EltSize)) {
3411       if (IsInt2FP) {
3412         // One narrowing int_to_fp, then an fp_round.
3413         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3414         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3415         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3416         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3417       }
3418       // FP2Int
3419       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3420       // representable by the integer, the result is poison.
3421       MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
3422                                     VT.getVectorElementCount());
3423       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3424       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3425     }
3426 
3427     // Scalable vectors can exit here. Patterns will handle equally-sized
3428     // conversions halving/doubling ones.
3429     if (!VT.isFixedLengthVector())
3430       return Op;
3431 
3432     // For fixed-length vectors we lower to a custom "VL" node.
3433     unsigned RVVOpc = 0;
3434     switch (Op.getOpcode()) {
3435     default:
3436       llvm_unreachable("Impossible opcode");
3437     case ISD::FP_TO_SINT:
3438       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3439       break;
3440     case ISD::FP_TO_UINT:
3441       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3442       break;
3443     case ISD::SINT_TO_FP:
3444       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3445       break;
3446     case ISD::UINT_TO_FP:
3447       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3448       break;
3449     }
3450 
3451     MVT ContainerVT, SrcContainerVT;
3452     // Derive the reference container type from the larger vector type.
3453     if (SrcEltSize > EltSize) {
3454       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3455       ContainerVT =
3456           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3457     } else {
3458       ContainerVT = getContainerForFixedLengthVector(VT);
3459       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3460     }
3461 
3462     SDValue Mask, VL;
3463     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3464 
3465     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3466     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3467     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3468   }
3469   case ISD::FP_TO_SINT_SAT:
3470   case ISD::FP_TO_UINT_SAT:
3471     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3472   case ISD::FTRUNC:
3473   case ISD::FCEIL:
3474   case ISD::FFLOOR:
3475     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3476   case ISD::FROUND:
3477     return lowerFROUND(Op, DAG);
3478   case ISD::VECREDUCE_ADD:
3479   case ISD::VECREDUCE_UMAX:
3480   case ISD::VECREDUCE_SMAX:
3481   case ISD::VECREDUCE_UMIN:
3482   case ISD::VECREDUCE_SMIN:
3483     return lowerVECREDUCE(Op, DAG);
3484   case ISD::VECREDUCE_AND:
3485   case ISD::VECREDUCE_OR:
3486   case ISD::VECREDUCE_XOR:
3487     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3488       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3489     return lowerVECREDUCE(Op, DAG);
3490   case ISD::VECREDUCE_FADD:
3491   case ISD::VECREDUCE_SEQ_FADD:
3492   case ISD::VECREDUCE_FMIN:
3493   case ISD::VECREDUCE_FMAX:
3494     return lowerFPVECREDUCE(Op, DAG);
3495   case ISD::VP_REDUCE_ADD:
3496   case ISD::VP_REDUCE_UMAX:
3497   case ISD::VP_REDUCE_SMAX:
3498   case ISD::VP_REDUCE_UMIN:
3499   case ISD::VP_REDUCE_SMIN:
3500   case ISD::VP_REDUCE_FADD:
3501   case ISD::VP_REDUCE_SEQ_FADD:
3502   case ISD::VP_REDUCE_FMIN:
3503   case ISD::VP_REDUCE_FMAX:
3504     return lowerVPREDUCE(Op, DAG);
3505   case ISD::VP_REDUCE_AND:
3506   case ISD::VP_REDUCE_OR:
3507   case ISD::VP_REDUCE_XOR:
3508     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3509       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3510     return lowerVPREDUCE(Op, DAG);
3511   case ISD::INSERT_SUBVECTOR:
3512     return lowerINSERT_SUBVECTOR(Op, DAG);
3513   case ISD::EXTRACT_SUBVECTOR:
3514     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3515   case ISD::STEP_VECTOR:
3516     return lowerSTEP_VECTOR(Op, DAG);
3517   case ISD::VECTOR_REVERSE:
3518     return lowerVECTOR_REVERSE(Op, DAG);
3519   case ISD::VECTOR_SPLICE:
3520     return lowerVECTOR_SPLICE(Op, DAG);
3521   case ISD::BUILD_VECTOR:
3522     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3523   case ISD::SPLAT_VECTOR:
3524     if (Op.getValueType().getVectorElementType() == MVT::i1)
3525       return lowerVectorMaskSplat(Op, DAG);
3526     return SDValue();
3527   case ISD::VECTOR_SHUFFLE:
3528     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3529   case ISD::CONCAT_VECTORS: {
3530     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3531     // better than going through the stack, as the default expansion does.
3532     SDLoc DL(Op);
3533     MVT VT = Op.getSimpleValueType();
3534     unsigned NumOpElts =
3535         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3536     SDValue Vec = DAG.getUNDEF(VT);
3537     for (const auto &OpIdx : enumerate(Op->ops())) {
3538       SDValue SubVec = OpIdx.value();
3539       // Don't insert undef subvectors.
3540       if (SubVec.isUndef())
3541         continue;
3542       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3543                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3544     }
3545     return Vec;
3546   }
3547   case ISD::LOAD:
3548     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3549       return V;
3550     if (Op.getValueType().isFixedLengthVector())
3551       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3552     return Op;
3553   case ISD::STORE:
3554     if (auto V = expandUnalignedRVVStore(Op, DAG))
3555       return V;
3556     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3557       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3558     return Op;
3559   case ISD::MLOAD:
3560   case ISD::VP_LOAD:
3561     return lowerMaskedLoad(Op, DAG);
3562   case ISD::MSTORE:
3563   case ISD::VP_STORE:
3564     return lowerMaskedStore(Op, DAG);
3565   case ISD::SETCC:
3566     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3567   case ISD::ADD:
3568     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3569   case ISD::SUB:
3570     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3571   case ISD::MUL:
3572     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3573   case ISD::MULHS:
3574     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3575   case ISD::MULHU:
3576     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3577   case ISD::AND:
3578     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3579                                               RISCVISD::AND_VL);
3580   case ISD::OR:
3581     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3582                                               RISCVISD::OR_VL);
3583   case ISD::XOR:
3584     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3585                                               RISCVISD::XOR_VL);
3586   case ISD::SDIV:
3587     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3588   case ISD::SREM:
3589     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3590   case ISD::UDIV:
3591     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3592   case ISD::UREM:
3593     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3594   case ISD::SHL:
3595   case ISD::SRA:
3596   case ISD::SRL:
3597     if (Op.getSimpleValueType().isFixedLengthVector())
3598       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3599     // This can be called for an i32 shift amount that needs to be promoted.
3600     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3601            "Unexpected custom legalisation");
3602     return SDValue();
3603   case ISD::SADDSAT:
3604     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3605   case ISD::UADDSAT:
3606     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3607   case ISD::SSUBSAT:
3608     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3609   case ISD::USUBSAT:
3610     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3611   case ISD::FADD:
3612     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3613   case ISD::FSUB:
3614     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3615   case ISD::FMUL:
3616     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3617   case ISD::FDIV:
3618     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3619   case ISD::FNEG:
3620     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3621   case ISD::FABS:
3622     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3623   case ISD::FSQRT:
3624     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3625   case ISD::FMA:
3626     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3627   case ISD::SMIN:
3628     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3629   case ISD::SMAX:
3630     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3631   case ISD::UMIN:
3632     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3633   case ISD::UMAX:
3634     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3635   case ISD::FMINNUM:
3636     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3637   case ISD::FMAXNUM:
3638     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3639   case ISD::ABS:
3640     return lowerABS(Op, DAG);
3641   case ISD::CTLZ_ZERO_UNDEF:
3642   case ISD::CTTZ_ZERO_UNDEF:
3643     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3644   case ISD::VSELECT:
3645     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3646   case ISD::FCOPYSIGN:
3647     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3648   case ISD::MGATHER:
3649   case ISD::VP_GATHER:
3650     return lowerMaskedGather(Op, DAG);
3651   case ISD::MSCATTER:
3652   case ISD::VP_SCATTER:
3653     return lowerMaskedScatter(Op, DAG);
3654   case ISD::FLT_ROUNDS_:
3655     return lowerGET_ROUNDING(Op, DAG);
3656   case ISD::SET_ROUNDING:
3657     return lowerSET_ROUNDING(Op, DAG);
3658   case ISD::VP_SELECT:
3659     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3660   case ISD::VP_MERGE:
3661     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3662   case ISD::VP_ADD:
3663     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3664   case ISD::VP_SUB:
3665     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3666   case ISD::VP_MUL:
3667     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3668   case ISD::VP_SDIV:
3669     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3670   case ISD::VP_UDIV:
3671     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3672   case ISD::VP_SREM:
3673     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3674   case ISD::VP_UREM:
3675     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3676   case ISD::VP_AND:
3677     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3678   case ISD::VP_OR:
3679     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3680   case ISD::VP_XOR:
3681     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3682   case ISD::VP_ASHR:
3683     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3684   case ISD::VP_LSHR:
3685     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3686   case ISD::VP_SHL:
3687     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3688   case ISD::VP_FADD:
3689     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3690   case ISD::VP_FSUB:
3691     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3692   case ISD::VP_FMUL:
3693     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3694   case ISD::VP_FDIV:
3695     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3696   case ISD::VP_FNEG:
3697     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3698   case ISD::VP_FMA:
3699     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3700   case ISD::VP_SEXT:
3701   case ISD::VP_ZEXT:
3702     if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
3703       return lowerVPExtMaskOp(Op, DAG);
3704     return lowerVPOp(Op, DAG,
3705                      Op.getOpcode() == ISD::VP_SEXT ? RISCVISD::VSEXT_VL
3706                                                     : RISCVISD::VZEXT_VL);
3707   case ISD::VP_FPTOSI:
3708     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL);
3709   case ISD::VP_FPTOUI:
3710     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL);
3711   case ISD::VP_SITOFP:
3712     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
3713   case ISD::VP_UITOFP:
3714     return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL);
3715   case ISD::VP_SETCC:
3716     return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL);
3717   }
3718 }
3719 
3720 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3721                              SelectionDAG &DAG, unsigned Flags) {
3722   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3723 }
3724 
3725 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3726                              SelectionDAG &DAG, unsigned Flags) {
3727   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3728                                    Flags);
3729 }
3730 
3731 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3732                              SelectionDAG &DAG, unsigned Flags) {
3733   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3734                                    N->getOffset(), Flags);
3735 }
3736 
3737 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3738                              SelectionDAG &DAG, unsigned Flags) {
3739   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3740 }
3741 
3742 template <class NodeTy>
3743 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3744                                      bool IsLocal) const {
3745   SDLoc DL(N);
3746   EVT Ty = getPointerTy(DAG.getDataLayout());
3747 
3748   if (isPositionIndependent()) {
3749     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3750     if (IsLocal)
3751       // Use PC-relative addressing to access the symbol. This generates the
3752       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3753       // %pcrel_lo(auipc)).
3754       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3755 
3756     // Use PC-relative addressing to access the GOT for this symbol, then load
3757     // the address from the GOT. This generates the pattern (PseudoLA sym),
3758     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3759     SDValue Load =
3760         SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3761     MachineFunction &MF = DAG.getMachineFunction();
3762     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3763         MachinePointerInfo::getGOT(MF),
3764         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3765             MachineMemOperand::MOInvariant,
3766         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3767     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3768     return Load;
3769   }
3770 
3771   switch (getTargetMachine().getCodeModel()) {
3772   default:
3773     report_fatal_error("Unsupported code model for lowering");
3774   case CodeModel::Small: {
3775     // Generate a sequence for accessing addresses within the first 2 GiB of
3776     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3777     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3778     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3779     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3780     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3781   }
3782   case CodeModel::Medium: {
3783     // Generate a sequence for accessing addresses within any 2GiB range within
3784     // the address space. This generates the pattern (PseudoLLA sym), which
3785     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3786     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3787     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3788   }
3789   }
3790 }
3791 
3792 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>(
3793     GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3794 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>(
3795     BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3796 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>(
3797     ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3798 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>(
3799     JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const;
3800 
3801 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3802                                                 SelectionDAG &DAG) const {
3803   SDLoc DL(Op);
3804   EVT Ty = Op.getValueType();
3805   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3806   int64_t Offset = N->getOffset();
3807   MVT XLenVT = Subtarget.getXLenVT();
3808 
3809   const GlobalValue *GV = N->getGlobal();
3810   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3811   SDValue Addr = getAddr(N, DAG, IsLocal);
3812 
3813   // In order to maximise the opportunity for common subexpression elimination,
3814   // emit a separate ADD node for the global address offset instead of folding
3815   // it in the global address node. Later peephole optimisations may choose to
3816   // fold it back in when profitable.
3817   if (Offset != 0)
3818     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3819                        DAG.getConstant(Offset, DL, XLenVT));
3820   return Addr;
3821 }
3822 
3823 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3824                                                SelectionDAG &DAG) const {
3825   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3826 
3827   return getAddr(N, DAG);
3828 }
3829 
3830 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3831                                                SelectionDAG &DAG) const {
3832   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3833 
3834   return getAddr(N, DAG);
3835 }
3836 
3837 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3838                                             SelectionDAG &DAG) const {
3839   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3840 
3841   return getAddr(N, DAG);
3842 }
3843 
3844 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3845                                               SelectionDAG &DAG,
3846                                               bool UseGOT) const {
3847   SDLoc DL(N);
3848   EVT Ty = getPointerTy(DAG.getDataLayout());
3849   const GlobalValue *GV = N->getGlobal();
3850   MVT XLenVT = Subtarget.getXLenVT();
3851 
3852   if (UseGOT) {
3853     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3854     // load the address from the GOT and add the thread pointer. This generates
3855     // the pattern (PseudoLA_TLS_IE sym), which expands to
3856     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3857     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3858     SDValue Load =
3859         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3860     MachineFunction &MF = DAG.getMachineFunction();
3861     MachineMemOperand *MemOp = MF.getMachineMemOperand(
3862         MachinePointerInfo::getGOT(MF),
3863         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
3864             MachineMemOperand::MOInvariant,
3865         LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
3866     DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp});
3867 
3868     // Add the thread pointer.
3869     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3870     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3871   }
3872 
3873   // Generate a sequence for accessing the address relative to the thread
3874   // pointer, with the appropriate adjustment for the thread pointer offset.
3875   // This generates the pattern
3876   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3877   SDValue AddrHi =
3878       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3879   SDValue AddrAdd =
3880       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3881   SDValue AddrLo =
3882       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3883 
3884   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3885   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3886   SDValue MNAdd = SDValue(
3887       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3888       0);
3889   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3890 }
3891 
3892 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3893                                                SelectionDAG &DAG) const {
3894   SDLoc DL(N);
3895   EVT Ty = getPointerTy(DAG.getDataLayout());
3896   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3897   const GlobalValue *GV = N->getGlobal();
3898 
3899   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3900   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3901   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3902   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3903   SDValue Load =
3904       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3905 
3906   // Prepare argument list to generate call.
3907   ArgListTy Args;
3908   ArgListEntry Entry;
3909   Entry.Node = Load;
3910   Entry.Ty = CallTy;
3911   Args.push_back(Entry);
3912 
3913   // Setup call to __tls_get_addr.
3914   TargetLowering::CallLoweringInfo CLI(DAG);
3915   CLI.setDebugLoc(DL)
3916       .setChain(DAG.getEntryNode())
3917       .setLibCallee(CallingConv::C, CallTy,
3918                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3919                     std::move(Args));
3920 
3921   return LowerCallTo(CLI).first;
3922 }
3923 
3924 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3925                                                    SelectionDAG &DAG) const {
3926   SDLoc DL(Op);
3927   EVT Ty = Op.getValueType();
3928   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3929   int64_t Offset = N->getOffset();
3930   MVT XLenVT = Subtarget.getXLenVT();
3931 
3932   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3933 
3934   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3935       CallingConv::GHC)
3936     report_fatal_error("In GHC calling convention TLS is not supported");
3937 
3938   SDValue Addr;
3939   switch (Model) {
3940   case TLSModel::LocalExec:
3941     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3942     break;
3943   case TLSModel::InitialExec:
3944     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3945     break;
3946   case TLSModel::LocalDynamic:
3947   case TLSModel::GeneralDynamic:
3948     Addr = getDynamicTLSAddr(N, DAG);
3949     break;
3950   }
3951 
3952   // In order to maximise the opportunity for common subexpression elimination,
3953   // emit a separate ADD node for the global address offset instead of folding
3954   // it in the global address node. Later peephole optimisations may choose to
3955   // fold it back in when profitable.
3956   if (Offset != 0)
3957     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3958                        DAG.getConstant(Offset, DL, XLenVT));
3959   return Addr;
3960 }
3961 
3962 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3963   SDValue CondV = Op.getOperand(0);
3964   SDValue TrueV = Op.getOperand(1);
3965   SDValue FalseV = Op.getOperand(2);
3966   SDLoc DL(Op);
3967   MVT VT = Op.getSimpleValueType();
3968   MVT XLenVT = Subtarget.getXLenVT();
3969 
3970   // Lower vector SELECTs to VSELECTs by splatting the condition.
3971   if (VT.isVector()) {
3972     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3973     SDValue CondSplat = VT.isScalableVector()
3974                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3975                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3976     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3977   }
3978 
3979   // If the result type is XLenVT and CondV is the output of a SETCC node
3980   // which also operated on XLenVT inputs, then merge the SETCC node into the
3981   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3982   // compare+branch instructions. i.e.:
3983   // (select (setcc lhs, rhs, cc), truev, falsev)
3984   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3985   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3986       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3987     SDValue LHS = CondV.getOperand(0);
3988     SDValue RHS = CondV.getOperand(1);
3989     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3990     ISD::CondCode CCVal = CC->get();
3991 
3992     // Special case for a select of 2 constants that have a diffence of 1.
3993     // Normally this is done by DAGCombine, but if the select is introduced by
3994     // type legalization or op legalization, we miss it. Restricting to SETLT
3995     // case for now because that is what signed saturating add/sub need.
3996     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3997     // but we would probably want to swap the true/false values if the condition
3998     // is SETGE/SETLE to avoid an XORI.
3999     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
4000         CCVal == ISD::SETLT) {
4001       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
4002       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
4003       if (TrueVal - 1 == FalseVal)
4004         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
4005       if (TrueVal + 1 == FalseVal)
4006         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
4007     }
4008 
4009     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
4010 
4011     SDValue TargetCC = DAG.getCondCode(CCVal);
4012     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
4013     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
4014   }
4015 
4016   // Otherwise:
4017   // (select condv, truev, falsev)
4018   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
4019   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4020   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
4021 
4022   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
4023 
4024   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
4025 }
4026 
4027 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4028   SDValue CondV = Op.getOperand(1);
4029   SDLoc DL(Op);
4030   MVT XLenVT = Subtarget.getXLenVT();
4031 
4032   if (CondV.getOpcode() == ISD::SETCC &&
4033       CondV.getOperand(0).getValueType() == XLenVT) {
4034     SDValue LHS = CondV.getOperand(0);
4035     SDValue RHS = CondV.getOperand(1);
4036     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
4037 
4038     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
4039 
4040     SDValue TargetCC = DAG.getCondCode(CCVal);
4041     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4042                        LHS, RHS, TargetCC, Op.getOperand(2));
4043   }
4044 
4045   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
4046                      CondV, DAG.getConstant(0, DL, XLenVT),
4047                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
4048 }
4049 
4050 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
4051   MachineFunction &MF = DAG.getMachineFunction();
4052   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
4053 
4054   SDLoc DL(Op);
4055   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
4056                                  getPointerTy(MF.getDataLayout()));
4057 
4058   // vastart just stores the address of the VarArgsFrameIndex slot into the
4059   // memory location argument.
4060   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4061   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
4062                       MachinePointerInfo(SV));
4063 }
4064 
4065 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
4066                                             SelectionDAG &DAG) const {
4067   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4068   MachineFunction &MF = DAG.getMachineFunction();
4069   MachineFrameInfo &MFI = MF.getFrameInfo();
4070   MFI.setFrameAddressIsTaken(true);
4071   Register FrameReg = RI.getFrameRegister(MF);
4072   int XLenInBytes = Subtarget.getXLen() / 8;
4073 
4074   EVT VT = Op.getValueType();
4075   SDLoc DL(Op);
4076   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
4077   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4078   while (Depth--) {
4079     int Offset = -(XLenInBytes * 2);
4080     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
4081                               DAG.getIntPtrConstant(Offset, DL));
4082     FrameAddr =
4083         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
4084   }
4085   return FrameAddr;
4086 }
4087 
4088 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
4089                                              SelectionDAG &DAG) const {
4090   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4091   MachineFunction &MF = DAG.getMachineFunction();
4092   MachineFrameInfo &MFI = MF.getFrameInfo();
4093   MFI.setReturnAddressIsTaken(true);
4094   MVT XLenVT = Subtarget.getXLenVT();
4095   int XLenInBytes = Subtarget.getXLen() / 8;
4096 
4097   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4098     return SDValue();
4099 
4100   EVT VT = Op.getValueType();
4101   SDLoc DL(Op);
4102   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4103   if (Depth) {
4104     int Off = -XLenInBytes;
4105     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4106     SDValue Offset = DAG.getConstant(Off, DL, VT);
4107     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4108                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4109                        MachinePointerInfo());
4110   }
4111 
4112   // Return the value of the return address register, marking it an implicit
4113   // live-in.
4114   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
4115   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
4116 }
4117 
4118 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
4119                                                  SelectionDAG &DAG) const {
4120   SDLoc DL(Op);
4121   SDValue Lo = Op.getOperand(0);
4122   SDValue Hi = Op.getOperand(1);
4123   SDValue Shamt = Op.getOperand(2);
4124   EVT VT = Lo.getValueType();
4125 
4126   // if Shamt-XLEN < 0: // Shamt < XLEN
4127   //   Lo = Lo << Shamt
4128   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
4129   // else:
4130   //   Lo = 0
4131   //   Hi = Lo << (Shamt-XLEN)
4132 
4133   SDValue Zero = DAG.getConstant(0, DL, VT);
4134   SDValue One = DAG.getConstant(1, DL, VT);
4135   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4136   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4137   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4138   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4139 
4140   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
4141   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
4142   SDValue ShiftRightLo =
4143       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
4144   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
4145   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
4146   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
4147 
4148   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4149 
4150   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
4151   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4152 
4153   SDValue Parts[2] = {Lo, Hi};
4154   return DAG.getMergeValues(Parts, DL);
4155 }
4156 
4157 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
4158                                                   bool IsSRA) const {
4159   SDLoc DL(Op);
4160   SDValue Lo = Op.getOperand(0);
4161   SDValue Hi = Op.getOperand(1);
4162   SDValue Shamt = Op.getOperand(2);
4163   EVT VT = Lo.getValueType();
4164 
4165   // SRA expansion:
4166   //   if Shamt-XLEN < 0: // Shamt < XLEN
4167   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4168   //     Hi = Hi >>s Shamt
4169   //   else:
4170   //     Lo = Hi >>s (Shamt-XLEN);
4171   //     Hi = Hi >>s (XLEN-1)
4172   //
4173   // SRL expansion:
4174   //   if Shamt-XLEN < 0: // Shamt < XLEN
4175   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4176   //     Hi = Hi >>u Shamt
4177   //   else:
4178   //     Lo = Hi >>u (Shamt-XLEN);
4179   //     Hi = 0;
4180 
4181   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4182 
4183   SDValue Zero = DAG.getConstant(0, DL, VT);
4184   SDValue One = DAG.getConstant(1, DL, VT);
4185   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4186   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4187   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4188   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4189 
4190   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4191   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4192   SDValue ShiftLeftHi =
4193       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4194   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4195   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4196   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4197   SDValue HiFalse =
4198       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4199 
4200   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4201 
4202   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4203   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4204 
4205   SDValue Parts[2] = {Lo, Hi};
4206   return DAG.getMergeValues(Parts, DL);
4207 }
4208 
4209 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4210 // legal equivalently-sized i8 type, so we can use that as a go-between.
4211 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4212                                                   SelectionDAG &DAG) const {
4213   SDLoc DL(Op);
4214   MVT VT = Op.getSimpleValueType();
4215   SDValue SplatVal = Op.getOperand(0);
4216   // All-zeros or all-ones splats are handled specially.
4217   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4218     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4219     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4220   }
4221   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4222     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4223     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4224   }
4225   MVT XLenVT = Subtarget.getXLenVT();
4226   assert(SplatVal.getValueType() == XLenVT &&
4227          "Unexpected type for i1 splat value");
4228   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4229   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4230                          DAG.getConstant(1, DL, XLenVT));
4231   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4232   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4233   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4234 }
4235 
4236 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4237 // illegal (currently only vXi64 RV32).
4238 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4239 // them to VMV_V_X_VL.
4240 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4241                                                      SelectionDAG &DAG) const {
4242   SDLoc DL(Op);
4243   MVT VecVT = Op.getSimpleValueType();
4244   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4245          "Unexpected SPLAT_VECTOR_PARTS lowering");
4246 
4247   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4248   SDValue Lo = Op.getOperand(0);
4249   SDValue Hi = Op.getOperand(1);
4250 
4251   if (VecVT.isFixedLengthVector()) {
4252     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4253     SDLoc DL(Op);
4254     SDValue Mask, VL;
4255     std::tie(Mask, VL) =
4256         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4257 
4258     SDValue Res =
4259         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4260     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4261   }
4262 
4263   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4264     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4265     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4266     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4267     // node in order to try and match RVV vector/scalar instructions.
4268     if ((LoC >> 31) == HiC)
4269       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4270                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4271   }
4272 
4273   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4274   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4275       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4276       Hi.getConstantOperandVal(1) == 31)
4277     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4278                        DAG.getRegister(RISCV::X0, MVT::i32));
4279 
4280   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4281   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4282                      DAG.getUNDEF(VecVT), Lo, Hi,
4283                      DAG.getRegister(RISCV::X0, MVT::i32));
4284 }
4285 
4286 // Custom-lower extensions from mask vectors by using a vselect either with 1
4287 // for zero/any-extension or -1 for sign-extension:
4288 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4289 // Note that any-extension is lowered identically to zero-extension.
4290 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4291                                                 int64_t ExtTrueVal) const {
4292   SDLoc DL(Op);
4293   MVT VecVT = Op.getSimpleValueType();
4294   SDValue Src = Op.getOperand(0);
4295   // Only custom-lower extensions from mask types
4296   assert(Src.getValueType().isVector() &&
4297          Src.getValueType().getVectorElementType() == MVT::i1);
4298 
4299   if (VecVT.isScalableVector()) {
4300     SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
4301     SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
4302     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4303   }
4304 
4305   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4306   MVT I1ContainerVT =
4307       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4308 
4309   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4310 
4311   SDValue Mask, VL;
4312   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4313 
4314   MVT XLenVT = Subtarget.getXLenVT();
4315   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4316   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4317 
4318   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4319                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4320   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4321                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4322   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4323                                SplatTrueVal, SplatZero, VL);
4324 
4325   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4326 }
4327 
4328 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4329     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4330   MVT ExtVT = Op.getSimpleValueType();
4331   // Only custom-lower extensions from fixed-length vector types.
4332   if (!ExtVT.isFixedLengthVector())
4333     return Op;
4334   MVT VT = Op.getOperand(0).getSimpleValueType();
4335   // Grab the canonical container type for the extended type. Infer the smaller
4336   // type from that to ensure the same number of vector elements, as we know
4337   // the LMUL will be sufficient to hold the smaller type.
4338   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4339   // Get the extended container type manually to ensure the same number of
4340   // vector elements between source and dest.
4341   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4342                                      ContainerExtVT.getVectorElementCount());
4343 
4344   SDValue Op1 =
4345       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4346 
4347   SDLoc DL(Op);
4348   SDValue Mask, VL;
4349   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4350 
4351   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4352 
4353   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4354 }
4355 
4356 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4357 // setcc operation:
4358 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4359 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
4360                                                   SelectionDAG &DAG) const {
4361   SDLoc DL(Op);
4362   EVT MaskVT = Op.getValueType();
4363   // Only expect to custom-lower truncations to mask types
4364   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4365          "Unexpected type for vector mask lowering");
4366   SDValue Src = Op.getOperand(0);
4367   MVT VecVT = Src.getSimpleValueType();
4368 
4369   // If this is a fixed vector, we need to convert it to a scalable vector.
4370   MVT ContainerVT = VecVT;
4371   if (VecVT.isFixedLengthVector()) {
4372     ContainerVT = getContainerForFixedLengthVector(VecVT);
4373     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4374   }
4375 
4376   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4377   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4378 
4379   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4380                          DAG.getUNDEF(ContainerVT), SplatOne);
4381   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4382                           DAG.getUNDEF(ContainerVT), SplatZero);
4383 
4384   if (VecVT.isScalableVector()) {
4385     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
4386     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
4387   }
4388 
4389   SDValue Mask, VL;
4390   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4391 
4392   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4393   SDValue Trunc =
4394       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4395   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4396                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4397   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4398 }
4399 
4400 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4401 // first position of a vector, and that vector is slid up to the insert index.
4402 // By limiting the active vector length to index+1 and merging with the
4403 // original vector (with an undisturbed tail policy for elements >= VL), we
4404 // achieve the desired result of leaving all elements untouched except the one
4405 // at VL-1, which is replaced with the desired value.
4406 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4407                                                     SelectionDAG &DAG) const {
4408   SDLoc DL(Op);
4409   MVT VecVT = Op.getSimpleValueType();
4410   SDValue Vec = Op.getOperand(0);
4411   SDValue Val = Op.getOperand(1);
4412   SDValue Idx = Op.getOperand(2);
4413 
4414   if (VecVT.getVectorElementType() == MVT::i1) {
4415     // FIXME: For now we just promote to an i8 vector and insert into that,
4416     // but this is probably not optimal.
4417     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4418     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4419     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4420     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4421   }
4422 
4423   MVT ContainerVT = VecVT;
4424   // If the operand is a fixed-length vector, convert to a scalable one.
4425   if (VecVT.isFixedLengthVector()) {
4426     ContainerVT = getContainerForFixedLengthVector(VecVT);
4427     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4428   }
4429 
4430   MVT XLenVT = Subtarget.getXLenVT();
4431 
4432   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4433   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4434   // Even i64-element vectors on RV32 can be lowered without scalar
4435   // legalization if the most-significant 32 bits of the value are not affected
4436   // by the sign-extension of the lower 32 bits.
4437   // TODO: We could also catch sign extensions of a 32-bit value.
4438   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4439     const auto *CVal = cast<ConstantSDNode>(Val);
4440     if (isInt<32>(CVal->getSExtValue())) {
4441       IsLegalInsert = true;
4442       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4443     }
4444   }
4445 
4446   SDValue Mask, VL;
4447   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4448 
4449   SDValue ValInVec;
4450 
4451   if (IsLegalInsert) {
4452     unsigned Opc =
4453         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4454     if (isNullConstant(Idx)) {
4455       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4456       if (!VecVT.isFixedLengthVector())
4457         return Vec;
4458       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4459     }
4460     ValInVec =
4461         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4462   } else {
4463     // On RV32, i64-element vectors must be specially handled to place the
4464     // value at element 0, by using two vslide1up instructions in sequence on
4465     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4466     // this.
4467     SDValue One = DAG.getConstant(1, DL, XLenVT);
4468     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4469     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4470     MVT I32ContainerVT =
4471         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4472     SDValue I32Mask =
4473         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4474     // Limit the active VL to two.
4475     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4476     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4477     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4478     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4479                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4480     // First slide in the hi value, then the lo in underneath it.
4481     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4482                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4483                            I32Mask, InsertI64VL);
4484     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4485                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4486                            I32Mask, InsertI64VL);
4487     // Bitcast back to the right container type.
4488     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4489   }
4490 
4491   // Now that the value is in a vector, slide it into position.
4492   SDValue InsertVL =
4493       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4494   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4495                                 ValInVec, Idx, Mask, InsertVL);
4496   if (!VecVT.isFixedLengthVector())
4497     return Slideup;
4498   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4499 }
4500 
4501 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4502 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4503 // types this is done using VMV_X_S to allow us to glean information about the
4504 // sign bits of the result.
4505 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4506                                                      SelectionDAG &DAG) const {
4507   SDLoc DL(Op);
4508   SDValue Idx = Op.getOperand(1);
4509   SDValue Vec = Op.getOperand(0);
4510   EVT EltVT = Op.getValueType();
4511   MVT VecVT = Vec.getSimpleValueType();
4512   MVT XLenVT = Subtarget.getXLenVT();
4513 
4514   if (VecVT.getVectorElementType() == MVT::i1) {
4515     if (VecVT.isFixedLengthVector()) {
4516       unsigned NumElts = VecVT.getVectorNumElements();
4517       if (NumElts >= 8) {
4518         MVT WideEltVT;
4519         unsigned WidenVecLen;
4520         SDValue ExtractElementIdx;
4521         SDValue ExtractBitIdx;
4522         unsigned MaxEEW = Subtarget.getELEN();
4523         MVT LargestEltVT = MVT::getIntegerVT(
4524             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4525         if (NumElts <= LargestEltVT.getSizeInBits()) {
4526           assert(isPowerOf2_32(NumElts) &&
4527                  "the number of elements should be power of 2");
4528           WideEltVT = MVT::getIntegerVT(NumElts);
4529           WidenVecLen = 1;
4530           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4531           ExtractBitIdx = Idx;
4532         } else {
4533           WideEltVT = LargestEltVT;
4534           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4535           // extract element index = index / element width
4536           ExtractElementIdx = DAG.getNode(
4537               ISD::SRL, DL, XLenVT, Idx,
4538               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4539           // mask bit index = index % element width
4540           ExtractBitIdx = DAG.getNode(
4541               ISD::AND, DL, XLenVT, Idx,
4542               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4543         }
4544         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4545         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4546         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4547                                          Vec, ExtractElementIdx);
4548         // Extract the bit from GPR.
4549         SDValue ShiftRight =
4550             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4551         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4552                            DAG.getConstant(1, DL, XLenVT));
4553       }
4554     }
4555     // Otherwise, promote to an i8 vector and extract from that.
4556     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4557     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4558     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4559   }
4560 
4561   // If this is a fixed vector, we need to convert it to a scalable vector.
4562   MVT ContainerVT = VecVT;
4563   if (VecVT.isFixedLengthVector()) {
4564     ContainerVT = getContainerForFixedLengthVector(VecVT);
4565     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4566   }
4567 
4568   // If the index is 0, the vector is already in the right position.
4569   if (!isNullConstant(Idx)) {
4570     // Use a VL of 1 to avoid processing more elements than we need.
4571     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4572     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4573     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4574     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4575                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4576   }
4577 
4578   if (!EltVT.isInteger()) {
4579     // Floating-point extracts are handled in TableGen.
4580     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4581                        DAG.getConstant(0, DL, XLenVT));
4582   }
4583 
4584   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4585   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4586 }
4587 
4588 // Some RVV intrinsics may claim that they want an integer operand to be
4589 // promoted or expanded.
4590 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
4591                                            const RISCVSubtarget &Subtarget) {
4592   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4593           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4594          "Unexpected opcode");
4595 
4596   if (!Subtarget.hasVInstructions())
4597     return SDValue();
4598 
4599   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4600   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4601   SDLoc DL(Op);
4602 
4603   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4604       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4605   if (!II || !II->hasScalarOperand())
4606     return SDValue();
4607 
4608   unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
4609   assert(SplatOp < Op.getNumOperands());
4610 
4611   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4612   SDValue &ScalarOp = Operands[SplatOp];
4613   MVT OpVT = ScalarOp.getSimpleValueType();
4614   MVT XLenVT = Subtarget.getXLenVT();
4615 
4616   // If this isn't a scalar, or its type is XLenVT we're done.
4617   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4618     return SDValue();
4619 
4620   // Simplest case is that the operand needs to be promoted to XLenVT.
4621   if (OpVT.bitsLT(XLenVT)) {
4622     // If the operand is a constant, sign extend to increase our chances
4623     // of being able to use a .vi instruction. ANY_EXTEND would become a
4624     // a zero extend and the simm5 check in isel would fail.
4625     // FIXME: Should we ignore the upper bits in isel instead?
4626     unsigned ExtOpc =
4627         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4628     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4629     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4630   }
4631 
4632   // Use the previous operand to get the vXi64 VT. The result might be a mask
4633   // VT for compares. Using the previous operand assumes that the previous
4634   // operand will never have a smaller element size than a scalar operand and
4635   // that a widening operation never uses SEW=64.
4636   // NOTE: If this fails the below assert, we can probably just find the
4637   // element count from any operand or result and use it to construct the VT.
4638   assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
4639   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4640 
4641   // The more complex case is when the scalar is larger than XLenVT.
4642   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4643          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4644 
4645   // If this is a sign-extended 32-bit value, we can truncate it and rely on the
4646   // instruction to sign-extend since SEW>XLEN.
4647   if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
4648     ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
4649     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4650   }
4651 
4652   switch (IntNo) {
4653   case Intrinsic::riscv_vslide1up:
4654   case Intrinsic::riscv_vslide1down:
4655   case Intrinsic::riscv_vslide1up_mask:
4656   case Intrinsic::riscv_vslide1down_mask: {
4657     // We need to special case these when the scalar is larger than XLen.
4658     unsigned NumOps = Op.getNumOperands();
4659     bool IsMasked = NumOps == 7;
4660 
4661     // Convert the vector source to the equivalent nxvXi32 vector.
4662     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4663     SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
4664 
4665     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4666                                    DAG.getConstant(0, DL, XLenVT));
4667     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
4668                                    DAG.getConstant(1, DL, XLenVT));
4669 
4670     // Double the VL since we halved SEW.
4671     SDValue AVL = getVLOperand(Op);
4672     SDValue I32VL;
4673 
4674     // Optimize for constant AVL
4675     if (isa<ConstantSDNode>(AVL)) {
4676       unsigned EltSize = VT.getScalarSizeInBits();
4677       unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
4678 
4679       unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
4680       unsigned MaxVLMAX =
4681           RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
4682 
4683       unsigned VectorBitsMin = Subtarget.getRealMinVLen();
4684       unsigned MinVLMAX =
4685           RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
4686 
4687       uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
4688       if (AVLInt <= MinVLMAX) {
4689         I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
4690       } else if (AVLInt >= 2 * MaxVLMAX) {
4691         // Just set vl to VLMAX in this situation
4692         RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
4693         SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4694         unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
4695         SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4696         SDValue SETVLMAX = DAG.getTargetConstant(
4697             Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
4698         I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
4699                             LMUL);
4700       } else {
4701         // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
4702         // is related to the hardware implementation.
4703         // So let the following code handle
4704       }
4705     }
4706     if (!I32VL) {
4707       RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
4708       SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
4709       unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
4710       SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
4711       SDValue SETVL =
4712           DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
4713       // Using vsetvli instruction to get actually used length which related to
4714       // the hardware implementation
4715       SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
4716                                SEW, LMUL);
4717       I32VL =
4718           DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4719     }
4720 
4721     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4722     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, I32VL);
4723 
4724     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4725     // instructions.
4726     SDValue Passthru;
4727     if (IsMasked)
4728       Passthru = DAG.getUNDEF(I32VT);
4729     else
4730       Passthru = DAG.getBitcast(I32VT, Operands[1]);
4731 
4732     if (IntNo == Intrinsic::riscv_vslide1up ||
4733         IntNo == Intrinsic::riscv_vslide1up_mask) {
4734       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4735                         ScalarHi, I32Mask, I32VL);
4736       Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4737                         ScalarLo, I32Mask, I32VL);
4738     } else {
4739       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4740                         ScalarLo, I32Mask, I32VL);
4741       Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4742                         ScalarHi, I32Mask, I32VL);
4743     }
4744 
4745     // Convert back to nxvXi64.
4746     Vec = DAG.getBitcast(VT, Vec);
4747 
4748     if (!IsMasked)
4749       return Vec;
4750     // Apply mask after the operation.
4751     SDValue Mask = Operands[NumOps - 3];
4752     SDValue MaskedOff = Operands[1];
4753     // Assume Policy operand is the last operand.
4754     uint64_t Policy =
4755         cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
4756     // We don't need to select maskedoff if it's undef.
4757     if (MaskedOff.isUndef())
4758       return Vec;
4759     // TAMU
4760     if (Policy == RISCVII::TAIL_AGNOSTIC)
4761       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4762                          AVL);
4763     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4764     // It's fine because vmerge does not care mask policy.
4765     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
4766                        AVL);
4767   }
4768   }
4769 
4770   // We need to convert the scalar to a splat vector.
4771   SDValue VL = getVLOperand(Op);
4772   assert(VL.getValueType() == XLenVT);
4773   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4774   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4775 }
4776 
4777 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4778                                                      SelectionDAG &DAG) const {
4779   unsigned IntNo = Op.getConstantOperandVal(0);
4780   SDLoc DL(Op);
4781   MVT XLenVT = Subtarget.getXLenVT();
4782 
4783   switch (IntNo) {
4784   default:
4785     break; // Don't custom lower most intrinsics.
4786   case Intrinsic::thread_pointer: {
4787     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4788     return DAG.getRegister(RISCV::X4, PtrVT);
4789   }
4790   case Intrinsic::riscv_orc_b:
4791   case Intrinsic::riscv_brev8: {
4792     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4793     unsigned Opc =
4794         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4795     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4796                        DAG.getConstant(7, DL, XLenVT));
4797   }
4798   case Intrinsic::riscv_grev:
4799   case Intrinsic::riscv_gorc: {
4800     unsigned Opc =
4801         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4802     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4803   }
4804   case Intrinsic::riscv_zip:
4805   case Intrinsic::riscv_unzip: {
4806     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4807     // For i32 the immediate is 15. For i64 the immediate is 31.
4808     unsigned Opc =
4809         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4810     unsigned BitWidth = Op.getValueSizeInBits();
4811     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4812     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4813                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4814   }
4815   case Intrinsic::riscv_shfl:
4816   case Intrinsic::riscv_unshfl: {
4817     unsigned Opc =
4818         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4819     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4820   }
4821   case Intrinsic::riscv_bcompress:
4822   case Intrinsic::riscv_bdecompress: {
4823     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4824                                                        : RISCVISD::BDECOMPRESS;
4825     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4826   }
4827   case Intrinsic::riscv_bfp:
4828     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4829                        Op.getOperand(2));
4830   case Intrinsic::riscv_fsl:
4831     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4832                        Op.getOperand(2), Op.getOperand(3));
4833   case Intrinsic::riscv_fsr:
4834     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4835                        Op.getOperand(2), Op.getOperand(3));
4836   case Intrinsic::riscv_vmv_x_s:
4837     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4838     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4839                        Op.getOperand(1));
4840   case Intrinsic::riscv_vmv_v_x:
4841     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4842                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4843                             Subtarget);
4844   case Intrinsic::riscv_vfmv_v_f:
4845     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4846                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4847   case Intrinsic::riscv_vmv_s_x: {
4848     SDValue Scalar = Op.getOperand(2);
4849 
4850     if (Scalar.getValueType().bitsLE(XLenVT)) {
4851       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4852       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4853                          Op.getOperand(1), Scalar, Op.getOperand(3));
4854     }
4855 
4856     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4857 
4858     // This is an i64 value that lives in two scalar registers. We have to
4859     // insert this in a convoluted way. First we build vXi64 splat containing
4860     // the two values that we assemble using some bit math. Next we'll use
4861     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4862     // to merge element 0 from our splat into the source vector.
4863     // FIXME: This is probably not the best way to do this, but it is
4864     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4865     // point.
4866     //   sw lo, (a0)
4867     //   sw hi, 4(a0)
4868     //   vlse vX, (a0)
4869     //
4870     //   vid.v      vVid
4871     //   vmseq.vx   mMask, vVid, 0
4872     //   vmerge.vvm vDest, vSrc, vVal, mMask
4873     MVT VT = Op.getSimpleValueType();
4874     SDValue Vec = Op.getOperand(1);
4875     SDValue VL = getVLOperand(Op);
4876 
4877     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4878     if (Op.getOperand(1).isUndef())
4879       return SplattedVal;
4880     SDValue SplattedIdx =
4881         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4882                     DAG.getConstant(0, DL, MVT::i32), VL);
4883 
4884     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4885     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4886     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4887     SDValue SelectCond =
4888         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4889                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4890     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4891                        Vec, VL);
4892   }
4893   }
4894 
4895   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4896 }
4897 
4898 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4899                                                     SelectionDAG &DAG) const {
4900   unsigned IntNo = Op.getConstantOperandVal(1);
4901   switch (IntNo) {
4902   default:
4903     break;
4904   case Intrinsic::riscv_masked_strided_load: {
4905     SDLoc DL(Op);
4906     MVT XLenVT = Subtarget.getXLenVT();
4907 
4908     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4909     // the selection of the masked intrinsics doesn't do this for us.
4910     SDValue Mask = Op.getOperand(5);
4911     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4912 
4913     MVT VT = Op->getSimpleValueType(0);
4914     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4915 
4916     SDValue PassThru = Op.getOperand(2);
4917     if (!IsUnmasked) {
4918       MVT MaskVT =
4919           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4920       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4921       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4922     }
4923 
4924     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4925 
4926     SDValue IntID = DAG.getTargetConstant(
4927         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4928         XLenVT);
4929 
4930     auto *Load = cast<MemIntrinsicSDNode>(Op);
4931     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4932     if (IsUnmasked)
4933       Ops.push_back(DAG.getUNDEF(ContainerVT));
4934     else
4935       Ops.push_back(PassThru);
4936     Ops.push_back(Op.getOperand(3)); // Ptr
4937     Ops.push_back(Op.getOperand(4)); // Stride
4938     if (!IsUnmasked)
4939       Ops.push_back(Mask);
4940     Ops.push_back(VL);
4941     if (!IsUnmasked) {
4942       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4943       Ops.push_back(Policy);
4944     }
4945 
4946     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4947     SDValue Result =
4948         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4949                                 Load->getMemoryVT(), Load->getMemOperand());
4950     SDValue Chain = Result.getValue(1);
4951     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4952     return DAG.getMergeValues({Result, Chain}, DL);
4953   }
4954   case Intrinsic::riscv_seg2_load:
4955   case Intrinsic::riscv_seg3_load:
4956   case Intrinsic::riscv_seg4_load:
4957   case Intrinsic::riscv_seg5_load:
4958   case Intrinsic::riscv_seg6_load:
4959   case Intrinsic::riscv_seg7_load:
4960   case Intrinsic::riscv_seg8_load: {
4961     SDLoc DL(Op);
4962     static const Intrinsic::ID VlsegInts[7] = {
4963         Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
4964         Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
4965         Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
4966         Intrinsic::riscv_vlseg8};
4967     unsigned NF = Op->getNumValues() - 1;
4968     assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
4969     MVT XLenVT = Subtarget.getXLenVT();
4970     MVT VT = Op->getSimpleValueType(0);
4971     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4972 
4973     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4974     SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
4975     auto *Load = cast<MemIntrinsicSDNode>(Op);
4976     SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
4977     ContainerVTs.push_back(MVT::Other);
4978     SDVTList VTs = DAG.getVTList(ContainerVTs);
4979     SDValue Result =
4980         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs,
4981                                 {Load->getChain(), IntID, Op.getOperand(2), VL},
4982                                 Load->getMemoryVT(), Load->getMemOperand());
4983     SmallVector<SDValue, 9> Results;
4984     for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
4985       Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
4986                                                   DAG, Subtarget));
4987     Results.push_back(Result.getValue(NF));
4988     return DAG.getMergeValues(Results, DL);
4989   }
4990   }
4991 
4992   return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
4993 }
4994 
4995 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4996                                                  SelectionDAG &DAG) const {
4997   unsigned IntNo = Op.getConstantOperandVal(1);
4998   switch (IntNo) {
4999   default:
5000     break;
5001   case Intrinsic::riscv_masked_strided_store: {
5002     SDLoc DL(Op);
5003     MVT XLenVT = Subtarget.getXLenVT();
5004 
5005     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
5006     // the selection of the masked intrinsics doesn't do this for us.
5007     SDValue Mask = Op.getOperand(5);
5008     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5009 
5010     SDValue Val = Op.getOperand(2);
5011     MVT VT = Val.getSimpleValueType();
5012     MVT ContainerVT = getContainerForFixedLengthVector(VT);
5013 
5014     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5015     if (!IsUnmasked) {
5016       MVT MaskVT =
5017           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5018       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5019     }
5020 
5021     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5022 
5023     SDValue IntID = DAG.getTargetConstant(
5024         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
5025         XLenVT);
5026 
5027     auto *Store = cast<MemIntrinsicSDNode>(Op);
5028     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
5029     Ops.push_back(Val);
5030     Ops.push_back(Op.getOperand(3)); // Ptr
5031     Ops.push_back(Op.getOperand(4)); // Stride
5032     if (!IsUnmasked)
5033       Ops.push_back(Mask);
5034     Ops.push_back(VL);
5035 
5036     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
5037                                    Ops, Store->getMemoryVT(),
5038                                    Store->getMemOperand());
5039   }
5040   }
5041 
5042   return SDValue();
5043 }
5044 
5045 static MVT getLMUL1VT(MVT VT) {
5046   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
5047          "Unexpected vector MVT");
5048   return MVT::getScalableVectorVT(
5049       VT.getVectorElementType(),
5050       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
5051 }
5052 
5053 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
5054   switch (ISDOpcode) {
5055   default:
5056     llvm_unreachable("Unhandled reduction");
5057   case ISD::VECREDUCE_ADD:
5058     return RISCVISD::VECREDUCE_ADD_VL;
5059   case ISD::VECREDUCE_UMAX:
5060     return RISCVISD::VECREDUCE_UMAX_VL;
5061   case ISD::VECREDUCE_SMAX:
5062     return RISCVISD::VECREDUCE_SMAX_VL;
5063   case ISD::VECREDUCE_UMIN:
5064     return RISCVISD::VECREDUCE_UMIN_VL;
5065   case ISD::VECREDUCE_SMIN:
5066     return RISCVISD::VECREDUCE_SMIN_VL;
5067   case ISD::VECREDUCE_AND:
5068     return RISCVISD::VECREDUCE_AND_VL;
5069   case ISD::VECREDUCE_OR:
5070     return RISCVISD::VECREDUCE_OR_VL;
5071   case ISD::VECREDUCE_XOR:
5072     return RISCVISD::VECREDUCE_XOR_VL;
5073   }
5074 }
5075 
5076 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
5077                                                          SelectionDAG &DAG,
5078                                                          bool IsVP) const {
5079   SDLoc DL(Op);
5080   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
5081   MVT VecVT = Vec.getSimpleValueType();
5082   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
5083           Op.getOpcode() == ISD::VECREDUCE_OR ||
5084           Op.getOpcode() == ISD::VECREDUCE_XOR ||
5085           Op.getOpcode() == ISD::VP_REDUCE_AND ||
5086           Op.getOpcode() == ISD::VP_REDUCE_OR ||
5087           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
5088          "Unexpected reduction lowering");
5089 
5090   MVT XLenVT = Subtarget.getXLenVT();
5091   assert(Op.getValueType() == XLenVT &&
5092          "Expected reduction output to be legalized to XLenVT");
5093 
5094   MVT ContainerVT = VecVT;
5095   if (VecVT.isFixedLengthVector()) {
5096     ContainerVT = getContainerForFixedLengthVector(VecVT);
5097     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5098   }
5099 
5100   SDValue Mask, VL;
5101   if (IsVP) {
5102     Mask = Op.getOperand(2);
5103     VL = Op.getOperand(3);
5104   } else {
5105     std::tie(Mask, VL) =
5106         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5107   }
5108 
5109   unsigned BaseOpc;
5110   ISD::CondCode CC;
5111   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5112 
5113   switch (Op.getOpcode()) {
5114   default:
5115     llvm_unreachable("Unhandled reduction");
5116   case ISD::VECREDUCE_AND:
5117   case ISD::VP_REDUCE_AND: {
5118     // vcpop ~x == 0
5119     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5120     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5121     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5122     CC = ISD::SETEQ;
5123     BaseOpc = ISD::AND;
5124     break;
5125   }
5126   case ISD::VECREDUCE_OR:
5127   case ISD::VP_REDUCE_OR:
5128     // vcpop x != 0
5129     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5130     CC = ISD::SETNE;
5131     BaseOpc = ISD::OR;
5132     break;
5133   case ISD::VECREDUCE_XOR:
5134   case ISD::VP_REDUCE_XOR: {
5135     // ((vcpop x) & 1) != 0
5136     SDValue One = DAG.getConstant(1, DL, XLenVT);
5137     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5138     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5139     CC = ISD::SETNE;
5140     BaseOpc = ISD::XOR;
5141     break;
5142   }
5143   }
5144 
5145   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5146 
5147   if (!IsVP)
5148     return SetCC;
5149 
5150   // Now include the start value in the operation.
5151   // Note that we must return the start value when no elements are operated
5152   // upon. The vcpop instructions we've emitted in each case above will return
5153   // 0 for an inactive vector, and so we've already received the neutral value:
5154   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5155   // can simply include the start value.
5156   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5157 }
5158 
5159 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5160                                             SelectionDAG &DAG) const {
5161   SDLoc DL(Op);
5162   SDValue Vec = Op.getOperand(0);
5163   EVT VecEVT = Vec.getValueType();
5164 
5165   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5166 
5167   // Due to ordering in legalize types we may have a vector type that needs to
5168   // be split. Do that manually so we can get down to a legal type.
5169   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5170          TargetLowering::TypeSplitVector) {
5171     SDValue Lo, Hi;
5172     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5173     VecEVT = Lo.getValueType();
5174     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5175   }
5176 
5177   // TODO: The type may need to be widened rather than split. Or widened before
5178   // it can be split.
5179   if (!isTypeLegal(VecEVT))
5180     return SDValue();
5181 
5182   MVT VecVT = VecEVT.getSimpleVT();
5183   MVT VecEltVT = VecVT.getVectorElementType();
5184   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5185 
5186   MVT ContainerVT = VecVT;
5187   if (VecVT.isFixedLengthVector()) {
5188     ContainerVT = getContainerForFixedLengthVector(VecVT);
5189     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5190   }
5191 
5192   MVT M1VT = getLMUL1VT(ContainerVT);
5193   MVT XLenVT = Subtarget.getXLenVT();
5194 
5195   SDValue Mask, VL;
5196   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5197 
5198   SDValue NeutralElem =
5199       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5200   SDValue IdentitySplat =
5201       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5202                        M1VT, DL, DAG, Subtarget);
5203   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5204                                   IdentitySplat, Mask, VL);
5205   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5206                              DAG.getConstant(0, DL, XLenVT));
5207   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5208 }
5209 
5210 // Given a reduction op, this function returns the matching reduction opcode,
5211 // the vector SDValue and the scalar SDValue required to lower this to a
5212 // RISCVISD node.
5213 static std::tuple<unsigned, SDValue, SDValue>
5214 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5215   SDLoc DL(Op);
5216   auto Flags = Op->getFlags();
5217   unsigned Opcode = Op.getOpcode();
5218   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5219   switch (Opcode) {
5220   default:
5221     llvm_unreachable("Unhandled reduction");
5222   case ISD::VECREDUCE_FADD: {
5223     // Use positive zero if we can. It is cheaper to materialize.
5224     SDValue Zero =
5225         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5226     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5227   }
5228   case ISD::VECREDUCE_SEQ_FADD:
5229     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5230                            Op.getOperand(0));
5231   case ISD::VECREDUCE_FMIN:
5232     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5233                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5234   case ISD::VECREDUCE_FMAX:
5235     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5236                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5237   }
5238 }
5239 
5240 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5241                                               SelectionDAG &DAG) const {
5242   SDLoc DL(Op);
5243   MVT VecEltVT = Op.getSimpleValueType();
5244 
5245   unsigned RVVOpcode;
5246   SDValue VectorVal, ScalarVal;
5247   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5248       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5249   MVT VecVT = VectorVal.getSimpleValueType();
5250 
5251   MVT ContainerVT = VecVT;
5252   if (VecVT.isFixedLengthVector()) {
5253     ContainerVT = getContainerForFixedLengthVector(VecVT);
5254     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5255   }
5256 
5257   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5258   MVT XLenVT = Subtarget.getXLenVT();
5259 
5260   SDValue Mask, VL;
5261   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5262 
5263   SDValue ScalarSplat =
5264       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5265                        M1VT, DL, DAG, Subtarget);
5266   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5267                                   VectorVal, ScalarSplat, Mask, VL);
5268   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5269                      DAG.getConstant(0, DL, XLenVT));
5270 }
5271 
5272 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5273   switch (ISDOpcode) {
5274   default:
5275     llvm_unreachable("Unhandled reduction");
5276   case ISD::VP_REDUCE_ADD:
5277     return RISCVISD::VECREDUCE_ADD_VL;
5278   case ISD::VP_REDUCE_UMAX:
5279     return RISCVISD::VECREDUCE_UMAX_VL;
5280   case ISD::VP_REDUCE_SMAX:
5281     return RISCVISD::VECREDUCE_SMAX_VL;
5282   case ISD::VP_REDUCE_UMIN:
5283     return RISCVISD::VECREDUCE_UMIN_VL;
5284   case ISD::VP_REDUCE_SMIN:
5285     return RISCVISD::VECREDUCE_SMIN_VL;
5286   case ISD::VP_REDUCE_AND:
5287     return RISCVISD::VECREDUCE_AND_VL;
5288   case ISD::VP_REDUCE_OR:
5289     return RISCVISD::VECREDUCE_OR_VL;
5290   case ISD::VP_REDUCE_XOR:
5291     return RISCVISD::VECREDUCE_XOR_VL;
5292   case ISD::VP_REDUCE_FADD:
5293     return RISCVISD::VECREDUCE_FADD_VL;
5294   case ISD::VP_REDUCE_SEQ_FADD:
5295     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5296   case ISD::VP_REDUCE_FMAX:
5297     return RISCVISD::VECREDUCE_FMAX_VL;
5298   case ISD::VP_REDUCE_FMIN:
5299     return RISCVISD::VECREDUCE_FMIN_VL;
5300   }
5301 }
5302 
5303 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5304                                            SelectionDAG &DAG) const {
5305   SDLoc DL(Op);
5306   SDValue Vec = Op.getOperand(1);
5307   EVT VecEVT = Vec.getValueType();
5308 
5309   // TODO: The type may need to be widened rather than split. Or widened before
5310   // it can be split.
5311   if (!isTypeLegal(VecEVT))
5312     return SDValue();
5313 
5314   MVT VecVT = VecEVT.getSimpleVT();
5315   MVT VecEltVT = VecVT.getVectorElementType();
5316   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5317 
5318   MVT ContainerVT = VecVT;
5319   if (VecVT.isFixedLengthVector()) {
5320     ContainerVT = getContainerForFixedLengthVector(VecVT);
5321     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5322   }
5323 
5324   SDValue VL = Op.getOperand(3);
5325   SDValue Mask = Op.getOperand(2);
5326 
5327   MVT M1VT = getLMUL1VT(ContainerVT);
5328   MVT XLenVT = Subtarget.getXLenVT();
5329   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5330 
5331   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5332                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5333                                         DL, DAG, Subtarget);
5334   SDValue Reduction =
5335       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5336   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5337                              DAG.getConstant(0, DL, XLenVT));
5338   if (!VecVT.isInteger())
5339     return Elt0;
5340   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5341 }
5342 
5343 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5344                                                    SelectionDAG &DAG) const {
5345   SDValue Vec = Op.getOperand(0);
5346   SDValue SubVec = Op.getOperand(1);
5347   MVT VecVT = Vec.getSimpleValueType();
5348   MVT SubVecVT = SubVec.getSimpleValueType();
5349 
5350   SDLoc DL(Op);
5351   MVT XLenVT = Subtarget.getXLenVT();
5352   unsigned OrigIdx = Op.getConstantOperandVal(2);
5353   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5354 
5355   // We don't have the ability to slide mask vectors up indexed by their i1
5356   // elements; the smallest we can do is i8. Often we are able to bitcast to
5357   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5358   // into a scalable one, we might not necessarily have enough scalable
5359   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5360   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5361       (OrigIdx != 0 || !Vec.isUndef())) {
5362     if (VecVT.getVectorMinNumElements() >= 8 &&
5363         SubVecVT.getVectorMinNumElements() >= 8) {
5364       assert(OrigIdx % 8 == 0 && "Invalid index");
5365       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5366              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5367              "Unexpected mask vector lowering");
5368       OrigIdx /= 8;
5369       SubVecVT =
5370           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5371                            SubVecVT.isScalableVector());
5372       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5373                                VecVT.isScalableVector());
5374       Vec = DAG.getBitcast(VecVT, Vec);
5375       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5376     } else {
5377       // We can't slide this mask vector up indexed by its i1 elements.
5378       // This poses a problem when we wish to insert a scalable vector which
5379       // can't be re-expressed as a larger type. Just choose the slow path and
5380       // extend to a larger type, then truncate back down.
5381       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5382       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5383       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5384       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5385       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5386                         Op.getOperand(2));
5387       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5388       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5389     }
5390   }
5391 
5392   // If the subvector vector is a fixed-length type, we cannot use subregister
5393   // manipulation to simplify the codegen; we don't know which register of a
5394   // LMUL group contains the specific subvector as we only know the minimum
5395   // register size. Therefore we must slide the vector group up the full
5396   // amount.
5397   if (SubVecVT.isFixedLengthVector()) {
5398     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5399       return Op;
5400     MVT ContainerVT = VecVT;
5401     if (VecVT.isFixedLengthVector()) {
5402       ContainerVT = getContainerForFixedLengthVector(VecVT);
5403       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5404     }
5405     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5406                          DAG.getUNDEF(ContainerVT), SubVec,
5407                          DAG.getConstant(0, DL, XLenVT));
5408     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5409       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5410       return DAG.getBitcast(Op.getValueType(), SubVec);
5411     }
5412     SDValue Mask =
5413         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5414     // Set the vector length to only the number of elements we care about. Note
5415     // that for slideup this includes the offset.
5416     SDValue VL =
5417         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5418     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5419     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5420                                   SubVec, SlideupAmt, Mask, VL);
5421     if (VecVT.isFixedLengthVector())
5422       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5423     return DAG.getBitcast(Op.getValueType(), Slideup);
5424   }
5425 
5426   unsigned SubRegIdx, RemIdx;
5427   std::tie(SubRegIdx, RemIdx) =
5428       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5429           VecVT, SubVecVT, OrigIdx, TRI);
5430 
5431   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5432   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5433                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5434                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5435 
5436   // 1. If the Idx has been completely eliminated and this subvector's size is
5437   // a vector register or a multiple thereof, or the surrounding elements are
5438   // undef, then this is a subvector insert which naturally aligns to a vector
5439   // register. These can easily be handled using subregister manipulation.
5440   // 2. If the subvector is smaller than a vector register, then the insertion
5441   // must preserve the undisturbed elements of the register. We do this by
5442   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5443   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5444   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5445   // LMUL=1 type back into the larger vector (resolving to another subregister
5446   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5447   // to avoid allocating a large register group to hold our subvector.
5448   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5449     return Op;
5450 
5451   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5452   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5453   // (in our case undisturbed). This means we can set up a subvector insertion
5454   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5455   // size of the subvector.
5456   MVT InterSubVT = VecVT;
5457   SDValue AlignedExtract = Vec;
5458   unsigned AlignedIdx = OrigIdx - RemIdx;
5459   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5460     InterSubVT = getLMUL1VT(VecVT);
5461     // Extract a subvector equal to the nearest full vector register type. This
5462     // should resolve to a EXTRACT_SUBREG instruction.
5463     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5464                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5465   }
5466 
5467   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5468   // For scalable vectors this must be further multiplied by vscale.
5469   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5470 
5471   SDValue Mask, VL;
5472   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5473 
5474   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5475   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5476   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5477   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5478 
5479   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5480                        DAG.getUNDEF(InterSubVT), SubVec,
5481                        DAG.getConstant(0, DL, XLenVT));
5482 
5483   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5484                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5485 
5486   // If required, insert this subvector back into the correct vector register.
5487   // This should resolve to an INSERT_SUBREG instruction.
5488   if (VecVT.bitsGT(InterSubVT))
5489     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5490                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5491 
5492   // We might have bitcast from a mask type: cast back to the original type if
5493   // required.
5494   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5495 }
5496 
5497 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5498                                                     SelectionDAG &DAG) const {
5499   SDValue Vec = Op.getOperand(0);
5500   MVT SubVecVT = Op.getSimpleValueType();
5501   MVT VecVT = Vec.getSimpleValueType();
5502 
5503   SDLoc DL(Op);
5504   MVT XLenVT = Subtarget.getXLenVT();
5505   unsigned OrigIdx = Op.getConstantOperandVal(1);
5506   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5507 
5508   // We don't have the ability to slide mask vectors down indexed by their i1
5509   // elements; the smallest we can do is i8. Often we are able to bitcast to
5510   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5511   // from a scalable one, we might not necessarily have enough scalable
5512   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5513   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5514     if (VecVT.getVectorMinNumElements() >= 8 &&
5515         SubVecVT.getVectorMinNumElements() >= 8) {
5516       assert(OrigIdx % 8 == 0 && "Invalid index");
5517       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5518              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5519              "Unexpected mask vector lowering");
5520       OrigIdx /= 8;
5521       SubVecVT =
5522           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5523                            SubVecVT.isScalableVector());
5524       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5525                                VecVT.isScalableVector());
5526       Vec = DAG.getBitcast(VecVT, Vec);
5527     } else {
5528       // We can't slide this mask vector down, indexed by its i1 elements.
5529       // This poses a problem when we wish to extract a scalable vector which
5530       // can't be re-expressed as a larger type. Just choose the slow path and
5531       // extend to a larger type, then truncate back down.
5532       // TODO: We could probably improve this when extracting certain fixed
5533       // from fixed, where we can extract as i8 and shift the correct element
5534       // right to reach the desired subvector?
5535       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5536       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5537       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5538       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5539                         Op.getOperand(1));
5540       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5541       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5542     }
5543   }
5544 
5545   // If the subvector vector is a fixed-length type, we cannot use subregister
5546   // manipulation to simplify the codegen; we don't know which register of a
5547   // LMUL group contains the specific subvector as we only know the minimum
5548   // register size. Therefore we must slide the vector group down the full
5549   // amount.
5550   if (SubVecVT.isFixedLengthVector()) {
5551     // With an index of 0 this is a cast-like subvector, which can be performed
5552     // with subregister operations.
5553     if (OrigIdx == 0)
5554       return Op;
5555     MVT ContainerVT = VecVT;
5556     if (VecVT.isFixedLengthVector()) {
5557       ContainerVT = getContainerForFixedLengthVector(VecVT);
5558       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5559     }
5560     SDValue Mask =
5561         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5562     // Set the vector length to only the number of elements we care about. This
5563     // avoids sliding down elements we're going to discard straight away.
5564     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5565     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5566     SDValue Slidedown =
5567         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5568                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5569     // Now we can use a cast-like subvector extract to get the result.
5570     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5571                             DAG.getConstant(0, DL, XLenVT));
5572     return DAG.getBitcast(Op.getValueType(), Slidedown);
5573   }
5574 
5575   unsigned SubRegIdx, RemIdx;
5576   std::tie(SubRegIdx, RemIdx) =
5577       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5578           VecVT, SubVecVT, OrigIdx, TRI);
5579 
5580   // If the Idx has been completely eliminated then this is a subvector extract
5581   // which naturally aligns to a vector register. These can easily be handled
5582   // using subregister manipulation.
5583   if (RemIdx == 0)
5584     return Op;
5585 
5586   // Else we must shift our vector register directly to extract the subvector.
5587   // Do this using VSLIDEDOWN.
5588 
5589   // If the vector type is an LMUL-group type, extract a subvector equal to the
5590   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5591   // instruction.
5592   MVT InterSubVT = VecVT;
5593   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5594     InterSubVT = getLMUL1VT(VecVT);
5595     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5596                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5597   }
5598 
5599   // Slide this vector register down by the desired number of elements in order
5600   // to place the desired subvector starting at element 0.
5601   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5602   // For scalable vectors this must be further multiplied by vscale.
5603   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5604 
5605   SDValue Mask, VL;
5606   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5607   SDValue Slidedown =
5608       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5609                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5610 
5611   // Now the vector is in the right position, extract our final subvector. This
5612   // should resolve to a COPY.
5613   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5614                           DAG.getConstant(0, DL, XLenVT));
5615 
5616   // We might have bitcast from a mask type: cast back to the original type if
5617   // required.
5618   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5619 }
5620 
5621 // Lower step_vector to the vid instruction. Any non-identity step value must
5622 // be accounted for my manual expansion.
5623 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5624                                               SelectionDAG &DAG) const {
5625   SDLoc DL(Op);
5626   MVT VT = Op.getSimpleValueType();
5627   MVT XLenVT = Subtarget.getXLenVT();
5628   SDValue Mask, VL;
5629   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5630   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5631   uint64_t StepValImm = Op.getConstantOperandVal(0);
5632   if (StepValImm != 1) {
5633     if (isPowerOf2_64(StepValImm)) {
5634       SDValue StepVal =
5635           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5636                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5637       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5638     } else {
5639       SDValue StepVal = lowerScalarSplat(
5640           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5641           VL, VT, DL, DAG, Subtarget);
5642       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5643     }
5644   }
5645   return StepVec;
5646 }
5647 
5648 // Implement vector_reverse using vrgather.vv with indices determined by
5649 // subtracting the id of each element from (VLMAX-1). This will convert
5650 // the indices like so:
5651 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5652 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5653 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5654                                                  SelectionDAG &DAG) const {
5655   SDLoc DL(Op);
5656   MVT VecVT = Op.getSimpleValueType();
5657   unsigned EltSize = VecVT.getScalarSizeInBits();
5658   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5659 
5660   unsigned MaxVLMAX = 0;
5661   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5662   if (VectorBitsMax != 0)
5663     MaxVLMAX =
5664         RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
5665 
5666   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5667   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5668 
5669   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5670   // to use vrgatherei16.vv.
5671   // TODO: It's also possible to use vrgatherei16.vv for other types to
5672   // decrease register width for the index calculation.
5673   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5674     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5675     // Reverse each half, then reassemble them in reverse order.
5676     // NOTE: It's also possible that after splitting that VLMAX no longer
5677     // requires vrgatherei16.vv.
5678     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5679       SDValue Lo, Hi;
5680       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5681       EVT LoVT, HiVT;
5682       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5683       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5684       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5685       // Reassemble the low and high pieces reversed.
5686       // FIXME: This is a CONCAT_VECTORS.
5687       SDValue Res =
5688           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5689                       DAG.getIntPtrConstant(0, DL));
5690       return DAG.getNode(
5691           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5692           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5693     }
5694 
5695     // Just promote the int type to i16 which will double the LMUL.
5696     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5697     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5698   }
5699 
5700   MVT XLenVT = Subtarget.getXLenVT();
5701   SDValue Mask, VL;
5702   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5703 
5704   // Calculate VLMAX-1 for the desired SEW.
5705   unsigned MinElts = VecVT.getVectorMinNumElements();
5706   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5707                               DAG.getConstant(MinElts, DL, XLenVT));
5708   SDValue VLMinus1 =
5709       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5710 
5711   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5712   bool IsRV32E64 =
5713       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5714   SDValue SplatVL;
5715   if (!IsRV32E64)
5716     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5717   else
5718     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5719                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5720 
5721   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5722   SDValue Indices =
5723       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5724 
5725   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5726 }
5727 
5728 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5729                                                 SelectionDAG &DAG) const {
5730   SDLoc DL(Op);
5731   SDValue V1 = Op.getOperand(0);
5732   SDValue V2 = Op.getOperand(1);
5733   MVT XLenVT = Subtarget.getXLenVT();
5734   MVT VecVT = Op.getSimpleValueType();
5735 
5736   unsigned MinElts = VecVT.getVectorMinNumElements();
5737   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5738                               DAG.getConstant(MinElts, DL, XLenVT));
5739 
5740   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5741   SDValue DownOffset, UpOffset;
5742   if (ImmValue >= 0) {
5743     // The operand is a TargetConstant, we need to rebuild it as a regular
5744     // constant.
5745     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5746     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5747   } else {
5748     // The operand is a TargetConstant, we need to rebuild it as a regular
5749     // constant rather than negating the original operand.
5750     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5751     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5752   }
5753 
5754   MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5755   SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax);
5756 
5757   SDValue SlideDown =
5758       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5759                   DownOffset, TrueMask, UpOffset);
5760   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5761                      TrueMask,
5762                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5763 }
5764 
5765 SDValue
5766 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5767                                                      SelectionDAG &DAG) const {
5768   SDLoc DL(Op);
5769   auto *Load = cast<LoadSDNode>(Op);
5770 
5771   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5772                                         Load->getMemoryVT(),
5773                                         *Load->getMemOperand()) &&
5774          "Expecting a correctly-aligned load");
5775 
5776   MVT VT = Op.getSimpleValueType();
5777   MVT XLenVT = Subtarget.getXLenVT();
5778   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5779 
5780   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5781 
5782   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5783   SDValue IntID = DAG.getTargetConstant(
5784       IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
5785   SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
5786   if (!IsMaskOp)
5787     Ops.push_back(DAG.getUNDEF(ContainerVT));
5788   Ops.push_back(Load->getBasePtr());
5789   Ops.push_back(VL);
5790   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5791   SDValue NewLoad =
5792       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
5793                               Load->getMemoryVT(), Load->getMemOperand());
5794 
5795   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5796   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5797 }
5798 
5799 SDValue
5800 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5801                                                       SelectionDAG &DAG) const {
5802   SDLoc DL(Op);
5803   auto *Store = cast<StoreSDNode>(Op);
5804 
5805   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5806                                         Store->getMemoryVT(),
5807                                         *Store->getMemOperand()) &&
5808          "Expecting a correctly-aligned store");
5809 
5810   SDValue StoreVal = Store->getValue();
5811   MVT VT = StoreVal.getSimpleValueType();
5812   MVT XLenVT = Subtarget.getXLenVT();
5813 
5814   // If the size less than a byte, we need to pad with zeros to make a byte.
5815   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5816     VT = MVT::v8i1;
5817     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5818                            DAG.getConstant(0, DL, VT), StoreVal,
5819                            DAG.getIntPtrConstant(0, DL));
5820   }
5821 
5822   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5823 
5824   SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
5825 
5826   SDValue NewValue =
5827       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5828 
5829   bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
5830   SDValue IntID = DAG.getTargetConstant(
5831       IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
5832   return DAG.getMemIntrinsicNode(
5833       ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
5834       {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
5835       Store->getMemoryVT(), Store->getMemOperand());
5836 }
5837 
5838 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5839                                              SelectionDAG &DAG) const {
5840   SDLoc DL(Op);
5841   MVT VT = Op.getSimpleValueType();
5842 
5843   const auto *MemSD = cast<MemSDNode>(Op);
5844   EVT MemVT = MemSD->getMemoryVT();
5845   MachineMemOperand *MMO = MemSD->getMemOperand();
5846   SDValue Chain = MemSD->getChain();
5847   SDValue BasePtr = MemSD->getBasePtr();
5848 
5849   SDValue Mask, PassThru, VL;
5850   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5851     Mask = VPLoad->getMask();
5852     PassThru = DAG.getUNDEF(VT);
5853     VL = VPLoad->getVectorLength();
5854   } else {
5855     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5856     Mask = MLoad->getMask();
5857     PassThru = MLoad->getPassThru();
5858   }
5859 
5860   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5861 
5862   MVT XLenVT = Subtarget.getXLenVT();
5863 
5864   MVT ContainerVT = VT;
5865   if (VT.isFixedLengthVector()) {
5866     ContainerVT = getContainerForFixedLengthVector(VT);
5867     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5868     if (!IsUnmasked) {
5869       MVT MaskVT =
5870           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5871       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5872     }
5873   }
5874 
5875   if (!VL)
5876     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5877 
5878   unsigned IntID =
5879       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5880   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5881   if (IsUnmasked)
5882     Ops.push_back(DAG.getUNDEF(ContainerVT));
5883   else
5884     Ops.push_back(PassThru);
5885   Ops.push_back(BasePtr);
5886   if (!IsUnmasked)
5887     Ops.push_back(Mask);
5888   Ops.push_back(VL);
5889   if (!IsUnmasked)
5890     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5891 
5892   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5893 
5894   SDValue Result =
5895       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5896   Chain = Result.getValue(1);
5897 
5898   if (VT.isFixedLengthVector())
5899     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5900 
5901   return DAG.getMergeValues({Result, Chain}, DL);
5902 }
5903 
5904 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5905                                               SelectionDAG &DAG) const {
5906   SDLoc DL(Op);
5907 
5908   const auto *MemSD = cast<MemSDNode>(Op);
5909   EVT MemVT = MemSD->getMemoryVT();
5910   MachineMemOperand *MMO = MemSD->getMemOperand();
5911   SDValue Chain = MemSD->getChain();
5912   SDValue BasePtr = MemSD->getBasePtr();
5913   SDValue Val, Mask, VL;
5914 
5915   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5916     Val = VPStore->getValue();
5917     Mask = VPStore->getMask();
5918     VL = VPStore->getVectorLength();
5919   } else {
5920     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5921     Val = MStore->getValue();
5922     Mask = MStore->getMask();
5923   }
5924 
5925   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5926 
5927   MVT VT = Val.getSimpleValueType();
5928   MVT XLenVT = Subtarget.getXLenVT();
5929 
5930   MVT ContainerVT = VT;
5931   if (VT.isFixedLengthVector()) {
5932     ContainerVT = getContainerForFixedLengthVector(VT);
5933 
5934     Val = convertToScalableVector(ContainerVT, Val, 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_vse : Intrinsic::riscv_vse_mask;
5947   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5948   Ops.push_back(Val);
5949   Ops.push_back(BasePtr);
5950   if (!IsUnmasked)
5951     Ops.push_back(Mask);
5952   Ops.push_back(VL);
5953 
5954   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5955                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5956 }
5957 
5958 SDValue
5959 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5960                                                       SelectionDAG &DAG) const {
5961   MVT InVT = Op.getOperand(0).getSimpleValueType();
5962   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5963 
5964   MVT VT = Op.getSimpleValueType();
5965 
5966   SDValue Op1 =
5967       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5968   SDValue Op2 =
5969       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5970 
5971   SDLoc DL(Op);
5972   SDValue VL =
5973       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5974 
5975   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5976   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5977 
5978   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5979                             Op.getOperand(2), Mask, VL);
5980 
5981   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5982 }
5983 
5984 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5985     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5986   MVT VT = Op.getSimpleValueType();
5987 
5988   if (VT.getVectorElementType() == MVT::i1)
5989     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5990 
5991   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5992 }
5993 
5994 SDValue
5995 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5996                                                       SelectionDAG &DAG) const {
5997   unsigned Opc;
5998   switch (Op.getOpcode()) {
5999   default: llvm_unreachable("Unexpected opcode!");
6000   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
6001   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
6002   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
6003   }
6004 
6005   return lowerToScalableOp(Op, DAG, Opc);
6006 }
6007 
6008 // Lower vector ABS to smax(X, sub(0, X)).
6009 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
6010   SDLoc DL(Op);
6011   MVT VT = Op.getSimpleValueType();
6012   SDValue X = Op.getOperand(0);
6013 
6014   assert(VT.isFixedLengthVector() && "Unexpected type");
6015 
6016   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6017   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
6018 
6019   SDValue Mask, VL;
6020   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6021 
6022   SDValue SplatZero = DAG.getNode(
6023       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
6024       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
6025   SDValue NegX =
6026       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
6027   SDValue Max =
6028       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
6029 
6030   return convertFromScalableVector(VT, Max, DAG, Subtarget);
6031 }
6032 
6033 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
6034     SDValue Op, SelectionDAG &DAG) const {
6035   SDLoc DL(Op);
6036   MVT VT = Op.getSimpleValueType();
6037   SDValue Mag = Op.getOperand(0);
6038   SDValue Sign = Op.getOperand(1);
6039   assert(Mag.getValueType() == Sign.getValueType() &&
6040          "Can only handle COPYSIGN with matching types.");
6041 
6042   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6043   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
6044   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
6045 
6046   SDValue Mask, VL;
6047   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6048 
6049   SDValue CopySign =
6050       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
6051 
6052   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
6053 }
6054 
6055 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
6056     SDValue Op, SelectionDAG &DAG) const {
6057   MVT VT = Op.getSimpleValueType();
6058   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6059 
6060   MVT I1ContainerVT =
6061       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6062 
6063   SDValue CC =
6064       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
6065   SDValue Op1 =
6066       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
6067   SDValue Op2 =
6068       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
6069 
6070   SDLoc DL(Op);
6071   SDValue Mask, VL;
6072   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6073 
6074   SDValue Select =
6075       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
6076 
6077   return convertFromScalableVector(VT, Select, DAG, Subtarget);
6078 }
6079 
6080 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
6081                                                unsigned NewOpc,
6082                                                bool HasMask) const {
6083   MVT VT = Op.getSimpleValueType();
6084   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6085 
6086   // Create list of operands by converting existing ones to scalable types.
6087   SmallVector<SDValue, 6> Ops;
6088   for (const SDValue &V : Op->op_values()) {
6089     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6090 
6091     // Pass through non-vector operands.
6092     if (!V.getValueType().isVector()) {
6093       Ops.push_back(V);
6094       continue;
6095     }
6096 
6097     // "cast" fixed length vector to a scalable vector.
6098     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
6099            "Only fixed length vectors are supported!");
6100     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6101   }
6102 
6103   SDLoc DL(Op);
6104   SDValue Mask, VL;
6105   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6106   if (HasMask)
6107     Ops.push_back(Mask);
6108   Ops.push_back(VL);
6109 
6110   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6111   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6112 }
6113 
6114 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6115 // * Operands of each node are assumed to be in the same order.
6116 // * The EVL operand is promoted from i32 to i64 on RV64.
6117 // * Fixed-length vectors are converted to their scalable-vector container
6118 //   types.
6119 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6120                                        unsigned RISCVISDOpc) const {
6121   SDLoc DL(Op);
6122   MVT VT = Op.getSimpleValueType();
6123   SmallVector<SDValue, 4> Ops;
6124 
6125   for (const auto &OpIdx : enumerate(Op->ops())) {
6126     SDValue V = OpIdx.value();
6127     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6128     // Pass through operands which aren't fixed-length vectors.
6129     if (!V.getValueType().isFixedLengthVector()) {
6130       Ops.push_back(V);
6131       continue;
6132     }
6133     // "cast" fixed length vector to a scalable vector.
6134     MVT OpVT = V.getSimpleValueType();
6135     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6136     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6137            "Only fixed length vectors are supported!");
6138     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6139   }
6140 
6141   if (!VT.isFixedLengthVector())
6142     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
6143 
6144   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6145 
6146   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
6147 
6148   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6149 }
6150 
6151 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op,
6152                                               SelectionDAG &DAG) const {
6153   SDLoc DL(Op);
6154   MVT VT = Op.getSimpleValueType();
6155 
6156   SDValue Src = Op.getOperand(0);
6157   // NOTE: Mask is dropped.
6158   SDValue VL = Op.getOperand(2);
6159 
6160   MVT ContainerVT = VT;
6161   if (VT.isFixedLengthVector()) {
6162     ContainerVT = getContainerForFixedLengthVector(VT);
6163     MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6164     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6165   }
6166 
6167   MVT XLenVT = Subtarget.getXLenVT();
6168   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6169   SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6170                                   DAG.getUNDEF(ContainerVT), Zero, VL);
6171 
6172   SDValue SplatValue =
6173       DAG.getConstant(Op.getOpcode() == ISD::VP_ZEXT ? 1 : -1, DL, XLenVT);
6174   SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6175                               DAG.getUNDEF(ContainerVT), SplatValue, VL);
6176 
6177   SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src,
6178                                Splat, ZeroSplat, VL);
6179   if (!VT.isFixedLengthVector())
6180     return Result;
6181   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6182 }
6183 
6184 // Lower Floating-Point/Integer Type-Convert VP SDNodes
6185 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
6186                                                 unsigned RISCVISDOpc) const {
6187   SDLoc DL(Op);
6188 
6189   SDValue Src = Op.getOperand(0);
6190   SDValue Mask = Op.getOperand(1);
6191   SDValue VL = Op.getOperand(2);
6192 
6193   MVT DstVT = Op.getSimpleValueType();
6194   MVT SrcVT = Src.getSimpleValueType();
6195   if (DstVT.isFixedLengthVector()) {
6196     DstVT = getContainerForFixedLengthVector(DstVT);
6197     SrcVT = getContainerForFixedLengthVector(SrcVT);
6198     Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
6199     MVT MaskVT = MVT::getVectorVT(MVT::i1, DstVT.getVectorElementCount());
6200     Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6201   }
6202 
6203   unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL ||
6204                              RISCVISDOpc == RISCVISD::FP_TO_SINT_VL)
6205                                 ? RISCVISD::VSEXT_VL
6206                                 : RISCVISD::VZEXT_VL;
6207 
6208   unsigned DstEltSize = DstVT.getScalarSizeInBits();
6209   unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
6210 
6211   SDValue Result;
6212   if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
6213     if (SrcVT.isInteger()) {
6214       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6215 
6216       // Do we need to do any pre-widening before converting?
6217       if (SrcEltSize == 1) {
6218         MVT IntVT = DstVT.changeVectorElementTypeToInteger();
6219         MVT XLenVT = Subtarget.getXLenVT();
6220         SDValue Zero = DAG.getConstant(0, DL, XLenVT);
6221         SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6222                                         DAG.getUNDEF(IntVT), Zero, VL);
6223         SDValue One = DAG.getConstant(
6224             RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
6225         SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
6226                                        DAG.getUNDEF(IntVT), One, VL);
6227         Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
6228                           ZeroSplat, VL);
6229       } else if (DstEltSize > (2 * SrcEltSize)) {
6230         // Widen before converting.
6231         MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
6232                                      DstVT.getVectorElementCount());
6233         Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL);
6234       }
6235 
6236       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6237     } else {
6238       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6239              "Wrong input/output vector types");
6240 
6241       // Convert f16 to f32 then convert f32 to i64.
6242       if (DstEltSize > (2 * SrcEltSize)) {
6243         assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6244         MVT InterimFVT =
6245             MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6246         Src =
6247             DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL);
6248       }
6249 
6250       Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
6251     }
6252   } else { // Narrowing + Conversion
6253     if (SrcVT.isInteger()) {
6254       assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
6255       // First do a narrowing convert to an FP type half the size, then round
6256       // the FP type to a small FP type if needed.
6257 
6258       MVT InterimFVT = DstVT;
6259       if (SrcEltSize > (2 * DstEltSize)) {
6260         assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
6261         assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
6262         InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
6263       }
6264 
6265       Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL);
6266 
6267       if (InterimFVT != DstVT) {
6268         Src = Result;
6269         Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL);
6270       }
6271     } else {
6272       assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
6273              "Wrong input/output vector types");
6274       // First do a narrowing conversion to an integer half the size, then
6275       // truncate if needed.
6276 
6277       if (DstEltSize == 1) {
6278         // First convert to the same size integer, then convert to mask using
6279         // setcc.
6280         assert(SrcEltSize >= 16 && "Unexpected FP type!");
6281         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize),
6282                                           DstVT.getVectorElementCount());
6283         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6284 
6285         // Compare the integer result to 0. The integer should be 0 or 1/-1,
6286         // otherwise the conversion was undefined.
6287         MVT XLenVT = Subtarget.getXLenVT();
6288         SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
6289         SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT,
6290                                 DAG.getUNDEF(InterimIVT), SplatZero);
6291         Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero,
6292                              DAG.getCondCode(ISD::SETNE), Mask, VL);
6293       } else {
6294         MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6295                                           DstVT.getVectorElementCount());
6296 
6297         Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
6298 
6299         while (InterimIVT != DstVT) {
6300           SrcEltSize /= 2;
6301           Src = Result;
6302           InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
6303                                         DstVT.getVectorElementCount());
6304           Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
6305                                Src, Mask, VL);
6306         }
6307       }
6308     }
6309   }
6310 
6311   MVT VT = Op.getSimpleValueType();
6312   if (!VT.isFixedLengthVector())
6313     return Result;
6314   return convertFromScalableVector(VT, Result, DAG, Subtarget);
6315 }
6316 
6317 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6318                                             unsigned MaskOpc,
6319                                             unsigned VecOpc) const {
6320   MVT VT = Op.getSimpleValueType();
6321   if (VT.getVectorElementType() != MVT::i1)
6322     return lowerVPOp(Op, DAG, VecOpc);
6323 
6324   // It is safe to drop mask parameter as masked-off elements are undef.
6325   SDValue Op1 = Op->getOperand(0);
6326   SDValue Op2 = Op->getOperand(1);
6327   SDValue VL = Op->getOperand(3);
6328 
6329   MVT ContainerVT = VT;
6330   const bool IsFixed = VT.isFixedLengthVector();
6331   if (IsFixed) {
6332     ContainerVT = getContainerForFixedLengthVector(VT);
6333     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6334     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6335   }
6336 
6337   SDLoc DL(Op);
6338   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6339   if (!IsFixed)
6340     return Val;
6341   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6342 }
6343 
6344 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6345 // matched to a RVV indexed load. The RVV indexed load instructions only
6346 // support the "unsigned unscaled" addressing mode; indices are implicitly
6347 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6348 // signed or scaled indexing is extended to the XLEN value type and scaled
6349 // accordingly.
6350 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6351                                                SelectionDAG &DAG) const {
6352   SDLoc DL(Op);
6353   MVT VT = Op.getSimpleValueType();
6354 
6355   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6356   EVT MemVT = MemSD->getMemoryVT();
6357   MachineMemOperand *MMO = MemSD->getMemOperand();
6358   SDValue Chain = MemSD->getChain();
6359   SDValue BasePtr = MemSD->getBasePtr();
6360 
6361   ISD::LoadExtType LoadExtType;
6362   SDValue Index, Mask, PassThru, VL;
6363 
6364   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6365     Index = VPGN->getIndex();
6366     Mask = VPGN->getMask();
6367     PassThru = DAG.getUNDEF(VT);
6368     VL = VPGN->getVectorLength();
6369     // VP doesn't support extending loads.
6370     LoadExtType = ISD::NON_EXTLOAD;
6371   } else {
6372     // Else it must be a MGATHER.
6373     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6374     Index = MGN->getIndex();
6375     Mask = MGN->getMask();
6376     PassThru = MGN->getPassThru();
6377     LoadExtType = MGN->getExtensionType();
6378   }
6379 
6380   MVT IndexVT = Index.getSimpleValueType();
6381   MVT XLenVT = Subtarget.getXLenVT();
6382 
6383   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6384          "Unexpected VTs!");
6385   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6386   // Targets have to explicitly opt-in for extending vector loads.
6387   assert(LoadExtType == ISD::NON_EXTLOAD &&
6388          "Unexpected extending MGATHER/VP_GATHER");
6389   (void)LoadExtType;
6390 
6391   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6392   // the selection of the masked intrinsics doesn't do this for us.
6393   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6394 
6395   MVT ContainerVT = VT;
6396   if (VT.isFixedLengthVector()) {
6397     // We need to use the larger of the result and index type to determine the
6398     // scalable type to use so we don't increase LMUL for any operand/result.
6399     if (VT.bitsGE(IndexVT)) {
6400       ContainerVT = getContainerForFixedLengthVector(VT);
6401       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6402                                  ContainerVT.getVectorElementCount());
6403     } else {
6404       IndexVT = getContainerForFixedLengthVector(IndexVT);
6405       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
6406                                      IndexVT.getVectorElementCount());
6407     }
6408 
6409     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6410 
6411     if (!IsUnmasked) {
6412       MVT MaskVT =
6413           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6414       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6415       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6416     }
6417   }
6418 
6419   if (!VL)
6420     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6421 
6422   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6423     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6424     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6425                                    VL);
6426     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6427                         TrueMask, VL);
6428   }
6429 
6430   unsigned IntID =
6431       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6432   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6433   if (IsUnmasked)
6434     Ops.push_back(DAG.getUNDEF(ContainerVT));
6435   else
6436     Ops.push_back(PassThru);
6437   Ops.push_back(BasePtr);
6438   Ops.push_back(Index);
6439   if (!IsUnmasked)
6440     Ops.push_back(Mask);
6441   Ops.push_back(VL);
6442   if (!IsUnmasked)
6443     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6444 
6445   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6446   SDValue Result =
6447       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6448   Chain = Result.getValue(1);
6449 
6450   if (VT.isFixedLengthVector())
6451     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6452 
6453   return DAG.getMergeValues({Result, Chain}, DL);
6454 }
6455 
6456 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6457 // matched to a RVV indexed store. The RVV indexed store instructions only
6458 // support the "unsigned unscaled" addressing mode; indices are implicitly
6459 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6460 // signed or scaled indexing is extended to the XLEN value type and scaled
6461 // accordingly.
6462 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6463                                                 SelectionDAG &DAG) const {
6464   SDLoc DL(Op);
6465   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6466   EVT MemVT = MemSD->getMemoryVT();
6467   MachineMemOperand *MMO = MemSD->getMemOperand();
6468   SDValue Chain = MemSD->getChain();
6469   SDValue BasePtr = MemSD->getBasePtr();
6470 
6471   bool IsTruncatingStore = false;
6472   SDValue Index, Mask, Val, VL;
6473 
6474   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6475     Index = VPSN->getIndex();
6476     Mask = VPSN->getMask();
6477     Val = VPSN->getValue();
6478     VL = VPSN->getVectorLength();
6479     // VP doesn't support truncating stores.
6480     IsTruncatingStore = false;
6481   } else {
6482     // Else it must be a MSCATTER.
6483     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6484     Index = MSN->getIndex();
6485     Mask = MSN->getMask();
6486     Val = MSN->getValue();
6487     IsTruncatingStore = MSN->isTruncatingStore();
6488   }
6489 
6490   MVT VT = Val.getSimpleValueType();
6491   MVT IndexVT = Index.getSimpleValueType();
6492   MVT XLenVT = Subtarget.getXLenVT();
6493 
6494   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6495          "Unexpected VTs!");
6496   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6497   // Targets have to explicitly opt-in for extending vector loads and
6498   // truncating vector stores.
6499   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6500   (void)IsTruncatingStore;
6501 
6502   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6503   // the selection of the masked intrinsics doesn't do this for us.
6504   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6505 
6506   MVT ContainerVT = VT;
6507   if (VT.isFixedLengthVector()) {
6508     // We need to use the larger of the value and index type to determine the
6509     // scalable type to use so we don't increase LMUL for any operand/result.
6510     if (VT.bitsGE(IndexVT)) {
6511       ContainerVT = getContainerForFixedLengthVector(VT);
6512       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6513                                  ContainerVT.getVectorElementCount());
6514     } else {
6515       IndexVT = getContainerForFixedLengthVector(IndexVT);
6516       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
6517                                      IndexVT.getVectorElementCount());
6518     }
6519 
6520     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6521     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6522 
6523     if (!IsUnmasked) {
6524       MVT MaskVT =
6525           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6526       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6527     }
6528   }
6529 
6530   if (!VL)
6531     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6532 
6533   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6534     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6535     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6536                                    VL);
6537     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6538                         TrueMask, VL);
6539   }
6540 
6541   unsigned IntID =
6542       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6543   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6544   Ops.push_back(Val);
6545   Ops.push_back(BasePtr);
6546   Ops.push_back(Index);
6547   if (!IsUnmasked)
6548     Ops.push_back(Mask);
6549   Ops.push_back(VL);
6550 
6551   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6552                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6553 }
6554 
6555 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6556                                                SelectionDAG &DAG) const {
6557   const MVT XLenVT = Subtarget.getXLenVT();
6558   SDLoc DL(Op);
6559   SDValue Chain = Op->getOperand(0);
6560   SDValue SysRegNo = DAG.getTargetConstant(
6561       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6562   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6563   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6564 
6565   // Encoding used for rounding mode in RISCV differs from that used in
6566   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6567   // table, which consists of a sequence of 4-bit fields, each representing
6568   // corresponding FLT_ROUNDS mode.
6569   static const int Table =
6570       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6571       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6572       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6573       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6574       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6575 
6576   SDValue Shift =
6577       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6578   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6579                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6580   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6581                                DAG.getConstant(7, DL, XLenVT));
6582 
6583   return DAG.getMergeValues({Masked, Chain}, DL);
6584 }
6585 
6586 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6587                                                SelectionDAG &DAG) const {
6588   const MVT XLenVT = Subtarget.getXLenVT();
6589   SDLoc DL(Op);
6590   SDValue Chain = Op->getOperand(0);
6591   SDValue RMValue = Op->getOperand(1);
6592   SDValue SysRegNo = DAG.getTargetConstant(
6593       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6594 
6595   // Encoding used for rounding mode in RISCV differs from that used in
6596   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6597   // a table, which consists of a sequence of 4-bit fields, each representing
6598   // corresponding RISCV mode.
6599   static const unsigned Table =
6600       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6601       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6602       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6603       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6604       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6605 
6606   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6607                               DAG.getConstant(2, DL, XLenVT));
6608   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6609                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6610   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6611                         DAG.getConstant(0x7, DL, XLenVT));
6612   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6613                      RMValue);
6614 }
6615 
6616 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6617   switch (IntNo) {
6618   default:
6619     llvm_unreachable("Unexpected Intrinsic");
6620   case Intrinsic::riscv_bcompress:
6621     return RISCVISD::BCOMPRESSW;
6622   case Intrinsic::riscv_bdecompress:
6623     return RISCVISD::BDECOMPRESSW;
6624   case Intrinsic::riscv_bfp:
6625     return RISCVISD::BFPW;
6626   case Intrinsic::riscv_fsl:
6627     return RISCVISD::FSLW;
6628   case Intrinsic::riscv_fsr:
6629     return RISCVISD::FSRW;
6630   }
6631 }
6632 
6633 // Converts the given intrinsic to a i64 operation with any extension.
6634 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6635                                          unsigned IntNo) {
6636   SDLoc DL(N);
6637   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6638   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6639   SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6640   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2);
6641   // ReplaceNodeResults requires we maintain the same type for the return value.
6642   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6643 }
6644 
6645 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6646 // form of the given Opcode.
6647 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6648   switch (Opcode) {
6649   default:
6650     llvm_unreachable("Unexpected opcode");
6651   case ISD::SHL:
6652     return RISCVISD::SLLW;
6653   case ISD::SRA:
6654     return RISCVISD::SRAW;
6655   case ISD::SRL:
6656     return RISCVISD::SRLW;
6657   case ISD::SDIV:
6658     return RISCVISD::DIVW;
6659   case ISD::UDIV:
6660     return RISCVISD::DIVUW;
6661   case ISD::UREM:
6662     return RISCVISD::REMUW;
6663   case ISD::ROTL:
6664     return RISCVISD::ROLW;
6665   case ISD::ROTR:
6666     return RISCVISD::RORW;
6667   }
6668 }
6669 
6670 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6671 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6672 // otherwise be promoted to i64, making it difficult to select the
6673 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6674 // type i8/i16/i32 is lost.
6675 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6676                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6677   SDLoc DL(N);
6678   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6679   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6680   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6681   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6682   // ReplaceNodeResults requires we maintain the same type for the return value.
6683   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6684 }
6685 
6686 // Converts the given 32-bit operation to a i64 operation with signed extension
6687 // semantic to reduce the signed extension instructions.
6688 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6689   SDLoc DL(N);
6690   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6691   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6692   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6693   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6694                                DAG.getValueType(MVT::i32));
6695   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6696 }
6697 
6698 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6699                                              SmallVectorImpl<SDValue> &Results,
6700                                              SelectionDAG &DAG) const {
6701   SDLoc DL(N);
6702   switch (N->getOpcode()) {
6703   default:
6704     llvm_unreachable("Don't know how to custom type legalize this operation!");
6705   case ISD::STRICT_FP_TO_SINT:
6706   case ISD::STRICT_FP_TO_UINT:
6707   case ISD::FP_TO_SINT:
6708   case ISD::FP_TO_UINT: {
6709     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6710            "Unexpected custom legalisation");
6711     bool IsStrict = N->isStrictFPOpcode();
6712     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6713                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6714     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6715     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6716         TargetLowering::TypeSoftenFloat) {
6717       if (!isTypeLegal(Op0.getValueType()))
6718         return;
6719       if (IsStrict) {
6720         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6721                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6722         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6723         SDValue Res = DAG.getNode(
6724             Opc, DL, VTs, N->getOperand(0), Op0,
6725             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6726         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6727         Results.push_back(Res.getValue(1));
6728         return;
6729       }
6730       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6731       SDValue Res =
6732           DAG.getNode(Opc, DL, MVT::i64, Op0,
6733                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6734       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6735       return;
6736     }
6737     // If the FP type needs to be softened, emit a library call using the 'si'
6738     // version. If we left it to default legalization we'd end up with 'di'. If
6739     // the FP type doesn't need to be softened just let generic type
6740     // legalization promote the result type.
6741     RTLIB::Libcall LC;
6742     if (IsSigned)
6743       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6744     else
6745       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6746     MakeLibCallOptions CallOptions;
6747     EVT OpVT = Op0.getValueType();
6748     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6749     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6750     SDValue Result;
6751     std::tie(Result, Chain) =
6752         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6753     Results.push_back(Result);
6754     if (IsStrict)
6755       Results.push_back(Chain);
6756     break;
6757   }
6758   case ISD::READCYCLECOUNTER: {
6759     assert(!Subtarget.is64Bit() &&
6760            "READCYCLECOUNTER only has custom type legalization on riscv32");
6761 
6762     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6763     SDValue RCW =
6764         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6765 
6766     Results.push_back(
6767         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6768     Results.push_back(RCW.getValue(2));
6769     break;
6770   }
6771   case ISD::MUL: {
6772     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6773     unsigned XLen = Subtarget.getXLen();
6774     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6775     if (Size > XLen) {
6776       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6777       SDValue LHS = N->getOperand(0);
6778       SDValue RHS = N->getOperand(1);
6779       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6780 
6781       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6782       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6783       // We need exactly one side to be unsigned.
6784       if (LHSIsU == RHSIsU)
6785         return;
6786 
6787       auto MakeMULPair = [&](SDValue S, SDValue U) {
6788         MVT XLenVT = Subtarget.getXLenVT();
6789         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6790         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6791         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6792         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6793         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6794       };
6795 
6796       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6797       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6798 
6799       // The other operand should be signed, but still prefer MULH when
6800       // possible.
6801       if (RHSIsU && LHSIsS && !RHSIsS)
6802         Results.push_back(MakeMULPair(LHS, RHS));
6803       else if (LHSIsU && RHSIsS && !LHSIsS)
6804         Results.push_back(MakeMULPair(RHS, LHS));
6805 
6806       return;
6807     }
6808     LLVM_FALLTHROUGH;
6809   }
6810   case ISD::ADD:
6811   case ISD::SUB:
6812     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6813            "Unexpected custom legalisation");
6814     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6815     break;
6816   case ISD::SHL:
6817   case ISD::SRA:
6818   case ISD::SRL:
6819     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6820            "Unexpected custom legalisation");
6821     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6822       Results.push_back(customLegalizeToWOp(N, DAG));
6823       break;
6824     }
6825 
6826     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6827     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6828     // shift amount.
6829     if (N->getOpcode() == ISD::SHL) {
6830       SDLoc DL(N);
6831       SDValue NewOp0 =
6832           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6833       SDValue NewOp1 =
6834           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6835       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6836       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6837                                    DAG.getValueType(MVT::i32));
6838       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6839     }
6840 
6841     break;
6842   case ISD::ROTL:
6843   case ISD::ROTR:
6844     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6845            "Unexpected custom legalisation");
6846     Results.push_back(customLegalizeToWOp(N, DAG));
6847     break;
6848   case ISD::CTTZ:
6849   case ISD::CTTZ_ZERO_UNDEF:
6850   case ISD::CTLZ:
6851   case ISD::CTLZ_ZERO_UNDEF: {
6852     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6853            "Unexpected custom legalisation");
6854 
6855     SDValue NewOp0 =
6856         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6857     bool IsCTZ =
6858         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6859     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6860     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6861     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6862     return;
6863   }
6864   case ISD::SDIV:
6865   case ISD::UDIV:
6866   case ISD::UREM: {
6867     MVT VT = N->getSimpleValueType(0);
6868     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6869            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6870            "Unexpected custom legalisation");
6871     // Don't promote division/remainder by constant since we should expand those
6872     // to multiply by magic constant.
6873     // FIXME: What if the expansion is disabled for minsize.
6874     if (N->getOperand(1).getOpcode() == ISD::Constant)
6875       return;
6876 
6877     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6878     // the upper 32 bits. For other types we need to sign or zero extend
6879     // based on the opcode.
6880     unsigned ExtOpc = ISD::ANY_EXTEND;
6881     if (VT != MVT::i32)
6882       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6883                                            : ISD::ZERO_EXTEND;
6884 
6885     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6886     break;
6887   }
6888   case ISD::UADDO:
6889   case ISD::USUBO: {
6890     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6891            "Unexpected custom legalisation");
6892     bool IsAdd = N->getOpcode() == ISD::UADDO;
6893     // Create an ADDW or SUBW.
6894     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6895     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6896     SDValue Res =
6897         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6898     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6899                       DAG.getValueType(MVT::i32));
6900 
6901     SDValue Overflow;
6902     if (IsAdd && isOneConstant(RHS)) {
6903       // Special case uaddo X, 1 overflowed if the addition result is 0.
6904       // FIXME: We can do this for any constant RHS by using (X + C) < C.
6905       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res,
6906                               DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ);
6907     } else {
6908       // Sign extend the LHS and perform an unsigned compare with the ADDW
6909       // result. Since the inputs are sign extended from i32, this is equivalent
6910       // to comparing the lower 32 bits.
6911       LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6912       Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6913                               IsAdd ? ISD::SETULT : ISD::SETUGT);
6914     }
6915 
6916     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6917     Results.push_back(Overflow);
6918     return;
6919   }
6920   case ISD::UADDSAT:
6921   case ISD::USUBSAT: {
6922     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6923            "Unexpected custom legalisation");
6924     if (Subtarget.hasStdExtZbb()) {
6925       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6926       // sign extend allows overflow of the lower 32 bits to be detected on
6927       // the promoted size.
6928       SDValue LHS =
6929           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6930       SDValue RHS =
6931           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6932       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6933       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6934       return;
6935     }
6936 
6937     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6938     // promotion for UADDO/USUBO.
6939     Results.push_back(expandAddSubSat(N, DAG));
6940     return;
6941   }
6942   case ISD::ABS: {
6943     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6944            "Unexpected custom legalisation");
6945           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6946 
6947     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
6948 
6949     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6950 
6951     // Freeze the source so we can increase it's use count.
6952     Src = DAG.getFreeze(Src);
6953 
6954     // Copy sign bit to all bits using the sraiw pattern.
6955     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
6956                                    DAG.getValueType(MVT::i32));
6957     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
6958                            DAG.getConstant(31, DL, MVT::i64));
6959 
6960     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
6961     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
6962 
6963     // NOTE: The result is only required to be anyextended, but sext is
6964     // consistent with type legalization of sub.
6965     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
6966                          DAG.getValueType(MVT::i32));
6967     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6968     return;
6969   }
6970   case ISD::BITCAST: {
6971     EVT VT = N->getValueType(0);
6972     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6973     SDValue Op0 = N->getOperand(0);
6974     EVT Op0VT = Op0.getValueType();
6975     MVT XLenVT = Subtarget.getXLenVT();
6976     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6977       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6978       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6979     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6980                Subtarget.hasStdExtF()) {
6981       SDValue FPConv =
6982           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6983       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6984     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6985                isTypeLegal(Op0VT)) {
6986       // Custom-legalize bitcasts from fixed-length vector types to illegal
6987       // scalar types in order to improve codegen. Bitcast the vector to a
6988       // one-element vector type whose element type is the same as the result
6989       // type, and extract the first element.
6990       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6991       if (isTypeLegal(BVT)) {
6992         SDValue BVec = DAG.getBitcast(BVT, Op0);
6993         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6994                                       DAG.getConstant(0, DL, XLenVT)));
6995       }
6996     }
6997     break;
6998   }
6999   case RISCVISD::GREV:
7000   case RISCVISD::GORC:
7001   case RISCVISD::SHFL: {
7002     MVT VT = N->getSimpleValueType(0);
7003     MVT XLenVT = Subtarget.getXLenVT();
7004     assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
7005            "Unexpected custom legalisation");
7006     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
7007     assert((Subtarget.hasStdExtZbp() ||
7008             (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV &&
7009              N->getConstantOperandVal(1) == 7)) &&
7010            "Unexpected extension");
7011     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7012     SDValue NewOp1 =
7013         DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1));
7014     SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1);
7015     // ReplaceNodeResults requires we maintain the same type for the return
7016     // value.
7017     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
7018     break;
7019   }
7020   case ISD::BSWAP:
7021   case ISD::BITREVERSE: {
7022     MVT VT = N->getSimpleValueType(0);
7023     MVT XLenVT = Subtarget.getXLenVT();
7024     assert((VT == MVT::i8 || VT == MVT::i16 ||
7025             (VT == MVT::i32 && Subtarget.is64Bit())) &&
7026            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
7027     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
7028     unsigned Imm = VT.getSizeInBits() - 1;
7029     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
7030     if (N->getOpcode() == ISD::BSWAP)
7031       Imm &= ~0x7U;
7032     SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0,
7033                                 DAG.getConstant(Imm, DL, XLenVT));
7034     // ReplaceNodeResults requires we maintain the same type for the return
7035     // value.
7036     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
7037     break;
7038   }
7039   case ISD::FSHL:
7040   case ISD::FSHR: {
7041     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7042            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
7043     SDValue NewOp0 =
7044         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
7045     SDValue NewOp1 =
7046         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7047     SDValue NewShAmt =
7048         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7049     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
7050     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
7051     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
7052                            DAG.getConstant(0x1f, DL, MVT::i64));
7053     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
7054     // instruction use different orders. fshl will return its first operand for
7055     // shift of zero, fshr will return its second operand. fsl and fsr both
7056     // return rs1 so the ISD nodes need to have different operand orders.
7057     // Shift amount is in rs2.
7058     unsigned Opc = RISCVISD::FSLW;
7059     if (N->getOpcode() == ISD::FSHR) {
7060       std::swap(NewOp0, NewOp1);
7061       Opc = RISCVISD::FSRW;
7062     }
7063     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
7064     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
7065     break;
7066   }
7067   case ISD::EXTRACT_VECTOR_ELT: {
7068     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
7069     // type is illegal (currently only vXi64 RV32).
7070     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
7071     // transferred to the destination register. We issue two of these from the
7072     // upper- and lower- halves of the SEW-bit vector element, slid down to the
7073     // first element.
7074     SDValue Vec = N->getOperand(0);
7075     SDValue Idx = N->getOperand(1);
7076 
7077     // The vector type hasn't been legalized yet so we can't issue target
7078     // specific nodes if it needs legalization.
7079     // FIXME: We would manually legalize if it's important.
7080     if (!isTypeLegal(Vec.getValueType()))
7081       return;
7082 
7083     MVT VecVT = Vec.getSimpleValueType();
7084 
7085     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
7086            VecVT.getVectorElementType() == MVT::i64 &&
7087            "Unexpected EXTRACT_VECTOR_ELT legalization");
7088 
7089     // If this is a fixed vector, we need to convert it to a scalable vector.
7090     MVT ContainerVT = VecVT;
7091     if (VecVT.isFixedLengthVector()) {
7092       ContainerVT = getContainerForFixedLengthVector(VecVT);
7093       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
7094     }
7095 
7096     MVT XLenVT = Subtarget.getXLenVT();
7097 
7098     // Use a VL of 1 to avoid processing more elements than we need.
7099     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
7100     SDValue VL = DAG.getConstant(1, DL, XLenVT);
7101     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7102 
7103     // Unless the index is known to be 0, we must slide the vector down to get
7104     // the desired element into index 0.
7105     if (!isNullConstant(Idx)) {
7106       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
7107                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
7108     }
7109 
7110     // Extract the lower XLEN bits of the correct vector element.
7111     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7112 
7113     // To extract the upper XLEN bits of the vector element, shift the first
7114     // element right by 32 bits and re-extract the lower XLEN bits.
7115     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
7116                                      DAG.getUNDEF(ContainerVT),
7117                                      DAG.getConstant(32, DL, XLenVT), VL);
7118     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
7119                                  ThirtyTwoV, Mask, VL);
7120 
7121     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7122 
7123     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7124     break;
7125   }
7126   case ISD::INTRINSIC_WO_CHAIN: {
7127     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7128     switch (IntNo) {
7129     default:
7130       llvm_unreachable(
7131           "Don't know how to custom type legalize this intrinsic!");
7132     case Intrinsic::riscv_grev:
7133     case Intrinsic::riscv_gorc: {
7134       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7135              "Unexpected custom legalisation");
7136       SDValue NewOp1 =
7137           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7138       SDValue NewOp2 =
7139           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7140       unsigned Opc =
7141           IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW;
7142       // If the control is a constant, promote the node by clearing any extra
7143       // bits bits in the control. isel will form greviw/gorciw if the result is
7144       // sign extended.
7145       if (isa<ConstantSDNode>(NewOp2)) {
7146         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7147                              DAG.getConstant(0x1f, DL, MVT::i64));
7148         Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
7149       }
7150       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7151       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7152       break;
7153     }
7154     case Intrinsic::riscv_bcompress:
7155     case Intrinsic::riscv_bdecompress:
7156     case Intrinsic::riscv_bfp: {
7157       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7158              "Unexpected custom legalisation");
7159       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
7160       break;
7161     }
7162     case Intrinsic::riscv_fsl:
7163     case Intrinsic::riscv_fsr: {
7164       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7165              "Unexpected custom legalisation");
7166       SDValue NewOp1 =
7167           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7168       SDValue NewOp2 =
7169           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7170       SDValue NewOp3 =
7171           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3));
7172       unsigned Opc = getRISCVWOpcodeByIntr(IntNo);
7173       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3);
7174       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7175       break;
7176     }
7177     case Intrinsic::riscv_orc_b: {
7178       // Lower to the GORCI encoding for orc.b with the operand extended.
7179       SDValue NewOp =
7180           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7181       SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp,
7182                                 DAG.getConstant(7, DL, MVT::i64));
7183       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7184       return;
7185     }
7186     case Intrinsic::riscv_shfl:
7187     case Intrinsic::riscv_unshfl: {
7188       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
7189              "Unexpected custom legalisation");
7190       SDValue NewOp1 =
7191           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
7192       SDValue NewOp2 =
7193           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
7194       unsigned Opc =
7195           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
7196       // There is no (UN)SHFLIW. If the control word is a constant, we can use
7197       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
7198       // will be shuffled the same way as the lower 32 bit half, but the two
7199       // halves won't cross.
7200       if (isa<ConstantSDNode>(NewOp2)) {
7201         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
7202                              DAG.getConstant(0xf, DL, MVT::i64));
7203         Opc =
7204             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
7205       }
7206       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
7207       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
7208       break;
7209     }
7210     case Intrinsic::riscv_vmv_x_s: {
7211       EVT VT = N->getValueType(0);
7212       MVT XLenVT = Subtarget.getXLenVT();
7213       if (VT.bitsLT(XLenVT)) {
7214         // Simple case just extract using vmv.x.s and truncate.
7215         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
7216                                       Subtarget.getXLenVT(), N->getOperand(1));
7217         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
7218         return;
7219       }
7220 
7221       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
7222              "Unexpected custom legalization");
7223 
7224       // We need to do the move in two steps.
7225       SDValue Vec = N->getOperand(1);
7226       MVT VecVT = Vec.getSimpleValueType();
7227 
7228       // First extract the lower XLEN bits of the element.
7229       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
7230 
7231       // To extract the upper XLEN bits of the vector element, shift the first
7232       // element right by 32 bits and re-extract the lower XLEN bits.
7233       SDValue VL = DAG.getConstant(1, DL, XLenVT);
7234       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
7235       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
7236       SDValue ThirtyTwoV =
7237           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
7238                       DAG.getConstant(32, DL, XLenVT), VL);
7239       SDValue LShr32 =
7240           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
7241       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
7242 
7243       Results.push_back(
7244           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
7245       break;
7246     }
7247     }
7248     break;
7249   }
7250   case ISD::VECREDUCE_ADD:
7251   case ISD::VECREDUCE_AND:
7252   case ISD::VECREDUCE_OR:
7253   case ISD::VECREDUCE_XOR:
7254   case ISD::VECREDUCE_SMAX:
7255   case ISD::VECREDUCE_UMAX:
7256   case ISD::VECREDUCE_SMIN:
7257   case ISD::VECREDUCE_UMIN:
7258     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
7259       Results.push_back(V);
7260     break;
7261   case ISD::VP_REDUCE_ADD:
7262   case ISD::VP_REDUCE_AND:
7263   case ISD::VP_REDUCE_OR:
7264   case ISD::VP_REDUCE_XOR:
7265   case ISD::VP_REDUCE_SMAX:
7266   case ISD::VP_REDUCE_UMAX:
7267   case ISD::VP_REDUCE_SMIN:
7268   case ISD::VP_REDUCE_UMIN:
7269     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
7270       Results.push_back(V);
7271     break;
7272   case ISD::FLT_ROUNDS_: {
7273     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7274     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7275     Results.push_back(Res.getValue(0));
7276     Results.push_back(Res.getValue(1));
7277     break;
7278   }
7279   }
7280 }
7281 
7282 // A structure to hold one of the bit-manipulation patterns below. Together, a
7283 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7284 //   (or (and (shl x, 1), 0xAAAAAAAA),
7285 //       (and (srl x, 1), 0x55555555))
7286 struct RISCVBitmanipPat {
7287   SDValue Op;
7288   unsigned ShAmt;
7289   bool IsSHL;
7290 
7291   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7292     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7293   }
7294 };
7295 
7296 // Matches patterns of the form
7297 //   (and (shl x, C2), (C1 << C2))
7298 //   (and (srl x, C2), C1)
7299 //   (shl (and x, C1), C2)
7300 //   (srl (and x, (C1 << C2)), C2)
7301 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7302 // The expected masks for each shift amount are specified in BitmanipMasks where
7303 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7304 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7305 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7306 // XLen is 64.
7307 static Optional<RISCVBitmanipPat>
7308 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7309   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7310          "Unexpected number of masks");
7311   Optional<uint64_t> Mask;
7312   // Optionally consume a mask around the shift operation.
7313   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7314     Mask = Op.getConstantOperandVal(1);
7315     Op = Op.getOperand(0);
7316   }
7317   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7318     return None;
7319   bool IsSHL = Op.getOpcode() == ISD::SHL;
7320 
7321   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7322     return None;
7323   uint64_t ShAmt = Op.getConstantOperandVal(1);
7324 
7325   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7326   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7327     return None;
7328   // If we don't have enough masks for 64 bit, then we must be trying to
7329   // match SHFL so we're only allowed to shift 1/4 of the width.
7330   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7331     return None;
7332 
7333   SDValue Src = Op.getOperand(0);
7334 
7335   // The expected mask is shifted left when the AND is found around SHL
7336   // patterns.
7337   //   ((x >> 1) & 0x55555555)
7338   //   ((x << 1) & 0xAAAAAAAA)
7339   bool SHLExpMask = IsSHL;
7340 
7341   if (!Mask) {
7342     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7343     // the mask is all ones: consume that now.
7344     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7345       Mask = Src.getConstantOperandVal(1);
7346       Src = Src.getOperand(0);
7347       // The expected mask is now in fact shifted left for SRL, so reverse the
7348       // decision.
7349       //   ((x & 0xAAAAAAAA) >> 1)
7350       //   ((x & 0x55555555) << 1)
7351       SHLExpMask = !SHLExpMask;
7352     } else {
7353       // Use a default shifted mask of all-ones if there's no AND, truncated
7354       // down to the expected width. This simplifies the logic later on.
7355       Mask = maskTrailingOnes<uint64_t>(Width);
7356       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7357     }
7358   }
7359 
7360   unsigned MaskIdx = Log2_32(ShAmt);
7361   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7362 
7363   if (SHLExpMask)
7364     ExpMask <<= ShAmt;
7365 
7366   if (Mask != ExpMask)
7367     return None;
7368 
7369   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7370 }
7371 
7372 // Matches any of the following bit-manipulation patterns:
7373 //   (and (shl x, 1), (0x55555555 << 1))
7374 //   (and (srl x, 1), 0x55555555)
7375 //   (shl (and x, 0x55555555), 1)
7376 //   (srl (and x, (0x55555555 << 1)), 1)
7377 // where the shift amount and mask may vary thus:
7378 //   [1]  = 0x55555555 / 0xAAAAAAAA
7379 //   [2]  = 0x33333333 / 0xCCCCCCCC
7380 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7381 //   [8]  = 0x00FF00FF / 0xFF00FF00
7382 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7383 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7384 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7385   // These are the unshifted masks which we use to match bit-manipulation
7386   // patterns. They may be shifted left in certain circumstances.
7387   static const uint64_t BitmanipMasks[] = {
7388       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7389       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7390 
7391   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7392 }
7393 
7394 // Match the following pattern as a GREVI(W) operation
7395 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7396 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7397                                const RISCVSubtarget &Subtarget) {
7398   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7399   EVT VT = Op.getValueType();
7400 
7401   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7402     auto LHS = matchGREVIPat(Op.getOperand(0));
7403     auto RHS = matchGREVIPat(Op.getOperand(1));
7404     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7405       SDLoc DL(Op);
7406       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7407                          DAG.getConstant(LHS->ShAmt, DL, VT));
7408     }
7409   }
7410   return SDValue();
7411 }
7412 
7413 // Matches any the following pattern as a GORCI(W) operation
7414 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7415 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7416 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7417 // Note that with the variant of 3.,
7418 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7419 // the inner pattern will first be matched as GREVI and then the outer
7420 // pattern will be matched to GORC via the first rule above.
7421 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7422 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7423                                const RISCVSubtarget &Subtarget) {
7424   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7425   EVT VT = Op.getValueType();
7426 
7427   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7428     SDLoc DL(Op);
7429     SDValue Op0 = Op.getOperand(0);
7430     SDValue Op1 = Op.getOperand(1);
7431 
7432     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7433       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7434           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7435           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7436         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7437       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7438       if ((Reverse.getOpcode() == ISD::ROTL ||
7439            Reverse.getOpcode() == ISD::ROTR) &&
7440           Reverse.getOperand(0) == X &&
7441           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7442         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7443         if (RotAmt == (VT.getSizeInBits() / 2))
7444           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7445                              DAG.getConstant(RotAmt, DL, VT));
7446       }
7447       return SDValue();
7448     };
7449 
7450     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7451     if (SDValue V = MatchOROfReverse(Op0, Op1))
7452       return V;
7453     if (SDValue V = MatchOROfReverse(Op1, Op0))
7454       return V;
7455 
7456     // OR is commutable so canonicalize its OR operand to the left
7457     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7458       std::swap(Op0, Op1);
7459     if (Op0.getOpcode() != ISD::OR)
7460       return SDValue();
7461     SDValue OrOp0 = Op0.getOperand(0);
7462     SDValue OrOp1 = Op0.getOperand(1);
7463     auto LHS = matchGREVIPat(OrOp0);
7464     // OR is commutable so swap the operands and try again: x might have been
7465     // on the left
7466     if (!LHS) {
7467       std::swap(OrOp0, OrOp1);
7468       LHS = matchGREVIPat(OrOp0);
7469     }
7470     auto RHS = matchGREVIPat(Op1);
7471     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7472       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7473                          DAG.getConstant(LHS->ShAmt, DL, VT));
7474     }
7475   }
7476   return SDValue();
7477 }
7478 
7479 // Matches any of the following bit-manipulation patterns:
7480 //   (and (shl x, 1), (0x22222222 << 1))
7481 //   (and (srl x, 1), 0x22222222)
7482 //   (shl (and x, 0x22222222), 1)
7483 //   (srl (and x, (0x22222222 << 1)), 1)
7484 // where the shift amount and mask may vary thus:
7485 //   [1]  = 0x22222222 / 0x44444444
7486 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7487 //   [4]  = 0x00F000F0 / 0x0F000F00
7488 //   [8]  = 0x0000FF00 / 0x00FF0000
7489 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7490 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7491   // These are the unshifted masks which we use to match bit-manipulation
7492   // patterns. They may be shifted left in certain circumstances.
7493   static const uint64_t BitmanipMasks[] = {
7494       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7495       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7496 
7497   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7498 }
7499 
7500 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7501 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7502                                const RISCVSubtarget &Subtarget) {
7503   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7504   EVT VT = Op.getValueType();
7505 
7506   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7507     return SDValue();
7508 
7509   SDValue Op0 = Op.getOperand(0);
7510   SDValue Op1 = Op.getOperand(1);
7511 
7512   // Or is commutable so canonicalize the second OR to the LHS.
7513   if (Op0.getOpcode() != ISD::OR)
7514     std::swap(Op0, Op1);
7515   if (Op0.getOpcode() != ISD::OR)
7516     return SDValue();
7517 
7518   // We found an inner OR, so our operands are the operands of the inner OR
7519   // and the other operand of the outer OR.
7520   SDValue A = Op0.getOperand(0);
7521   SDValue B = Op0.getOperand(1);
7522   SDValue C = Op1;
7523 
7524   auto Match1 = matchSHFLPat(A);
7525   auto Match2 = matchSHFLPat(B);
7526 
7527   // If neither matched, we failed.
7528   if (!Match1 && !Match2)
7529     return SDValue();
7530 
7531   // We had at least one match. if one failed, try the remaining C operand.
7532   if (!Match1) {
7533     std::swap(A, C);
7534     Match1 = matchSHFLPat(A);
7535     if (!Match1)
7536       return SDValue();
7537   } else if (!Match2) {
7538     std::swap(B, C);
7539     Match2 = matchSHFLPat(B);
7540     if (!Match2)
7541       return SDValue();
7542   }
7543   assert(Match1 && Match2);
7544 
7545   // Make sure our matches pair up.
7546   if (!Match1->formsPairWith(*Match2))
7547     return SDValue();
7548 
7549   // All the remains is to make sure C is an AND with the same input, that masks
7550   // out the bits that are being shuffled.
7551   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7552       C.getOperand(0) != Match1->Op)
7553     return SDValue();
7554 
7555   uint64_t Mask = C.getConstantOperandVal(1);
7556 
7557   static const uint64_t BitmanipMasks[] = {
7558       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7559       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7560   };
7561 
7562   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7563   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7564   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7565 
7566   if (Mask != ExpMask)
7567     return SDValue();
7568 
7569   SDLoc DL(Op);
7570   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7571                      DAG.getConstant(Match1->ShAmt, DL, VT));
7572 }
7573 
7574 // Optimize (add (shl x, c0), (shl y, c1)) ->
7575 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7576 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7577                                   const RISCVSubtarget &Subtarget) {
7578   // Perform this optimization only in the zba extension.
7579   if (!Subtarget.hasStdExtZba())
7580     return SDValue();
7581 
7582   // Skip for vector types and larger types.
7583   EVT VT = N->getValueType(0);
7584   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7585     return SDValue();
7586 
7587   // The two operand nodes must be SHL and have no other use.
7588   SDValue N0 = N->getOperand(0);
7589   SDValue N1 = N->getOperand(1);
7590   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7591       !N0->hasOneUse() || !N1->hasOneUse())
7592     return SDValue();
7593 
7594   // Check c0 and c1.
7595   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7596   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7597   if (!N0C || !N1C)
7598     return SDValue();
7599   int64_t C0 = N0C->getSExtValue();
7600   int64_t C1 = N1C->getSExtValue();
7601   if (C0 <= 0 || C1 <= 0)
7602     return SDValue();
7603 
7604   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7605   int64_t Bits = std::min(C0, C1);
7606   int64_t Diff = std::abs(C0 - C1);
7607   if (Diff != 1 && Diff != 2 && Diff != 3)
7608     return SDValue();
7609 
7610   // Build nodes.
7611   SDLoc DL(N);
7612   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7613   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7614   SDValue NA0 =
7615       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7616   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7617   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7618 }
7619 
7620 // Combine
7621 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7622 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32
7623 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7624 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64
7625 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7626 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64
7627 // The grev patterns represents BSWAP.
7628 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7629 // off the grev.
7630 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7631                                           const RISCVSubtarget &Subtarget) {
7632   bool IsWInstruction =
7633       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7634   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7635           IsWInstruction) &&
7636          "Unexpected opcode!");
7637   SDValue Src = N->getOperand(0);
7638   EVT VT = N->getValueType(0);
7639   SDLoc DL(N);
7640 
7641   if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV)
7642     return SDValue();
7643 
7644   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7645       !isa<ConstantSDNode>(Src.getOperand(1)))
7646     return SDValue();
7647 
7648   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7649   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7650 
7651   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7652   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7653   unsigned ShAmt1 = N->getConstantOperandVal(1);
7654   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7655   if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7656     return SDValue();
7657 
7658   Src = Src.getOperand(0);
7659 
7660   // Toggle bit the MSB of the shift.
7661   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7662   if (CombinedShAmt == 0)
7663     return Src;
7664 
7665   SDValue Res = DAG.getNode(
7666       RISCVISD::GREV, DL, VT, Src,
7667       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7668   if (!IsWInstruction)
7669     return Res;
7670 
7671   // Sign extend the result to match the behavior of the rotate. This will be
7672   // selected to GREVIW in isel.
7673   return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res,
7674                      DAG.getValueType(MVT::i32));
7675 }
7676 
7677 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7678 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7679 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7680 // not undo itself, but they are redundant.
7681 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7682   bool IsGORC = N->getOpcode() == RISCVISD::GORC;
7683   assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode");
7684   SDValue Src = N->getOperand(0);
7685 
7686   if (Src.getOpcode() != N->getOpcode())
7687     return SDValue();
7688 
7689   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7690       !isa<ConstantSDNode>(Src.getOperand(1)))
7691     return SDValue();
7692 
7693   unsigned ShAmt1 = N->getConstantOperandVal(1);
7694   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7695   Src = Src.getOperand(0);
7696 
7697   unsigned CombinedShAmt;
7698   if (IsGORC)
7699     CombinedShAmt = ShAmt1 | ShAmt2;
7700   else
7701     CombinedShAmt = ShAmt1 ^ ShAmt2;
7702 
7703   if (CombinedShAmt == 0)
7704     return Src;
7705 
7706   SDLoc DL(N);
7707   return DAG.getNode(
7708       N->getOpcode(), DL, N->getValueType(0), Src,
7709       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7710 }
7711 
7712 // Combine a constant select operand into its use:
7713 //
7714 // (and (select cond, -1, c), x)
7715 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7716 // (or  (select cond, 0, c), x)
7717 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7718 // (xor (select cond, 0, c), x)
7719 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7720 // (add (select cond, 0, c), x)
7721 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7722 // (sub x, (select cond, 0, c))
7723 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7724 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7725                                    SelectionDAG &DAG, bool AllOnes) {
7726   EVT VT = N->getValueType(0);
7727 
7728   // Skip vectors.
7729   if (VT.isVector())
7730     return SDValue();
7731 
7732   if ((Slct.getOpcode() != ISD::SELECT &&
7733        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7734       !Slct.hasOneUse())
7735     return SDValue();
7736 
7737   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7738     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7739   };
7740 
7741   bool SwapSelectOps;
7742   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7743   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7744   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7745   SDValue NonConstantVal;
7746   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7747     SwapSelectOps = false;
7748     NonConstantVal = FalseVal;
7749   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7750     SwapSelectOps = true;
7751     NonConstantVal = TrueVal;
7752   } else
7753     return SDValue();
7754 
7755   // Slct is now know to be the desired identity constant when CC is true.
7756   TrueVal = OtherOp;
7757   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7758   // Unless SwapSelectOps says the condition should be false.
7759   if (SwapSelectOps)
7760     std::swap(TrueVal, FalseVal);
7761 
7762   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7763     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7764                        {Slct.getOperand(0), Slct.getOperand(1),
7765                         Slct.getOperand(2), TrueVal, FalseVal});
7766 
7767   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7768                      {Slct.getOperand(0), TrueVal, FalseVal});
7769 }
7770 
7771 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7772 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7773                                               bool AllOnes) {
7774   SDValue N0 = N->getOperand(0);
7775   SDValue N1 = N->getOperand(1);
7776   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7777     return Result;
7778   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7779     return Result;
7780   return SDValue();
7781 }
7782 
7783 // Transform (add (mul x, c0), c1) ->
7784 //           (add (mul (add x, c1/c0), c0), c1%c0).
7785 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7786 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7787 // to an infinite loop in DAGCombine if transformed.
7788 // Or transform (add (mul x, c0), c1) ->
7789 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7790 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7791 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7792 // lead to an infinite loop in DAGCombine if transformed.
7793 // Or transform (add (mul x, c0), c1) ->
7794 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7795 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7796 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7797 // lead to an infinite loop in DAGCombine if transformed.
7798 // Or transform (add (mul x, c0), c1) ->
7799 //              (mul (add x, c1/c0), c0).
7800 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7801 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7802                                      const RISCVSubtarget &Subtarget) {
7803   // Skip for vector types and larger types.
7804   EVT VT = N->getValueType(0);
7805   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7806     return SDValue();
7807   // The first operand node must be a MUL and has no other use.
7808   SDValue N0 = N->getOperand(0);
7809   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7810     return SDValue();
7811   // Check if c0 and c1 match above conditions.
7812   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7813   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7814   if (!N0C || !N1C)
7815     return SDValue();
7816   // If N0C has multiple uses it's possible one of the cases in
7817   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7818   // in an infinite loop.
7819   if (!N0C->hasOneUse())
7820     return SDValue();
7821   int64_t C0 = N0C->getSExtValue();
7822   int64_t C1 = N1C->getSExtValue();
7823   int64_t CA, CB;
7824   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7825     return SDValue();
7826   // Search for proper CA (non-zero) and CB that both are simm12.
7827   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7828       !isInt<12>(C0 * (C1 / C0))) {
7829     CA = C1 / C0;
7830     CB = C1 % C0;
7831   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7832              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7833     CA = C1 / C0 + 1;
7834     CB = C1 % C0 - C0;
7835   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7836              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7837     CA = C1 / C0 - 1;
7838     CB = C1 % C0 + C0;
7839   } else
7840     return SDValue();
7841   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7842   SDLoc DL(N);
7843   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7844                              DAG.getConstant(CA, DL, VT));
7845   SDValue New1 =
7846       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7847   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7848 }
7849 
7850 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7851                                  const RISCVSubtarget &Subtarget) {
7852   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7853     return V;
7854   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7855     return V;
7856   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7857   //      (select lhs, rhs, cc, x, (add x, y))
7858   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7859 }
7860 
7861 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7862   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7863   //      (select lhs, rhs, cc, x, (sub x, y))
7864   SDValue N0 = N->getOperand(0);
7865   SDValue N1 = N->getOperand(1);
7866   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7867 }
7868 
7869 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7870   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7871   //      (select lhs, rhs, cc, x, (and x, y))
7872   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7873 }
7874 
7875 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7876                                 const RISCVSubtarget &Subtarget) {
7877   if (Subtarget.hasStdExtZbp()) {
7878     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7879       return GREV;
7880     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7881       return GORC;
7882     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7883       return SHFL;
7884   }
7885 
7886   // fold (or (select cond, 0, y), x) ->
7887   //      (select cond, x, (or x, y))
7888   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7889 }
7890 
7891 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7892   // fold (xor (select cond, 0, y), x) ->
7893   //      (select cond, x, (xor x, y))
7894   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7895 }
7896 
7897 static SDValue
7898 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
7899                                 const RISCVSubtarget &Subtarget) {
7900   SDValue Src = N->getOperand(0);
7901   EVT VT = N->getValueType(0);
7902 
7903   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
7904   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7905       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
7906     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
7907                        Src.getOperand(0));
7908 
7909   // Fold (i64 (sext_inreg (abs X), i32)) ->
7910   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
7911   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
7912   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
7913   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
7914   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
7915   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
7916   // may get combined into an earlier operation so we need to use
7917   // ComputeNumSignBits.
7918   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
7919   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
7920   // we can't assume that X has 33 sign bits. We must check.
7921   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
7922       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
7923       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
7924       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
7925     SDLoc DL(N);
7926     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
7927     SDValue Neg =
7928         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
7929     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
7930                       DAG.getValueType(MVT::i32));
7931     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
7932   }
7933 
7934   return SDValue();
7935 }
7936 
7937 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
7938 // vwadd(u).vv/vx or vwsub(u).vv/vx.
7939 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
7940                                              bool Commute = false) {
7941   assert((N->getOpcode() == RISCVISD::ADD_VL ||
7942           N->getOpcode() == RISCVISD::SUB_VL) &&
7943          "Unexpected opcode");
7944   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
7945   SDValue Op0 = N->getOperand(0);
7946   SDValue Op1 = N->getOperand(1);
7947   if (Commute)
7948     std::swap(Op0, Op1);
7949 
7950   MVT VT = N->getSimpleValueType(0);
7951 
7952   // Determine the narrow size for a widening add/sub.
7953   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7954   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7955                                   VT.getVectorElementCount());
7956 
7957   SDValue Mask = N->getOperand(2);
7958   SDValue VL = N->getOperand(3);
7959 
7960   SDLoc DL(N);
7961 
7962   // If the RHS is a sext or zext, we can form a widening op.
7963   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
7964        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
7965       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
7966     unsigned ExtOpc = Op1.getOpcode();
7967     Op1 = Op1.getOperand(0);
7968     // Re-introduce narrower extends if needed.
7969     if (Op1.getValueType() != NarrowVT)
7970       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7971 
7972     unsigned WOpc;
7973     if (ExtOpc == RISCVISD::VSEXT_VL)
7974       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
7975     else
7976       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
7977 
7978     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
7979   }
7980 
7981   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
7982   // sext/zext?
7983 
7984   return SDValue();
7985 }
7986 
7987 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
7988 // vwsub(u).vv/vx.
7989 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
7990   SDValue Op0 = N->getOperand(0);
7991   SDValue Op1 = N->getOperand(1);
7992   SDValue Mask = N->getOperand(2);
7993   SDValue VL = N->getOperand(3);
7994 
7995   MVT VT = N->getSimpleValueType(0);
7996   MVT NarrowVT = Op1.getSimpleValueType();
7997   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
7998 
7999   unsigned VOpc;
8000   switch (N->getOpcode()) {
8001   default: llvm_unreachable("Unexpected opcode");
8002   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
8003   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
8004   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
8005   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
8006   }
8007 
8008   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8009                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
8010 
8011   SDLoc DL(N);
8012 
8013   // If the LHS is a sext or zext, we can narrow this op to the same size as
8014   // the RHS.
8015   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
8016        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
8017       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
8018     unsigned ExtOpc = Op0.getOpcode();
8019     Op0 = Op0.getOperand(0);
8020     // Re-introduce narrower extends if needed.
8021     if (Op0.getValueType() != NarrowVT)
8022       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8023     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
8024   }
8025 
8026   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
8027                N->getOpcode() == RISCVISD::VWADDU_W_VL;
8028 
8029   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
8030   // to commute and use a vwadd(u).vx instead.
8031   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
8032       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
8033     Op0 = Op0.getOperand(1);
8034 
8035     // See if have enough sign bits or zero bits in the scalar to use a
8036     // widening add/sub by splatting to smaller element size.
8037     unsigned EltBits = VT.getScalarSizeInBits();
8038     unsigned ScalarBits = Op0.getValueSizeInBits();
8039     // Make sure we're getting all element bits from the scalar register.
8040     // FIXME: Support implicit sign extension of vmv.v.x?
8041     if (ScalarBits < EltBits)
8042       return SDValue();
8043 
8044     if (IsSigned) {
8045       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
8046         return SDValue();
8047     } else {
8048       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8049       if (!DAG.MaskedValueIsZero(Op0, Mask))
8050         return SDValue();
8051     }
8052 
8053     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8054                       DAG.getUNDEF(NarrowVT), Op0, VL);
8055     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
8056   }
8057 
8058   return SDValue();
8059 }
8060 
8061 // Try to form VWMUL, VWMULU or VWMULSU.
8062 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
8063 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
8064                                        bool Commute) {
8065   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
8066   SDValue Op0 = N->getOperand(0);
8067   SDValue Op1 = N->getOperand(1);
8068   if (Commute)
8069     std::swap(Op0, Op1);
8070 
8071   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
8072   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
8073   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
8074   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
8075     return SDValue();
8076 
8077   SDValue Mask = N->getOperand(2);
8078   SDValue VL = N->getOperand(3);
8079 
8080   // Make sure the mask and VL match.
8081   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
8082     return SDValue();
8083 
8084   MVT VT = N->getSimpleValueType(0);
8085 
8086   // Determine the narrow size for a widening multiply.
8087   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
8088   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
8089                                   VT.getVectorElementCount());
8090 
8091   SDLoc DL(N);
8092 
8093   // See if the other operand is the same opcode.
8094   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
8095     if (!Op1.hasOneUse())
8096       return SDValue();
8097 
8098     // Make sure the mask and VL match.
8099     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
8100       return SDValue();
8101 
8102     Op1 = Op1.getOperand(0);
8103   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
8104     // The operand is a splat of a scalar.
8105 
8106     // The pasthru must be undef for tail agnostic
8107     if (!Op1.getOperand(0).isUndef())
8108       return SDValue();
8109     // The VL must be the same.
8110     if (Op1.getOperand(2) != VL)
8111       return SDValue();
8112 
8113     // Get the scalar value.
8114     Op1 = Op1.getOperand(1);
8115 
8116     // See if have enough sign bits or zero bits in the scalar to use a
8117     // widening multiply by splatting to smaller element size.
8118     unsigned EltBits = VT.getScalarSizeInBits();
8119     unsigned ScalarBits = Op1.getValueSizeInBits();
8120     // Make sure we're getting all element bits from the scalar register.
8121     // FIXME: Support implicit sign extension of vmv.v.x?
8122     if (ScalarBits < EltBits)
8123       return SDValue();
8124 
8125     // If the LHS is a sign extend, try to use vwmul.
8126     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
8127       // Can use vwmul.
8128     } else {
8129       // Otherwise try to use vwmulu or vwmulsu.
8130       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
8131       if (DAG.MaskedValueIsZero(Op1, Mask))
8132         IsVWMULSU = IsSignExt;
8133       else
8134         return SDValue();
8135     }
8136 
8137     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
8138                       DAG.getUNDEF(NarrowVT), Op1, VL);
8139   } else
8140     return SDValue();
8141 
8142   Op0 = Op0.getOperand(0);
8143 
8144   // Re-introduce narrower extends if needed.
8145   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
8146   if (Op0.getValueType() != NarrowVT)
8147     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
8148   // vwmulsu requires second operand to be zero extended.
8149   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
8150   if (Op1.getValueType() != NarrowVT)
8151     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
8152 
8153   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
8154   if (!IsVWMULSU)
8155     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
8156   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
8157 }
8158 
8159 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
8160   switch (Op.getOpcode()) {
8161   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
8162   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
8163   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
8164   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
8165   case ISD::FROUND:     return RISCVFPRndMode::RMM;
8166   }
8167 
8168   return RISCVFPRndMode::Invalid;
8169 }
8170 
8171 // Fold
8172 //   (fp_to_int (froundeven X)) -> fcvt X, rne
8173 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
8174 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
8175 //   (fp_to_int (fceil X))      -> fcvt X, rup
8176 //   (fp_to_int (fround X))     -> fcvt X, rmm
8177 static SDValue performFP_TO_INTCombine(SDNode *N,
8178                                        TargetLowering::DAGCombinerInfo &DCI,
8179                                        const RISCVSubtarget &Subtarget) {
8180   SelectionDAG &DAG = DCI.DAG;
8181   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8182   MVT XLenVT = Subtarget.getXLenVT();
8183 
8184   // Only handle XLen or i32 types. Other types narrower than XLen will
8185   // eventually be legalized to XLenVT.
8186   EVT VT = N->getValueType(0);
8187   if (VT != MVT::i32 && VT != XLenVT)
8188     return SDValue();
8189 
8190   SDValue Src = N->getOperand(0);
8191 
8192   // Ensure the FP type is also legal.
8193   if (!TLI.isTypeLegal(Src.getValueType()))
8194     return SDValue();
8195 
8196   // Don't do this for f16 with Zfhmin and not Zfh.
8197   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8198     return SDValue();
8199 
8200   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8201   if (FRM == RISCVFPRndMode::Invalid)
8202     return SDValue();
8203 
8204   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8205 
8206   unsigned Opc;
8207   if (VT == XLenVT)
8208     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8209   else
8210     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8211 
8212   SDLoc DL(N);
8213   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8214                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8215   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8216 }
8217 
8218 // Fold
8219 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8220 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8221 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8222 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8223 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8224 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8225                                        TargetLowering::DAGCombinerInfo &DCI,
8226                                        const RISCVSubtarget &Subtarget) {
8227   SelectionDAG &DAG = DCI.DAG;
8228   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8229   MVT XLenVT = Subtarget.getXLenVT();
8230 
8231   // Only handle XLen types. Other types narrower than XLen will eventually be
8232   // legalized to XLenVT.
8233   EVT DstVT = N->getValueType(0);
8234   if (DstVT != XLenVT)
8235     return SDValue();
8236 
8237   SDValue Src = N->getOperand(0);
8238 
8239   // Ensure the FP type is also legal.
8240   if (!TLI.isTypeLegal(Src.getValueType()))
8241     return SDValue();
8242 
8243   // Don't do this for f16 with Zfhmin and not Zfh.
8244   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8245     return SDValue();
8246 
8247   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8248 
8249   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8250   if (FRM == RISCVFPRndMode::Invalid)
8251     return SDValue();
8252 
8253   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8254 
8255   unsigned Opc;
8256   if (SatVT == DstVT)
8257     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8258   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8259     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8260   else
8261     return SDValue();
8262   // FIXME: Support other SatVTs by clamping before or after the conversion.
8263 
8264   Src = Src.getOperand(0);
8265 
8266   SDLoc DL(N);
8267   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8268                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8269 
8270   // RISCV FP-to-int conversions saturate to the destination register size, but
8271   // don't produce 0 for nan.
8272   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8273   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8274 }
8275 
8276 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
8277 // smaller than XLenVT.
8278 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
8279                                         const RISCVSubtarget &Subtarget) {
8280   assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
8281 
8282   SDValue Src = N->getOperand(0);
8283   if (Src.getOpcode() != ISD::BSWAP)
8284     return SDValue();
8285 
8286   EVT VT = N->getValueType(0);
8287   if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
8288       !isPowerOf2_32(VT.getSizeInBits()))
8289     return SDValue();
8290 
8291   SDLoc DL(N);
8292   return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0),
8293                      DAG.getConstant(7, DL, VT));
8294 }
8295 
8296 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8297                                                DAGCombinerInfo &DCI) const {
8298   SelectionDAG &DAG = DCI.DAG;
8299 
8300   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8301   // bits are demanded. N will be added to the Worklist if it was not deleted.
8302   // Caller should return SDValue(N, 0) if this returns true.
8303   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8304     SDValue Op = N->getOperand(OpNo);
8305     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8306     if (!SimplifyDemandedBits(Op, Mask, DCI))
8307       return false;
8308 
8309     if (N->getOpcode() != ISD::DELETED_NODE)
8310       DCI.AddToWorklist(N);
8311     return true;
8312   };
8313 
8314   switch (N->getOpcode()) {
8315   default:
8316     break;
8317   case RISCVISD::SplitF64: {
8318     SDValue Op0 = N->getOperand(0);
8319     // If the input to SplitF64 is just BuildPairF64 then the operation is
8320     // redundant. Instead, use BuildPairF64's operands directly.
8321     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8322       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8323 
8324     if (Op0->isUndef()) {
8325       SDValue Lo = DAG.getUNDEF(MVT::i32);
8326       SDValue Hi = DAG.getUNDEF(MVT::i32);
8327       return DCI.CombineTo(N, Lo, Hi);
8328     }
8329 
8330     SDLoc DL(N);
8331 
8332     // It's cheaper to materialise two 32-bit integers than to load a double
8333     // from the constant pool and transfer it to integer registers through the
8334     // stack.
8335     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8336       APInt V = C->getValueAPF().bitcastToAPInt();
8337       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8338       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8339       return DCI.CombineTo(N, Lo, Hi);
8340     }
8341 
8342     // This is a target-specific version of a DAGCombine performed in
8343     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8344     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8345     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8346     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8347         !Op0.getNode()->hasOneUse())
8348       break;
8349     SDValue NewSplitF64 =
8350         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8351                     Op0.getOperand(0));
8352     SDValue Lo = NewSplitF64.getValue(0);
8353     SDValue Hi = NewSplitF64.getValue(1);
8354     APInt SignBit = APInt::getSignMask(32);
8355     if (Op0.getOpcode() == ISD::FNEG) {
8356       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8357                                   DAG.getConstant(SignBit, DL, MVT::i32));
8358       return DCI.CombineTo(N, Lo, NewHi);
8359     }
8360     assert(Op0.getOpcode() == ISD::FABS);
8361     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8362                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8363     return DCI.CombineTo(N, Lo, NewHi);
8364   }
8365   case RISCVISD::SLLW:
8366   case RISCVISD::SRAW:
8367   case RISCVISD::SRLW: {
8368     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8369     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8370         SimplifyDemandedLowBitsHelper(1, 5))
8371       return SDValue(N, 0);
8372 
8373     break;
8374   }
8375   case ISD::ROTR:
8376   case ISD::ROTL:
8377   case RISCVISD::RORW:
8378   case RISCVISD::ROLW: {
8379     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8380       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8381       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8382           SimplifyDemandedLowBitsHelper(1, 5))
8383         return SDValue(N, 0);
8384     }
8385 
8386     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8387   }
8388   case RISCVISD::CLZW:
8389   case RISCVISD::CTZW: {
8390     // Only the lower 32 bits of the first operand are read
8391     if (SimplifyDemandedLowBitsHelper(0, 32))
8392       return SDValue(N, 0);
8393     break;
8394   }
8395   case RISCVISD::GREV:
8396   case RISCVISD::GORC: {
8397     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8398     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8399     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8400     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8401       return SDValue(N, 0);
8402 
8403     return combineGREVI_GORCI(N, DAG);
8404   }
8405   case RISCVISD::GREVW:
8406   case RISCVISD::GORCW: {
8407     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8408     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8409         SimplifyDemandedLowBitsHelper(1, 5))
8410       return SDValue(N, 0);
8411 
8412     break;
8413   }
8414   case RISCVISD::SHFL:
8415   case RISCVISD::UNSHFL: {
8416     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8417     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8418     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8419     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8420       return SDValue(N, 0);
8421 
8422     break;
8423   }
8424   case RISCVISD::SHFLW:
8425   case RISCVISD::UNSHFLW: {
8426     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8427     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8428         SimplifyDemandedLowBitsHelper(1, 4))
8429       return SDValue(N, 0);
8430 
8431     break;
8432   }
8433   case RISCVISD::BCOMPRESSW:
8434   case RISCVISD::BDECOMPRESSW: {
8435     // Only the lower 32 bits of LHS and RHS are read.
8436     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8437         SimplifyDemandedLowBitsHelper(1, 32))
8438       return SDValue(N, 0);
8439 
8440     break;
8441   }
8442   case RISCVISD::FSR:
8443   case RISCVISD::FSL:
8444   case RISCVISD::FSRW:
8445   case RISCVISD::FSLW: {
8446     bool IsWInstruction =
8447         N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW;
8448     unsigned BitWidth =
8449         IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits();
8450     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8451     // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read.
8452     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1))
8453       return SDValue(N, 0);
8454 
8455     break;
8456   }
8457   case RISCVISD::FMV_X_ANYEXTH:
8458   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8459     SDLoc DL(N);
8460     SDValue Op0 = N->getOperand(0);
8461     MVT VT = N->getSimpleValueType(0);
8462     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8463     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8464     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8465     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8466          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8467         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8468          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8469       assert(Op0.getOperand(0).getValueType() == VT &&
8470              "Unexpected value type!");
8471       return Op0.getOperand(0);
8472     }
8473 
8474     // This is a target-specific version of a DAGCombine performed in
8475     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8476     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8477     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8478     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8479         !Op0.getNode()->hasOneUse())
8480       break;
8481     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8482     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8483     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
8484     if (Op0.getOpcode() == ISD::FNEG)
8485       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8486                          DAG.getConstant(SignBit, DL, VT));
8487 
8488     assert(Op0.getOpcode() == ISD::FABS);
8489     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8490                        DAG.getConstant(~SignBit, DL, VT));
8491   }
8492   case ISD::ADD:
8493     return performADDCombine(N, DAG, Subtarget);
8494   case ISD::SUB:
8495     return performSUBCombine(N, DAG);
8496   case ISD::AND:
8497     return performANDCombine(N, DAG);
8498   case ISD::OR:
8499     return performORCombine(N, DAG, Subtarget);
8500   case ISD::XOR:
8501     return performXORCombine(N, DAG);
8502   case ISD::SIGN_EXTEND_INREG:
8503     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8504   case ISD::ZERO_EXTEND:
8505     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8506     // type legalization. This is safe because fp_to_uint produces poison if
8507     // it overflows.
8508     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8509       SDValue Src = N->getOperand(0);
8510       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8511           isTypeLegal(Src.getOperand(0).getValueType()))
8512         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8513                            Src.getOperand(0));
8514       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8515           isTypeLegal(Src.getOperand(1).getValueType())) {
8516         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8517         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8518                                   Src.getOperand(0), Src.getOperand(1));
8519         DCI.CombineTo(N, Res);
8520         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8521         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8522         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8523       }
8524     }
8525     return SDValue();
8526   case RISCVISD::SELECT_CC: {
8527     // Transform
8528     SDValue LHS = N->getOperand(0);
8529     SDValue RHS = N->getOperand(1);
8530     SDValue TrueV = N->getOperand(3);
8531     SDValue FalseV = N->getOperand(4);
8532 
8533     // If the True and False values are the same, we don't need a select_cc.
8534     if (TrueV == FalseV)
8535       return TrueV;
8536 
8537     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8538     if (!ISD::isIntEqualitySetCC(CCVal))
8539       break;
8540 
8541     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8542     //      (select_cc X, Y, lt, trueV, falseV)
8543     // Sometimes the setcc is introduced after select_cc has been formed.
8544     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8545         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8546       // If we're looking for eq 0 instead of ne 0, we need to invert the
8547       // condition.
8548       bool Invert = CCVal == ISD::SETEQ;
8549       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8550       if (Invert)
8551         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8552 
8553       SDLoc DL(N);
8554       RHS = LHS.getOperand(1);
8555       LHS = LHS.getOperand(0);
8556       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8557 
8558       SDValue TargetCC = DAG.getCondCode(CCVal);
8559       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8560                          {LHS, RHS, TargetCC, TrueV, FalseV});
8561     }
8562 
8563     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8564     //      (select_cc X, Y, eq/ne, trueV, falseV)
8565     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8566       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8567                          {LHS.getOperand(0), LHS.getOperand(1),
8568                           N->getOperand(2), TrueV, FalseV});
8569     // (select_cc X, 1, setne, trueV, falseV) ->
8570     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8571     // This can occur when legalizing some floating point comparisons.
8572     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8573     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8574       SDLoc DL(N);
8575       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8576       SDValue TargetCC = DAG.getCondCode(CCVal);
8577       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8578       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8579                          {LHS, RHS, TargetCC, TrueV, FalseV});
8580     }
8581 
8582     break;
8583   }
8584   case RISCVISD::BR_CC: {
8585     SDValue LHS = N->getOperand(1);
8586     SDValue RHS = N->getOperand(2);
8587     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8588     if (!ISD::isIntEqualitySetCC(CCVal))
8589       break;
8590 
8591     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8592     //      (br_cc X, Y, lt, dest)
8593     // Sometimes the setcc is introduced after br_cc has been formed.
8594     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8595         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8596       // If we're looking for eq 0 instead of ne 0, we need to invert the
8597       // condition.
8598       bool Invert = CCVal == ISD::SETEQ;
8599       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8600       if (Invert)
8601         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8602 
8603       SDLoc DL(N);
8604       RHS = LHS.getOperand(1);
8605       LHS = LHS.getOperand(0);
8606       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8607 
8608       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8609                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8610                          N->getOperand(4));
8611     }
8612 
8613     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8614     //      (br_cc X, Y, eq/ne, trueV, falseV)
8615     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8616       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8617                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8618                          N->getOperand(3), N->getOperand(4));
8619 
8620     // (br_cc X, 1, setne, br_cc) ->
8621     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8622     // This can occur when legalizing some floating point comparisons.
8623     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8624     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8625       SDLoc DL(N);
8626       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8627       SDValue TargetCC = DAG.getCondCode(CCVal);
8628       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8629       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8630                          N->getOperand(0), LHS, RHS, TargetCC,
8631                          N->getOperand(4));
8632     }
8633     break;
8634   }
8635   case ISD::BITREVERSE:
8636     return performBITREVERSECombine(N, DAG, Subtarget);
8637   case ISD::FP_TO_SINT:
8638   case ISD::FP_TO_UINT:
8639     return performFP_TO_INTCombine(N, DCI, Subtarget);
8640   case ISD::FP_TO_SINT_SAT:
8641   case ISD::FP_TO_UINT_SAT:
8642     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8643   case ISD::FCOPYSIGN: {
8644     EVT VT = N->getValueType(0);
8645     if (!VT.isVector())
8646       break;
8647     // There is a form of VFSGNJ which injects the negated sign of its second
8648     // operand. Try and bubble any FNEG up after the extend/round to produce
8649     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8650     // TRUNC=1.
8651     SDValue In2 = N->getOperand(1);
8652     // Avoid cases where the extend/round has multiple uses, as duplicating
8653     // those is typically more expensive than removing a fneg.
8654     if (!In2.hasOneUse())
8655       break;
8656     if (In2.getOpcode() != ISD::FP_EXTEND &&
8657         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8658       break;
8659     In2 = In2.getOperand(0);
8660     if (In2.getOpcode() != ISD::FNEG)
8661       break;
8662     SDLoc DL(N);
8663     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8664     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8665                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8666   }
8667   case ISD::MGATHER:
8668   case ISD::MSCATTER:
8669   case ISD::VP_GATHER:
8670   case ISD::VP_SCATTER: {
8671     if (!DCI.isBeforeLegalize())
8672       break;
8673     SDValue Index, ScaleOp;
8674     bool IsIndexScaled = false;
8675     bool IsIndexSigned = false;
8676     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8677       Index = VPGSN->getIndex();
8678       ScaleOp = VPGSN->getScale();
8679       IsIndexScaled = VPGSN->isIndexScaled();
8680       IsIndexSigned = VPGSN->isIndexSigned();
8681     } else {
8682       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8683       Index = MGSN->getIndex();
8684       ScaleOp = MGSN->getScale();
8685       IsIndexScaled = MGSN->isIndexScaled();
8686       IsIndexSigned = MGSN->isIndexSigned();
8687     }
8688     EVT IndexVT = Index.getValueType();
8689     MVT XLenVT = Subtarget.getXLenVT();
8690     // RISCV indexed loads only support the "unsigned unscaled" addressing
8691     // mode, so anything else must be manually legalized.
8692     bool NeedsIdxLegalization =
8693         IsIndexScaled ||
8694         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8695     if (!NeedsIdxLegalization)
8696       break;
8697 
8698     SDLoc DL(N);
8699 
8700     // Any index legalization should first promote to XLenVT, so we don't lose
8701     // bits when scaling. This may create an illegal index type so we let
8702     // LLVM's legalization take care of the splitting.
8703     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8704     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8705       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8706       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8707                           DL, IndexVT, Index);
8708     }
8709 
8710     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8711     if (IsIndexScaled && Scale != 1) {
8712       // Manually scale the indices by the element size.
8713       // TODO: Sanitize the scale operand here?
8714       // TODO: For VP nodes, should we use VP_SHL here?
8715       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8716       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8717       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8718     }
8719 
8720     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
8721     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8722       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8723                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8724                               VPGN->getScale(), VPGN->getMask(),
8725                               VPGN->getVectorLength()},
8726                              VPGN->getMemOperand(), NewIndexTy);
8727     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8728       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8729                               {VPSN->getChain(), VPSN->getValue(),
8730                                VPSN->getBasePtr(), Index, VPSN->getScale(),
8731                                VPSN->getMask(), VPSN->getVectorLength()},
8732                               VPSN->getMemOperand(), NewIndexTy);
8733     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8734       return DAG.getMaskedGather(
8735           N->getVTList(), MGN->getMemoryVT(), DL,
8736           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8737            MGN->getBasePtr(), Index, MGN->getScale()},
8738           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8739     const auto *MSN = cast<MaskedScatterSDNode>(N);
8740     return DAG.getMaskedScatter(
8741         N->getVTList(), MSN->getMemoryVT(), DL,
8742         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8743          Index, MSN->getScale()},
8744         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8745   }
8746   case RISCVISD::SRA_VL:
8747   case RISCVISD::SRL_VL:
8748   case RISCVISD::SHL_VL: {
8749     SDValue ShAmt = N->getOperand(1);
8750     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8751       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8752       SDLoc DL(N);
8753       SDValue VL = N->getOperand(3);
8754       EVT VT = N->getValueType(0);
8755       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8756                           ShAmt.getOperand(1), VL);
8757       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8758                          N->getOperand(2), N->getOperand(3));
8759     }
8760     break;
8761   }
8762   case ISD::SRA:
8763   case ISD::SRL:
8764   case ISD::SHL: {
8765     SDValue ShAmt = N->getOperand(1);
8766     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8767       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8768       SDLoc DL(N);
8769       EVT VT = N->getValueType(0);
8770       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8771                           ShAmt.getOperand(1),
8772                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8773       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8774     }
8775     break;
8776   }
8777   case RISCVISD::ADD_VL:
8778     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8779       return V;
8780     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8781   case RISCVISD::SUB_VL:
8782     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8783   case RISCVISD::VWADD_W_VL:
8784   case RISCVISD::VWADDU_W_VL:
8785   case RISCVISD::VWSUB_W_VL:
8786   case RISCVISD::VWSUBU_W_VL:
8787     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8788   case RISCVISD::MUL_VL:
8789     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8790       return V;
8791     // Mul is commutative.
8792     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8793   case ISD::STORE: {
8794     auto *Store = cast<StoreSDNode>(N);
8795     SDValue Val = Store->getValue();
8796     // Combine store of vmv.x.s to vse with VL of 1.
8797     // FIXME: Support FP.
8798     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8799       SDValue Src = Val.getOperand(0);
8800       EVT VecVT = Src.getValueType();
8801       EVT MemVT = Store->getMemoryVT();
8802       // The memory VT and the element type must match.
8803       if (VecVT.getVectorElementType() == MemVT) {
8804         SDLoc DL(N);
8805         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8806         return DAG.getStoreVP(
8807             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8808             DAG.getConstant(1, DL, MaskVT),
8809             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8810             Store->getMemOperand(), Store->getAddressingMode(),
8811             Store->isTruncatingStore(), /*IsCompress*/ false);
8812       }
8813     }
8814 
8815     break;
8816   }
8817   case ISD::SPLAT_VECTOR: {
8818     EVT VT = N->getValueType(0);
8819     // Only perform this combine on legal MVT types.
8820     if (!isTypeLegal(VT))
8821       break;
8822     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
8823                                          DAG, Subtarget))
8824       return Gather;
8825     break;
8826   }
8827   case RISCVISD::VMV_V_X_VL: {
8828     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
8829     // scalar input.
8830     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
8831     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
8832     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
8833       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
8834         return SDValue(N, 0);
8835 
8836     break;
8837   }
8838   case ISD::INTRINSIC_WO_CHAIN: {
8839     unsigned IntNo = N->getConstantOperandVal(0);
8840     switch (IntNo) {
8841       // By default we do not combine any intrinsic.
8842     default:
8843       return SDValue();
8844     case Intrinsic::riscv_vcpop:
8845     case Intrinsic::riscv_vcpop_mask:
8846     case Intrinsic::riscv_vfirst:
8847     case Intrinsic::riscv_vfirst_mask: {
8848       SDValue VL = N->getOperand(2);
8849       if (IntNo == Intrinsic::riscv_vcpop_mask ||
8850           IntNo == Intrinsic::riscv_vfirst_mask)
8851         VL = N->getOperand(3);
8852       if (!isNullConstant(VL))
8853         return SDValue();
8854       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
8855       SDLoc DL(N);
8856       EVT VT = N->getValueType(0);
8857       if (IntNo == Intrinsic::riscv_vfirst ||
8858           IntNo == Intrinsic::riscv_vfirst_mask)
8859         return DAG.getConstant(-1, DL, VT);
8860       return DAG.getConstant(0, DL, VT);
8861     }
8862     }
8863   }
8864   }
8865 
8866   return SDValue();
8867 }
8868 
8869 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8870     const SDNode *N, CombineLevel Level) const {
8871   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8872   // materialised in fewer instructions than `(OP _, c1)`:
8873   //
8874   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8875   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8876   SDValue N0 = N->getOperand(0);
8877   EVT Ty = N0.getValueType();
8878   if (Ty.isScalarInteger() &&
8879       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8880     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8881     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8882     if (C1 && C2) {
8883       const APInt &C1Int = C1->getAPIntValue();
8884       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8885 
8886       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8887       // and the combine should happen, to potentially allow further combines
8888       // later.
8889       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8890           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8891         return true;
8892 
8893       // We can materialise `c1` in an add immediate, so it's "free", and the
8894       // combine should be prevented.
8895       if (C1Int.getMinSignedBits() <= 64 &&
8896           isLegalAddImmediate(C1Int.getSExtValue()))
8897         return false;
8898 
8899       // Neither constant will fit into an immediate, so find materialisation
8900       // costs.
8901       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8902                                               Subtarget.getFeatureBits(),
8903                                               /*CompressionCost*/true);
8904       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8905           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8906           /*CompressionCost*/true);
8907 
8908       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8909       // combine should be prevented.
8910       if (C1Cost < ShiftedC1Cost)
8911         return false;
8912     }
8913   }
8914   return true;
8915 }
8916 
8917 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8918     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8919     TargetLoweringOpt &TLO) const {
8920   // Delay this optimization as late as possible.
8921   if (!TLO.LegalOps)
8922     return false;
8923 
8924   EVT VT = Op.getValueType();
8925   if (VT.isVector())
8926     return false;
8927 
8928   // Only handle AND for now.
8929   if (Op.getOpcode() != ISD::AND)
8930     return false;
8931 
8932   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8933   if (!C)
8934     return false;
8935 
8936   const APInt &Mask = C->getAPIntValue();
8937 
8938   // Clear all non-demanded bits initially.
8939   APInt ShrunkMask = Mask & DemandedBits;
8940 
8941   // Try to make a smaller immediate by setting undemanded bits.
8942 
8943   APInt ExpandedMask = Mask | ~DemandedBits;
8944 
8945   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8946     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8947   };
8948   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8949     if (NewMask == Mask)
8950       return true;
8951     SDLoc DL(Op);
8952     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8953     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8954     return TLO.CombineTo(Op, NewOp);
8955   };
8956 
8957   // If the shrunk mask fits in sign extended 12 bits, let the target
8958   // independent code apply it.
8959   if (ShrunkMask.isSignedIntN(12))
8960     return false;
8961 
8962   // Preserve (and X, 0xffff) when zext.h is supported.
8963   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8964     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8965     if (IsLegalMask(NewMask))
8966       return UseMask(NewMask);
8967   }
8968 
8969   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8970   if (VT == MVT::i64) {
8971     APInt NewMask = APInt(64, 0xffffffff);
8972     if (IsLegalMask(NewMask))
8973       return UseMask(NewMask);
8974   }
8975 
8976   // For the remaining optimizations, we need to be able to make a negative
8977   // number through a combination of mask and undemanded bits.
8978   if (!ExpandedMask.isNegative())
8979     return false;
8980 
8981   // What is the fewest number of bits we need to represent the negative number.
8982   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8983 
8984   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8985   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8986   APInt NewMask = ShrunkMask;
8987   if (MinSignedBits <= 12)
8988     NewMask.setBitsFrom(11);
8989   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8990     NewMask.setBitsFrom(31);
8991   else
8992     return false;
8993 
8994   // Check that our new mask is a subset of the demanded mask.
8995   assert(IsLegalMask(NewMask));
8996   return UseMask(NewMask);
8997 }
8998 
8999 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
9000   static const uint64_t GREVMasks[] = {
9001       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
9002       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
9003 
9004   for (unsigned Stage = 0; Stage != 6; ++Stage) {
9005     unsigned Shift = 1 << Stage;
9006     if (ShAmt & Shift) {
9007       uint64_t Mask = GREVMasks[Stage];
9008       uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
9009       if (IsGORC)
9010         Res |= x;
9011       x = Res;
9012     }
9013   }
9014 
9015   return x;
9016 }
9017 
9018 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9019                                                         KnownBits &Known,
9020                                                         const APInt &DemandedElts,
9021                                                         const SelectionDAG &DAG,
9022                                                         unsigned Depth) const {
9023   unsigned BitWidth = Known.getBitWidth();
9024   unsigned Opc = Op.getOpcode();
9025   assert((Opc >= ISD::BUILTIN_OP_END ||
9026           Opc == ISD::INTRINSIC_WO_CHAIN ||
9027           Opc == ISD::INTRINSIC_W_CHAIN ||
9028           Opc == ISD::INTRINSIC_VOID) &&
9029          "Should use MaskedValueIsZero if you don't know whether Op"
9030          " is a target node!");
9031 
9032   Known.resetAll();
9033   switch (Opc) {
9034   default: break;
9035   case RISCVISD::SELECT_CC: {
9036     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
9037     // If we don't know any bits, early out.
9038     if (Known.isUnknown())
9039       break;
9040     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
9041 
9042     // Only known if known in both the LHS and RHS.
9043     Known = KnownBits::commonBits(Known, Known2);
9044     break;
9045   }
9046   case RISCVISD::REMUW: {
9047     KnownBits Known2;
9048     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9049     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9050     // We only care about the lower 32 bits.
9051     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
9052     // Restore the original width by sign extending.
9053     Known = Known.sext(BitWidth);
9054     break;
9055   }
9056   case RISCVISD::DIVUW: {
9057     KnownBits Known2;
9058     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
9059     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
9060     // We only care about the lower 32 bits.
9061     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
9062     // Restore the original width by sign extending.
9063     Known = Known.sext(BitWidth);
9064     break;
9065   }
9066   case RISCVISD::CTZW: {
9067     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9068     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
9069     unsigned LowBits = Log2_32(PossibleTZ) + 1;
9070     Known.Zero.setBitsFrom(LowBits);
9071     break;
9072   }
9073   case RISCVISD::CLZW: {
9074     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9075     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
9076     unsigned LowBits = Log2_32(PossibleLZ) + 1;
9077     Known.Zero.setBitsFrom(LowBits);
9078     break;
9079   }
9080   case RISCVISD::GREV:
9081   case RISCVISD::GORC: {
9082     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9083       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
9084       unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1);
9085       bool IsGORC = Op.getOpcode() == RISCVISD::GORC;
9086       // To compute zeros, we need to invert the value and invert it back after.
9087       Known.Zero =
9088           ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC);
9089       Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC);
9090     }
9091     break;
9092   }
9093   case RISCVISD::READ_VLENB: {
9094     // If we know the minimum VLen from Zvl extensions, we can use that to
9095     // determine the trailing zeros of VLENB.
9096     // FIXME: Limit to 128 bit vectors until we have more testing.
9097     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
9098     if (MinVLenB > 0)
9099       Known.Zero.setLowBits(Log2_32(MinVLenB));
9100     // We assume VLENB is no more than 65536 / 8 bytes.
9101     Known.Zero.setBitsFrom(14);
9102     break;
9103   }
9104   case ISD::INTRINSIC_W_CHAIN:
9105   case ISD::INTRINSIC_WO_CHAIN: {
9106     unsigned IntNo =
9107         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
9108     switch (IntNo) {
9109     default:
9110       // We can't do anything for most intrinsics.
9111       break;
9112     case Intrinsic::riscv_vsetvli:
9113     case Intrinsic::riscv_vsetvlimax:
9114     case Intrinsic::riscv_vsetvli_opt:
9115     case Intrinsic::riscv_vsetvlimax_opt:
9116       // Assume that VL output is positive and would fit in an int32_t.
9117       // TODO: VLEN might be capped at 16 bits in a future V spec update.
9118       if (BitWidth >= 32)
9119         Known.Zero.setBitsFrom(31);
9120       break;
9121     }
9122     break;
9123   }
9124   }
9125 }
9126 
9127 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
9128     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
9129     unsigned Depth) const {
9130   switch (Op.getOpcode()) {
9131   default:
9132     break;
9133   case RISCVISD::SELECT_CC: {
9134     unsigned Tmp =
9135         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
9136     if (Tmp == 1) return 1;  // Early out.
9137     unsigned Tmp2 =
9138         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
9139     return std::min(Tmp, Tmp2);
9140   }
9141   case RISCVISD::SLLW:
9142   case RISCVISD::SRAW:
9143   case RISCVISD::SRLW:
9144   case RISCVISD::DIVW:
9145   case RISCVISD::DIVUW:
9146   case RISCVISD::REMUW:
9147   case RISCVISD::ROLW:
9148   case RISCVISD::RORW:
9149   case RISCVISD::GREVW:
9150   case RISCVISD::GORCW:
9151   case RISCVISD::FSLW:
9152   case RISCVISD::FSRW:
9153   case RISCVISD::SHFLW:
9154   case RISCVISD::UNSHFLW:
9155   case RISCVISD::BCOMPRESSW:
9156   case RISCVISD::BDECOMPRESSW:
9157   case RISCVISD::BFPW:
9158   case RISCVISD::FCVT_W_RV64:
9159   case RISCVISD::FCVT_WU_RV64:
9160   case RISCVISD::STRICT_FCVT_W_RV64:
9161   case RISCVISD::STRICT_FCVT_WU_RV64:
9162     // TODO: As the result is sign-extended, this is conservatively correct. A
9163     // more precise answer could be calculated for SRAW depending on known
9164     // bits in the shift amount.
9165     return 33;
9166   case RISCVISD::SHFL:
9167   case RISCVISD::UNSHFL: {
9168     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
9169     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
9170     // will stay within the upper 32 bits. If there were more than 32 sign bits
9171     // before there will be at least 33 sign bits after.
9172     if (Op.getValueType() == MVT::i64 &&
9173         isa<ConstantSDNode>(Op.getOperand(1)) &&
9174         (Op.getConstantOperandVal(1) & 0x10) == 0) {
9175       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
9176       if (Tmp > 32)
9177         return 33;
9178     }
9179     break;
9180   }
9181   case RISCVISD::VMV_X_S: {
9182     // The number of sign bits of the scalar result is computed by obtaining the
9183     // element type of the input vector operand, subtracting its width from the
9184     // XLEN, and then adding one (sign bit within the element type). If the
9185     // element type is wider than XLen, the least-significant XLEN bits are
9186     // taken.
9187     unsigned XLen = Subtarget.getXLen();
9188     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
9189     if (EltBits <= XLen)
9190       return XLen - EltBits + 1;
9191     break;
9192   }
9193   }
9194 
9195   return 1;
9196 }
9197 
9198 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
9199                                                   MachineBasicBlock *BB) {
9200   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
9201 
9202   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
9203   // Should the count have wrapped while it was being read, we need to try
9204   // again.
9205   // ...
9206   // read:
9207   // rdcycleh x3 # load high word of cycle
9208   // rdcycle  x2 # load low word of cycle
9209   // rdcycleh x4 # load high word of cycle
9210   // bne x3, x4, read # check if high word reads match, otherwise try again
9211   // ...
9212 
9213   MachineFunction &MF = *BB->getParent();
9214   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9215   MachineFunction::iterator It = ++BB->getIterator();
9216 
9217   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9218   MF.insert(It, LoopMBB);
9219 
9220   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9221   MF.insert(It, DoneMBB);
9222 
9223   // Transfer the remainder of BB and its successor edges to DoneMBB.
9224   DoneMBB->splice(DoneMBB->begin(), BB,
9225                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9226   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
9227 
9228   BB->addSuccessor(LoopMBB);
9229 
9230   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9231   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9232   Register LoReg = MI.getOperand(0).getReg();
9233   Register HiReg = MI.getOperand(1).getReg();
9234   DebugLoc DL = MI.getDebugLoc();
9235 
9236   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9237   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9238       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9239       .addReg(RISCV::X0);
9240   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9241       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9242       .addReg(RISCV::X0);
9243   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9244       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9245       .addReg(RISCV::X0);
9246 
9247   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9248       .addReg(HiReg)
9249       .addReg(ReadAgainReg)
9250       .addMBB(LoopMBB);
9251 
9252   LoopMBB->addSuccessor(LoopMBB);
9253   LoopMBB->addSuccessor(DoneMBB);
9254 
9255   MI.eraseFromParent();
9256 
9257   return DoneMBB;
9258 }
9259 
9260 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9261                                              MachineBasicBlock *BB) {
9262   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9263 
9264   MachineFunction &MF = *BB->getParent();
9265   DebugLoc DL = MI.getDebugLoc();
9266   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9267   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9268   Register LoReg = MI.getOperand(0).getReg();
9269   Register HiReg = MI.getOperand(1).getReg();
9270   Register SrcReg = MI.getOperand(2).getReg();
9271   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9272   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9273 
9274   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9275                           RI);
9276   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9277   MachineMemOperand *MMOLo =
9278       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9279   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9280       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9281   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9282       .addFrameIndex(FI)
9283       .addImm(0)
9284       .addMemOperand(MMOLo);
9285   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9286       .addFrameIndex(FI)
9287       .addImm(4)
9288       .addMemOperand(MMOHi);
9289   MI.eraseFromParent(); // The pseudo instruction is gone now.
9290   return BB;
9291 }
9292 
9293 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9294                                                  MachineBasicBlock *BB) {
9295   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9296          "Unexpected instruction");
9297 
9298   MachineFunction &MF = *BB->getParent();
9299   DebugLoc DL = MI.getDebugLoc();
9300   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9301   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9302   Register DstReg = MI.getOperand(0).getReg();
9303   Register LoReg = MI.getOperand(1).getReg();
9304   Register HiReg = MI.getOperand(2).getReg();
9305   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9306   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9307 
9308   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9309   MachineMemOperand *MMOLo =
9310       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9311   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9312       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9313   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9314       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9315       .addFrameIndex(FI)
9316       .addImm(0)
9317       .addMemOperand(MMOLo);
9318   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9319       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9320       .addFrameIndex(FI)
9321       .addImm(4)
9322       .addMemOperand(MMOHi);
9323   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9324   MI.eraseFromParent(); // The pseudo instruction is gone now.
9325   return BB;
9326 }
9327 
9328 static bool isSelectPseudo(MachineInstr &MI) {
9329   switch (MI.getOpcode()) {
9330   default:
9331     return false;
9332   case RISCV::Select_GPR_Using_CC_GPR:
9333   case RISCV::Select_FPR16_Using_CC_GPR:
9334   case RISCV::Select_FPR32_Using_CC_GPR:
9335   case RISCV::Select_FPR64_Using_CC_GPR:
9336     return true;
9337   }
9338 }
9339 
9340 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9341                                         unsigned RelOpcode, unsigned EqOpcode,
9342                                         const RISCVSubtarget &Subtarget) {
9343   DebugLoc DL = MI.getDebugLoc();
9344   Register DstReg = MI.getOperand(0).getReg();
9345   Register Src1Reg = MI.getOperand(1).getReg();
9346   Register Src2Reg = MI.getOperand(2).getReg();
9347   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9348   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9349   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9350 
9351   // Save the current FFLAGS.
9352   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9353 
9354   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9355                  .addReg(Src1Reg)
9356                  .addReg(Src2Reg);
9357   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9358     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9359 
9360   // Restore the FFLAGS.
9361   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9362       .addReg(SavedFFlags, RegState::Kill);
9363 
9364   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9365   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9366                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9367                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9368   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9369     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9370 
9371   // Erase the pseudoinstruction.
9372   MI.eraseFromParent();
9373   return BB;
9374 }
9375 
9376 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9377                                            MachineBasicBlock *BB,
9378                                            const RISCVSubtarget &Subtarget) {
9379   // To "insert" Select_* instructions, we actually have to insert the triangle
9380   // control-flow pattern.  The incoming instructions know the destination vreg
9381   // to set, the condition code register to branch on, the true/false values to
9382   // select between, and the condcode to use to select the appropriate branch.
9383   //
9384   // We produce the following control flow:
9385   //     HeadMBB
9386   //     |  \
9387   //     |  IfFalseMBB
9388   //     | /
9389   //    TailMBB
9390   //
9391   // When we find a sequence of selects we attempt to optimize their emission
9392   // by sharing the control flow. Currently we only handle cases where we have
9393   // multiple selects with the exact same condition (same LHS, RHS and CC).
9394   // The selects may be interleaved with other instructions if the other
9395   // instructions meet some requirements we deem safe:
9396   // - They are debug instructions. Otherwise,
9397   // - They do not have side-effects, do not access memory and their inputs do
9398   //   not depend on the results of the select pseudo-instructions.
9399   // The TrueV/FalseV operands of the selects cannot depend on the result of
9400   // previous selects in the sequence.
9401   // These conditions could be further relaxed. See the X86 target for a
9402   // related approach and more information.
9403   Register LHS = MI.getOperand(1).getReg();
9404   Register RHS = MI.getOperand(2).getReg();
9405   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9406 
9407   SmallVector<MachineInstr *, 4> SelectDebugValues;
9408   SmallSet<Register, 4> SelectDests;
9409   SelectDests.insert(MI.getOperand(0).getReg());
9410 
9411   MachineInstr *LastSelectPseudo = &MI;
9412 
9413   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9414        SequenceMBBI != E; ++SequenceMBBI) {
9415     if (SequenceMBBI->isDebugInstr())
9416       continue;
9417     else if (isSelectPseudo(*SequenceMBBI)) {
9418       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9419           SequenceMBBI->getOperand(2).getReg() != RHS ||
9420           SequenceMBBI->getOperand(3).getImm() != CC ||
9421           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9422           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9423         break;
9424       LastSelectPseudo = &*SequenceMBBI;
9425       SequenceMBBI->collectDebugValues(SelectDebugValues);
9426       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9427     } else {
9428       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9429           SequenceMBBI->mayLoadOrStore())
9430         break;
9431       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9432             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9433           }))
9434         break;
9435     }
9436   }
9437 
9438   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9439   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9440   DebugLoc DL = MI.getDebugLoc();
9441   MachineFunction::iterator I = ++BB->getIterator();
9442 
9443   MachineBasicBlock *HeadMBB = BB;
9444   MachineFunction *F = BB->getParent();
9445   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9446   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9447 
9448   F->insert(I, IfFalseMBB);
9449   F->insert(I, TailMBB);
9450 
9451   // Transfer debug instructions associated with the selects to TailMBB.
9452   for (MachineInstr *DebugInstr : SelectDebugValues) {
9453     TailMBB->push_back(DebugInstr->removeFromParent());
9454   }
9455 
9456   // Move all instructions after the sequence to TailMBB.
9457   TailMBB->splice(TailMBB->end(), HeadMBB,
9458                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9459   // Update machine-CFG edges by transferring all successors of the current
9460   // block to the new block which will contain the Phi nodes for the selects.
9461   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9462   // Set the successors for HeadMBB.
9463   HeadMBB->addSuccessor(IfFalseMBB);
9464   HeadMBB->addSuccessor(TailMBB);
9465 
9466   // Insert appropriate branch.
9467   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9468     .addReg(LHS)
9469     .addReg(RHS)
9470     .addMBB(TailMBB);
9471 
9472   // IfFalseMBB just falls through to TailMBB.
9473   IfFalseMBB->addSuccessor(TailMBB);
9474 
9475   // Create PHIs for all of the select pseudo-instructions.
9476   auto SelectMBBI = MI.getIterator();
9477   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9478   auto InsertionPoint = TailMBB->begin();
9479   while (SelectMBBI != SelectEnd) {
9480     auto Next = std::next(SelectMBBI);
9481     if (isSelectPseudo(*SelectMBBI)) {
9482       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9483       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9484               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9485           .addReg(SelectMBBI->getOperand(4).getReg())
9486           .addMBB(HeadMBB)
9487           .addReg(SelectMBBI->getOperand(5).getReg())
9488           .addMBB(IfFalseMBB);
9489       SelectMBBI->eraseFromParent();
9490     }
9491     SelectMBBI = Next;
9492   }
9493 
9494   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9495   return TailMBB;
9496 }
9497 
9498 MachineBasicBlock *
9499 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9500                                                  MachineBasicBlock *BB) const {
9501   switch (MI.getOpcode()) {
9502   default:
9503     llvm_unreachable("Unexpected instr type to insert");
9504   case RISCV::ReadCycleWide:
9505     assert(!Subtarget.is64Bit() &&
9506            "ReadCycleWrite is only to be used on riscv32");
9507     return emitReadCycleWidePseudo(MI, BB);
9508   case RISCV::Select_GPR_Using_CC_GPR:
9509   case RISCV::Select_FPR16_Using_CC_GPR:
9510   case RISCV::Select_FPR32_Using_CC_GPR:
9511   case RISCV::Select_FPR64_Using_CC_GPR:
9512     return emitSelectPseudo(MI, BB, Subtarget);
9513   case RISCV::BuildPairF64Pseudo:
9514     return emitBuildPairF64Pseudo(MI, BB);
9515   case RISCV::SplitF64Pseudo:
9516     return emitSplitF64Pseudo(MI, BB);
9517   case RISCV::PseudoQuietFLE_H:
9518     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9519   case RISCV::PseudoQuietFLT_H:
9520     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9521   case RISCV::PseudoQuietFLE_S:
9522     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9523   case RISCV::PseudoQuietFLT_S:
9524     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9525   case RISCV::PseudoQuietFLE_D:
9526     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9527   case RISCV::PseudoQuietFLT_D:
9528     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9529   }
9530 }
9531 
9532 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9533                                                         SDNode *Node) const {
9534   // Add FRM dependency to any instructions with dynamic rounding mode.
9535   unsigned Opc = MI.getOpcode();
9536   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9537   if (Idx < 0)
9538     return;
9539   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9540     return;
9541   // If the instruction already reads FRM, don't add another read.
9542   if (MI.readsRegister(RISCV::FRM))
9543     return;
9544   MI.addOperand(
9545       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9546 }
9547 
9548 // Calling Convention Implementation.
9549 // The expectations for frontend ABI lowering vary from target to target.
9550 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9551 // details, but this is a longer term goal. For now, we simply try to keep the
9552 // role of the frontend as simple and well-defined as possible. The rules can
9553 // be summarised as:
9554 // * Never split up large scalar arguments. We handle them here.
9555 // * If a hardfloat calling convention is being used, and the struct may be
9556 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9557 // available, then pass as two separate arguments. If either the GPRs or FPRs
9558 // are exhausted, then pass according to the rule below.
9559 // * If a struct could never be passed in registers or directly in a stack
9560 // slot (as it is larger than 2*XLEN and the floating point rules don't
9561 // apply), then pass it using a pointer with the byval attribute.
9562 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9563 // word-sized array or a 2*XLEN scalar (depending on alignment).
9564 // * The frontend can determine whether a struct is returned by reference or
9565 // not based on its size and fields. If it will be returned by reference, the
9566 // frontend must modify the prototype so a pointer with the sret annotation is
9567 // passed as the first argument. This is not necessary for large scalar
9568 // returns.
9569 // * Struct return values and varargs should be coerced to structs containing
9570 // register-size fields in the same situations they would be for fixed
9571 // arguments.
9572 
9573 static const MCPhysReg ArgGPRs[] = {
9574   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9575   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9576 };
9577 static const MCPhysReg ArgFPR16s[] = {
9578   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9579   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9580 };
9581 static const MCPhysReg ArgFPR32s[] = {
9582   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9583   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9584 };
9585 static const MCPhysReg ArgFPR64s[] = {
9586   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9587   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9588 };
9589 // This is an interim calling convention and it may be changed in the future.
9590 static const MCPhysReg ArgVRs[] = {
9591     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9592     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9593     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9594 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9595                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9596                                      RISCV::V20M2, RISCV::V22M2};
9597 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9598                                      RISCV::V20M4};
9599 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9600 
9601 // Pass a 2*XLEN argument that has been split into two XLEN values through
9602 // registers or the stack as necessary.
9603 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9604                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9605                                 MVT ValVT2, MVT LocVT2,
9606                                 ISD::ArgFlagsTy ArgFlags2) {
9607   unsigned XLenInBytes = XLen / 8;
9608   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9609     // At least one half can be passed via register.
9610     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9611                                      VA1.getLocVT(), CCValAssign::Full));
9612   } else {
9613     // Both halves must be passed on the stack, with proper alignment.
9614     Align StackAlign =
9615         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9616     State.addLoc(
9617         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9618                             State.AllocateStack(XLenInBytes, StackAlign),
9619                             VA1.getLocVT(), CCValAssign::Full));
9620     State.addLoc(CCValAssign::getMem(
9621         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9622         LocVT2, CCValAssign::Full));
9623     return false;
9624   }
9625 
9626   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9627     // The second half can also be passed via register.
9628     State.addLoc(
9629         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9630   } else {
9631     // The second half is passed via the stack, without additional alignment.
9632     State.addLoc(CCValAssign::getMem(
9633         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9634         LocVT2, CCValAssign::Full));
9635   }
9636 
9637   return false;
9638 }
9639 
9640 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9641                                Optional<unsigned> FirstMaskArgument,
9642                                CCState &State, const RISCVTargetLowering &TLI) {
9643   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9644   if (RC == &RISCV::VRRegClass) {
9645     // Assign the first mask argument to V0.
9646     // This is an interim calling convention and it may be changed in the
9647     // future.
9648     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
9649       return State.AllocateReg(RISCV::V0);
9650     return State.AllocateReg(ArgVRs);
9651   }
9652   if (RC == &RISCV::VRM2RegClass)
9653     return State.AllocateReg(ArgVRM2s);
9654   if (RC == &RISCV::VRM4RegClass)
9655     return State.AllocateReg(ArgVRM4s);
9656   if (RC == &RISCV::VRM8RegClass)
9657     return State.AllocateReg(ArgVRM8s);
9658   llvm_unreachable("Unhandled register class for ValueType");
9659 }
9660 
9661 // Implements the RISC-V calling convention. Returns true upon failure.
9662 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9663                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9664                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9665                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9666                      Optional<unsigned> FirstMaskArgument) {
9667   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9668   assert(XLen == 32 || XLen == 64);
9669   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9670 
9671   // Any return value split in to more than two values can't be returned
9672   // directly. Vectors are returned via the available vector registers.
9673   if (!LocVT.isVector() && IsRet && ValNo > 1)
9674     return true;
9675 
9676   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9677   // variadic argument, or if no F16/F32 argument registers are available.
9678   bool UseGPRForF16_F32 = true;
9679   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9680   // variadic argument, or if no F64 argument registers are available.
9681   bool UseGPRForF64 = true;
9682 
9683   switch (ABI) {
9684   default:
9685     llvm_unreachable("Unexpected ABI");
9686   case RISCVABI::ABI_ILP32:
9687   case RISCVABI::ABI_LP64:
9688     break;
9689   case RISCVABI::ABI_ILP32F:
9690   case RISCVABI::ABI_LP64F:
9691     UseGPRForF16_F32 = !IsFixed;
9692     break;
9693   case RISCVABI::ABI_ILP32D:
9694   case RISCVABI::ABI_LP64D:
9695     UseGPRForF16_F32 = !IsFixed;
9696     UseGPRForF64 = !IsFixed;
9697     break;
9698   }
9699 
9700   // FPR16, FPR32, and FPR64 alias each other.
9701   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9702     UseGPRForF16_F32 = true;
9703     UseGPRForF64 = true;
9704   }
9705 
9706   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9707   // similar local variables rather than directly checking against the target
9708   // ABI.
9709 
9710   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9711     LocVT = XLenVT;
9712     LocInfo = CCValAssign::BCvt;
9713   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9714     LocVT = MVT::i64;
9715     LocInfo = CCValAssign::BCvt;
9716   }
9717 
9718   // If this is a variadic argument, the RISC-V calling convention requires
9719   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9720   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9721   // be used regardless of whether the original argument was split during
9722   // legalisation or not. The argument will not be passed by registers if the
9723   // original type is larger than 2*XLEN, so the register alignment rule does
9724   // not apply.
9725   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9726   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9727       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9728     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9729     // Skip 'odd' register if necessary.
9730     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9731       State.AllocateReg(ArgGPRs);
9732   }
9733 
9734   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9735   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9736       State.getPendingArgFlags();
9737 
9738   assert(PendingLocs.size() == PendingArgFlags.size() &&
9739          "PendingLocs and PendingArgFlags out of sync");
9740 
9741   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9742   // registers are exhausted.
9743   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9744     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9745            "Can't lower f64 if it is split");
9746     // Depending on available argument GPRS, f64 may be passed in a pair of
9747     // GPRs, split between a GPR and the stack, or passed completely on the
9748     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9749     // cases.
9750     Register Reg = State.AllocateReg(ArgGPRs);
9751     LocVT = MVT::i32;
9752     if (!Reg) {
9753       unsigned StackOffset = State.AllocateStack(8, Align(8));
9754       State.addLoc(
9755           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9756       return false;
9757     }
9758     if (!State.AllocateReg(ArgGPRs))
9759       State.AllocateStack(4, Align(4));
9760     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9761     return false;
9762   }
9763 
9764   // Fixed-length vectors are located in the corresponding scalable-vector
9765   // container types.
9766   if (ValVT.isFixedLengthVector())
9767     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9768 
9769   // Split arguments might be passed indirectly, so keep track of the pending
9770   // values. Split vectors are passed via a mix of registers and indirectly, so
9771   // treat them as we would any other argument.
9772   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9773     LocVT = XLenVT;
9774     LocInfo = CCValAssign::Indirect;
9775     PendingLocs.push_back(
9776         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9777     PendingArgFlags.push_back(ArgFlags);
9778     if (!ArgFlags.isSplitEnd()) {
9779       return false;
9780     }
9781   }
9782 
9783   // If the split argument only had two elements, it should be passed directly
9784   // in registers or on the stack.
9785   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9786       PendingLocs.size() <= 2) {
9787     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9788     // Apply the normal calling convention rules to the first half of the
9789     // split argument.
9790     CCValAssign VA = PendingLocs[0];
9791     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9792     PendingLocs.clear();
9793     PendingArgFlags.clear();
9794     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9795                                ArgFlags);
9796   }
9797 
9798   // Allocate to a register if possible, or else a stack slot.
9799   Register Reg;
9800   unsigned StoreSizeBytes = XLen / 8;
9801   Align StackAlign = Align(XLen / 8);
9802 
9803   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9804     Reg = State.AllocateReg(ArgFPR16s);
9805   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9806     Reg = State.AllocateReg(ArgFPR32s);
9807   else if (ValVT == MVT::f64 && !UseGPRForF64)
9808     Reg = State.AllocateReg(ArgFPR64s);
9809   else if (ValVT.isVector()) {
9810     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9811     if (!Reg) {
9812       // For return values, the vector must be passed fully via registers or
9813       // via the stack.
9814       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9815       // but we're using all of them.
9816       if (IsRet)
9817         return true;
9818       // Try using a GPR to pass the address
9819       if ((Reg = State.AllocateReg(ArgGPRs))) {
9820         LocVT = XLenVT;
9821         LocInfo = CCValAssign::Indirect;
9822       } else if (ValVT.isScalableVector()) {
9823         LocVT = XLenVT;
9824         LocInfo = CCValAssign::Indirect;
9825       } else {
9826         // Pass fixed-length vectors on the stack.
9827         LocVT = ValVT;
9828         StoreSizeBytes = ValVT.getStoreSize();
9829         // Align vectors to their element sizes, being careful for vXi1
9830         // vectors.
9831         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9832       }
9833     }
9834   } else {
9835     Reg = State.AllocateReg(ArgGPRs);
9836   }
9837 
9838   unsigned StackOffset =
9839       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9840 
9841   // If we reach this point and PendingLocs is non-empty, we must be at the
9842   // end of a split argument that must be passed indirectly.
9843   if (!PendingLocs.empty()) {
9844     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9845     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9846 
9847     for (auto &It : PendingLocs) {
9848       if (Reg)
9849         It.convertToReg(Reg);
9850       else
9851         It.convertToMem(StackOffset);
9852       State.addLoc(It);
9853     }
9854     PendingLocs.clear();
9855     PendingArgFlags.clear();
9856     return false;
9857   }
9858 
9859   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9860           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9861          "Expected an XLenVT or vector types at this stage");
9862 
9863   if (Reg) {
9864     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9865     return false;
9866   }
9867 
9868   // When a floating-point value is passed on the stack, no bit-conversion is
9869   // needed.
9870   if (ValVT.isFloatingPoint()) {
9871     LocVT = ValVT;
9872     LocInfo = CCValAssign::Full;
9873   }
9874   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9875   return false;
9876 }
9877 
9878 template <typename ArgTy>
9879 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9880   for (const auto &ArgIdx : enumerate(Args)) {
9881     MVT ArgVT = ArgIdx.value().VT;
9882     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9883       return ArgIdx.index();
9884   }
9885   return None;
9886 }
9887 
9888 void RISCVTargetLowering::analyzeInputArgs(
9889     MachineFunction &MF, CCState &CCInfo,
9890     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9891     RISCVCCAssignFn Fn) const {
9892   unsigned NumArgs = Ins.size();
9893   FunctionType *FType = MF.getFunction().getFunctionType();
9894 
9895   Optional<unsigned> FirstMaskArgument;
9896   if (Subtarget.hasVInstructions())
9897     FirstMaskArgument = preAssignMask(Ins);
9898 
9899   for (unsigned i = 0; i != NumArgs; ++i) {
9900     MVT ArgVT = Ins[i].VT;
9901     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9902 
9903     Type *ArgTy = nullptr;
9904     if (IsRet)
9905       ArgTy = FType->getReturnType();
9906     else if (Ins[i].isOrigArg())
9907       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9908 
9909     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9910     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9911            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9912            FirstMaskArgument)) {
9913       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9914                         << EVT(ArgVT).getEVTString() << '\n');
9915       llvm_unreachable(nullptr);
9916     }
9917   }
9918 }
9919 
9920 void RISCVTargetLowering::analyzeOutputArgs(
9921     MachineFunction &MF, CCState &CCInfo,
9922     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9923     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9924   unsigned NumArgs = Outs.size();
9925 
9926   Optional<unsigned> FirstMaskArgument;
9927   if (Subtarget.hasVInstructions())
9928     FirstMaskArgument = preAssignMask(Outs);
9929 
9930   for (unsigned i = 0; i != NumArgs; i++) {
9931     MVT ArgVT = Outs[i].VT;
9932     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9933     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9934 
9935     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9936     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9937            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9938            FirstMaskArgument)) {
9939       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9940                         << EVT(ArgVT).getEVTString() << "\n");
9941       llvm_unreachable(nullptr);
9942     }
9943   }
9944 }
9945 
9946 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9947 // values.
9948 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9949                                    const CCValAssign &VA, const SDLoc &DL,
9950                                    const RISCVSubtarget &Subtarget) {
9951   switch (VA.getLocInfo()) {
9952   default:
9953     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9954   case CCValAssign::Full:
9955     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9956       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9957     break;
9958   case CCValAssign::BCvt:
9959     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9960       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9961     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9962       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9963     else
9964       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9965     break;
9966   }
9967   return Val;
9968 }
9969 
9970 // The caller is responsible for loading the full value if the argument is
9971 // passed with CCValAssign::Indirect.
9972 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9973                                 const CCValAssign &VA, const SDLoc &DL,
9974                                 const RISCVTargetLowering &TLI) {
9975   MachineFunction &MF = DAG.getMachineFunction();
9976   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9977   EVT LocVT = VA.getLocVT();
9978   SDValue Val;
9979   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9980   Register VReg = RegInfo.createVirtualRegister(RC);
9981   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9982   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9983 
9984   if (VA.getLocInfo() == CCValAssign::Indirect)
9985     return Val;
9986 
9987   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9988 }
9989 
9990 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9991                                    const CCValAssign &VA, const SDLoc &DL,
9992                                    const RISCVSubtarget &Subtarget) {
9993   EVT LocVT = VA.getLocVT();
9994 
9995   switch (VA.getLocInfo()) {
9996   default:
9997     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9998   case CCValAssign::Full:
9999     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
10000       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
10001     break;
10002   case CCValAssign::BCvt:
10003     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
10004       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
10005     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
10006       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
10007     else
10008       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
10009     break;
10010   }
10011   return Val;
10012 }
10013 
10014 // The caller is responsible for loading the full value if the argument is
10015 // passed with CCValAssign::Indirect.
10016 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
10017                                 const CCValAssign &VA, const SDLoc &DL) {
10018   MachineFunction &MF = DAG.getMachineFunction();
10019   MachineFrameInfo &MFI = MF.getFrameInfo();
10020   EVT LocVT = VA.getLocVT();
10021   EVT ValVT = VA.getValVT();
10022   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
10023   if (ValVT.isScalableVector()) {
10024     // When the value is a scalable vector, we save the pointer which points to
10025     // the scalable vector value in the stack. The ValVT will be the pointer
10026     // type, instead of the scalable vector type.
10027     ValVT = LocVT;
10028   }
10029   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
10030                                  /*IsImmutable=*/true);
10031   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
10032   SDValue Val;
10033 
10034   ISD::LoadExtType ExtType;
10035   switch (VA.getLocInfo()) {
10036   default:
10037     llvm_unreachable("Unexpected CCValAssign::LocInfo");
10038   case CCValAssign::Full:
10039   case CCValAssign::Indirect:
10040   case CCValAssign::BCvt:
10041     ExtType = ISD::NON_EXTLOAD;
10042     break;
10043   }
10044   Val = DAG.getExtLoad(
10045       ExtType, DL, LocVT, Chain, FIN,
10046       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
10047   return Val;
10048 }
10049 
10050 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
10051                                        const CCValAssign &VA, const SDLoc &DL) {
10052   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
10053          "Unexpected VA");
10054   MachineFunction &MF = DAG.getMachineFunction();
10055   MachineFrameInfo &MFI = MF.getFrameInfo();
10056   MachineRegisterInfo &RegInfo = MF.getRegInfo();
10057 
10058   if (VA.isMemLoc()) {
10059     // f64 is passed on the stack.
10060     int FI =
10061         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
10062     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10063     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
10064                        MachinePointerInfo::getFixedStack(MF, FI));
10065   }
10066 
10067   assert(VA.isRegLoc() && "Expected register VA assignment");
10068 
10069   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10070   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
10071   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
10072   SDValue Hi;
10073   if (VA.getLocReg() == RISCV::X17) {
10074     // Second half of f64 is passed on the stack.
10075     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
10076     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
10077     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
10078                      MachinePointerInfo::getFixedStack(MF, FI));
10079   } else {
10080     // Second half of f64 is passed in another GPR.
10081     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
10082     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
10083     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
10084   }
10085   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
10086 }
10087 
10088 // FastCC has less than 1% performance improvement for some particular
10089 // benchmark. But theoretically, it may has benenfit for some cases.
10090 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
10091                             unsigned ValNo, MVT ValVT, MVT LocVT,
10092                             CCValAssign::LocInfo LocInfo,
10093                             ISD::ArgFlagsTy ArgFlags, CCState &State,
10094                             bool IsFixed, bool IsRet, Type *OrigTy,
10095                             const RISCVTargetLowering &TLI,
10096                             Optional<unsigned> FirstMaskArgument) {
10097 
10098   // X5 and X6 might be used for save-restore libcall.
10099   static const MCPhysReg GPRList[] = {
10100       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
10101       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
10102       RISCV::X29, RISCV::X30, RISCV::X31};
10103 
10104   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10105     if (unsigned Reg = State.AllocateReg(GPRList)) {
10106       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10107       return false;
10108     }
10109   }
10110 
10111   if (LocVT == MVT::f16) {
10112     static const MCPhysReg FPR16List[] = {
10113         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
10114         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
10115         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
10116         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
10117     if (unsigned Reg = State.AllocateReg(FPR16List)) {
10118       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10119       return false;
10120     }
10121   }
10122 
10123   if (LocVT == MVT::f32) {
10124     static const MCPhysReg FPR32List[] = {
10125         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
10126         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
10127         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
10128         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
10129     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10130       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10131       return false;
10132     }
10133   }
10134 
10135   if (LocVT == MVT::f64) {
10136     static const MCPhysReg FPR64List[] = {
10137         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
10138         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
10139         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
10140         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
10141     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10142       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10143       return false;
10144     }
10145   }
10146 
10147   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
10148     unsigned Offset4 = State.AllocateStack(4, Align(4));
10149     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
10150     return false;
10151   }
10152 
10153   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
10154     unsigned Offset5 = State.AllocateStack(8, Align(8));
10155     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
10156     return false;
10157   }
10158 
10159   if (LocVT.isVector()) {
10160     if (unsigned Reg =
10161             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
10162       // Fixed-length vectors are located in the corresponding scalable-vector
10163       // container types.
10164       if (ValVT.isFixedLengthVector())
10165         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
10166       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10167     } else {
10168       // Try and pass the address via a "fast" GPR.
10169       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
10170         LocInfo = CCValAssign::Indirect;
10171         LocVT = TLI.getSubtarget().getXLenVT();
10172         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
10173       } else if (ValVT.isFixedLengthVector()) {
10174         auto StackAlign =
10175             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
10176         unsigned StackOffset =
10177             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
10178         State.addLoc(
10179             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
10180       } else {
10181         // Can't pass scalable vectors on the stack.
10182         return true;
10183       }
10184     }
10185 
10186     return false;
10187   }
10188 
10189   return true; // CC didn't match.
10190 }
10191 
10192 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
10193                          CCValAssign::LocInfo LocInfo,
10194                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
10195 
10196   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
10197     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
10198     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
10199     static const MCPhysReg GPRList[] = {
10200         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
10201         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
10202     if (unsigned Reg = State.AllocateReg(GPRList)) {
10203       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10204       return false;
10205     }
10206   }
10207 
10208   if (LocVT == MVT::f32) {
10209     // Pass in STG registers: F1, ..., F6
10210     //                        fs0 ... fs5
10211     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
10212                                           RISCV::F18_F, RISCV::F19_F,
10213                                           RISCV::F20_F, RISCV::F21_F};
10214     if (unsigned Reg = State.AllocateReg(FPR32List)) {
10215       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10216       return false;
10217     }
10218   }
10219 
10220   if (LocVT == MVT::f64) {
10221     // Pass in STG registers: D1, ..., D6
10222     //                        fs6 ... fs11
10223     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
10224                                           RISCV::F24_D, RISCV::F25_D,
10225                                           RISCV::F26_D, RISCV::F27_D};
10226     if (unsigned Reg = State.AllocateReg(FPR64List)) {
10227       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10228       return false;
10229     }
10230   }
10231 
10232   report_fatal_error("No registers left in GHC calling convention");
10233   return true;
10234 }
10235 
10236 // Transform physical registers into virtual registers.
10237 SDValue RISCVTargetLowering::LowerFormalArguments(
10238     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10239     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10240     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10241 
10242   MachineFunction &MF = DAG.getMachineFunction();
10243 
10244   switch (CallConv) {
10245   default:
10246     report_fatal_error("Unsupported calling convention");
10247   case CallingConv::C:
10248   case CallingConv::Fast:
10249     break;
10250   case CallingConv::GHC:
10251     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10252         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10253       report_fatal_error(
10254         "GHC calling convention requires the F and D instruction set extensions");
10255   }
10256 
10257   const Function &Func = MF.getFunction();
10258   if (Func.hasFnAttribute("interrupt")) {
10259     if (!Func.arg_empty())
10260       report_fatal_error(
10261         "Functions with the interrupt attribute cannot have arguments!");
10262 
10263     StringRef Kind =
10264       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10265 
10266     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10267       report_fatal_error(
10268         "Function interrupt attribute argument not supported!");
10269   }
10270 
10271   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10272   MVT XLenVT = Subtarget.getXLenVT();
10273   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10274   // Used with vargs to acumulate store chains.
10275   std::vector<SDValue> OutChains;
10276 
10277   // Assign locations to all of the incoming arguments.
10278   SmallVector<CCValAssign, 16> ArgLocs;
10279   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10280 
10281   if (CallConv == CallingConv::GHC)
10282     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10283   else
10284     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10285                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10286                                                    : CC_RISCV);
10287 
10288   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10289     CCValAssign &VA = ArgLocs[i];
10290     SDValue ArgValue;
10291     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10292     // case.
10293     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10294       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10295     else if (VA.isRegLoc())
10296       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10297     else
10298       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10299 
10300     if (VA.getLocInfo() == CCValAssign::Indirect) {
10301       // If the original argument was split and passed by reference (e.g. i128
10302       // on RV32), we need to load all parts of it here (using the same
10303       // address). Vectors may be partly split to registers and partly to the
10304       // stack, in which case the base address is partly offset and subsequent
10305       // stores are relative to that.
10306       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10307                                    MachinePointerInfo()));
10308       unsigned ArgIndex = Ins[i].OrigArgIndex;
10309       unsigned ArgPartOffset = Ins[i].PartOffset;
10310       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10311       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10312         CCValAssign &PartVA = ArgLocs[i + 1];
10313         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10314         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10315         if (PartVA.getValVT().isScalableVector())
10316           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10317         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10318         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10319                                      MachinePointerInfo()));
10320         ++i;
10321       }
10322       continue;
10323     }
10324     InVals.push_back(ArgValue);
10325   }
10326 
10327   if (IsVarArg) {
10328     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10329     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10330     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10331     MachineFrameInfo &MFI = MF.getFrameInfo();
10332     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10333     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10334 
10335     // Offset of the first variable argument from stack pointer, and size of
10336     // the vararg save area. For now, the varargs save area is either zero or
10337     // large enough to hold a0-a7.
10338     int VaArgOffset, VarArgsSaveSize;
10339 
10340     // If all registers are allocated, then all varargs must be passed on the
10341     // stack and we don't need to save any argregs.
10342     if (ArgRegs.size() == Idx) {
10343       VaArgOffset = CCInfo.getNextStackOffset();
10344       VarArgsSaveSize = 0;
10345     } else {
10346       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10347       VaArgOffset = -VarArgsSaveSize;
10348     }
10349 
10350     // Record the frame index of the first variable argument
10351     // which is a value necessary to VASTART.
10352     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10353     RVFI->setVarArgsFrameIndex(FI);
10354 
10355     // If saving an odd number of registers then create an extra stack slot to
10356     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10357     // offsets to even-numbered registered remain 2*XLEN-aligned.
10358     if (Idx % 2) {
10359       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10360       VarArgsSaveSize += XLenInBytes;
10361     }
10362 
10363     // Copy the integer registers that may have been used for passing varargs
10364     // to the vararg save area.
10365     for (unsigned I = Idx; I < ArgRegs.size();
10366          ++I, VaArgOffset += XLenInBytes) {
10367       const Register Reg = RegInfo.createVirtualRegister(RC);
10368       RegInfo.addLiveIn(ArgRegs[I], Reg);
10369       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10370       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10371       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10372       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10373                                    MachinePointerInfo::getFixedStack(MF, FI));
10374       cast<StoreSDNode>(Store.getNode())
10375           ->getMemOperand()
10376           ->setValue((Value *)nullptr);
10377       OutChains.push_back(Store);
10378     }
10379     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10380   }
10381 
10382   // All stores are grouped in one node to allow the matching between
10383   // the size of Ins and InVals. This only happens for vararg functions.
10384   if (!OutChains.empty()) {
10385     OutChains.push_back(Chain);
10386     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10387   }
10388 
10389   return Chain;
10390 }
10391 
10392 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10393 /// for tail call optimization.
10394 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10395 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10396     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10397     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10398 
10399   auto &Callee = CLI.Callee;
10400   auto CalleeCC = CLI.CallConv;
10401   auto &Outs = CLI.Outs;
10402   auto &Caller = MF.getFunction();
10403   auto CallerCC = Caller.getCallingConv();
10404 
10405   // Exception-handling functions need a special set of instructions to
10406   // indicate a return to the hardware. Tail-calling another function would
10407   // probably break this.
10408   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10409   // should be expanded as new function attributes are introduced.
10410   if (Caller.hasFnAttribute("interrupt"))
10411     return false;
10412 
10413   // Do not tail call opt if the stack is used to pass parameters.
10414   if (CCInfo.getNextStackOffset() != 0)
10415     return false;
10416 
10417   // Do not tail call opt if any parameters need to be passed indirectly.
10418   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10419   // passed indirectly. So the address of the value will be passed in a
10420   // register, or if not available, then the address is put on the stack. In
10421   // order to pass indirectly, space on the stack often needs to be allocated
10422   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10423   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10424   // are passed CCValAssign::Indirect.
10425   for (auto &VA : ArgLocs)
10426     if (VA.getLocInfo() == CCValAssign::Indirect)
10427       return false;
10428 
10429   // Do not tail call opt if either caller or callee uses struct return
10430   // semantics.
10431   auto IsCallerStructRet = Caller.hasStructRetAttr();
10432   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10433   if (IsCallerStructRet || IsCalleeStructRet)
10434     return false;
10435 
10436   // Externally-defined functions with weak linkage should not be
10437   // tail-called. The behaviour of branch instructions in this situation (as
10438   // used for tail calls) is implementation-defined, so we cannot rely on the
10439   // linker replacing the tail call with a return.
10440   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10441     const GlobalValue *GV = G->getGlobal();
10442     if (GV->hasExternalWeakLinkage())
10443       return false;
10444   }
10445 
10446   // The callee has to preserve all registers the caller needs to preserve.
10447   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10448   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10449   if (CalleeCC != CallerCC) {
10450     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10451     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10452       return false;
10453   }
10454 
10455   // Byval parameters hand the function a pointer directly into the stack area
10456   // we want to reuse during a tail call. Working around this *is* possible
10457   // but less efficient and uglier in LowerCall.
10458   for (auto &Arg : Outs)
10459     if (Arg.Flags.isByVal())
10460       return false;
10461 
10462   return true;
10463 }
10464 
10465 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10466   return DAG.getDataLayout().getPrefTypeAlign(
10467       VT.getTypeForEVT(*DAG.getContext()));
10468 }
10469 
10470 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10471 // and output parameter nodes.
10472 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10473                                        SmallVectorImpl<SDValue> &InVals) const {
10474   SelectionDAG &DAG = CLI.DAG;
10475   SDLoc &DL = CLI.DL;
10476   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10477   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10478   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10479   SDValue Chain = CLI.Chain;
10480   SDValue Callee = CLI.Callee;
10481   bool &IsTailCall = CLI.IsTailCall;
10482   CallingConv::ID CallConv = CLI.CallConv;
10483   bool IsVarArg = CLI.IsVarArg;
10484   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10485   MVT XLenVT = Subtarget.getXLenVT();
10486 
10487   MachineFunction &MF = DAG.getMachineFunction();
10488 
10489   // Analyze the operands of the call, assigning locations to each operand.
10490   SmallVector<CCValAssign, 16> ArgLocs;
10491   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10492 
10493   if (CallConv == CallingConv::GHC)
10494     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10495   else
10496     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10497                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10498                                                     : CC_RISCV);
10499 
10500   // Check if it's really possible to do a tail call.
10501   if (IsTailCall)
10502     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10503 
10504   if (IsTailCall)
10505     ++NumTailCalls;
10506   else if (CLI.CB && CLI.CB->isMustTailCall())
10507     report_fatal_error("failed to perform tail call elimination on a call "
10508                        "site marked musttail");
10509 
10510   // Get a count of how many bytes are to be pushed on the stack.
10511   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10512 
10513   // Create local copies for byval args
10514   SmallVector<SDValue, 8> ByValArgs;
10515   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10516     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10517     if (!Flags.isByVal())
10518       continue;
10519 
10520     SDValue Arg = OutVals[i];
10521     unsigned Size = Flags.getByValSize();
10522     Align Alignment = Flags.getNonZeroByValAlign();
10523 
10524     int FI =
10525         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10526     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10527     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10528 
10529     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10530                           /*IsVolatile=*/false,
10531                           /*AlwaysInline=*/false, IsTailCall,
10532                           MachinePointerInfo(), MachinePointerInfo());
10533     ByValArgs.push_back(FIPtr);
10534   }
10535 
10536   if (!IsTailCall)
10537     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10538 
10539   // Copy argument values to their designated locations.
10540   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10541   SmallVector<SDValue, 8> MemOpChains;
10542   SDValue StackPtr;
10543   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10544     CCValAssign &VA = ArgLocs[i];
10545     SDValue ArgValue = OutVals[i];
10546     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10547 
10548     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10549     bool IsF64OnRV32DSoftABI =
10550         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10551     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10552       SDValue SplitF64 = DAG.getNode(
10553           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10554       SDValue Lo = SplitF64.getValue(0);
10555       SDValue Hi = SplitF64.getValue(1);
10556 
10557       Register RegLo = VA.getLocReg();
10558       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10559 
10560       if (RegLo == RISCV::X17) {
10561         // Second half of f64 is passed on the stack.
10562         // Work out the address of the stack slot.
10563         if (!StackPtr.getNode())
10564           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10565         // Emit the store.
10566         MemOpChains.push_back(
10567             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10568       } else {
10569         // Second half of f64 is passed in another GPR.
10570         assert(RegLo < RISCV::X31 && "Invalid register pair");
10571         Register RegHigh = RegLo + 1;
10572         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10573       }
10574       continue;
10575     }
10576 
10577     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10578     // as any other MemLoc.
10579 
10580     // Promote the value if needed.
10581     // For now, only handle fully promoted and indirect arguments.
10582     if (VA.getLocInfo() == CCValAssign::Indirect) {
10583       // Store the argument in a stack slot and pass its address.
10584       Align StackAlign =
10585           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10586                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10587       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10588       // If the original argument was split (e.g. i128), we need
10589       // to store the required parts of it here (and pass just one address).
10590       // Vectors may be partly split to registers and partly to the stack, in
10591       // which case the base address is partly offset and subsequent stores are
10592       // relative to that.
10593       unsigned ArgIndex = Outs[i].OrigArgIndex;
10594       unsigned ArgPartOffset = Outs[i].PartOffset;
10595       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10596       // Calculate the total size to store. We don't have access to what we're
10597       // actually storing other than performing the loop and collecting the
10598       // info.
10599       SmallVector<std::pair<SDValue, SDValue>> Parts;
10600       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10601         SDValue PartValue = OutVals[i + 1];
10602         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10603         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10604         EVT PartVT = PartValue.getValueType();
10605         if (PartVT.isScalableVector())
10606           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10607         StoredSize += PartVT.getStoreSize();
10608         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10609         Parts.push_back(std::make_pair(PartValue, Offset));
10610         ++i;
10611       }
10612       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10613       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10614       MemOpChains.push_back(
10615           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10616                        MachinePointerInfo::getFixedStack(MF, FI)));
10617       for (const auto &Part : Parts) {
10618         SDValue PartValue = Part.first;
10619         SDValue PartOffset = Part.second;
10620         SDValue Address =
10621             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10622         MemOpChains.push_back(
10623             DAG.getStore(Chain, DL, PartValue, Address,
10624                          MachinePointerInfo::getFixedStack(MF, FI)));
10625       }
10626       ArgValue = SpillSlot;
10627     } else {
10628       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10629     }
10630 
10631     // Use local copy if it is a byval arg.
10632     if (Flags.isByVal())
10633       ArgValue = ByValArgs[j++];
10634 
10635     if (VA.isRegLoc()) {
10636       // Queue up the argument copies and emit them at the end.
10637       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10638     } else {
10639       assert(VA.isMemLoc() && "Argument not register or memory");
10640       assert(!IsTailCall && "Tail call not allowed if stack is used "
10641                             "for passing parameters");
10642 
10643       // Work out the address of the stack slot.
10644       if (!StackPtr.getNode())
10645         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10646       SDValue Address =
10647           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10648                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10649 
10650       // Emit the store.
10651       MemOpChains.push_back(
10652           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10653     }
10654   }
10655 
10656   // Join the stores, which are independent of one another.
10657   if (!MemOpChains.empty())
10658     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10659 
10660   SDValue Glue;
10661 
10662   // Build a sequence of copy-to-reg nodes, chained and glued together.
10663   for (auto &Reg : RegsToPass) {
10664     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10665     Glue = Chain.getValue(1);
10666   }
10667 
10668   // Validate that none of the argument registers have been marked as
10669   // reserved, if so report an error. Do the same for the return address if this
10670   // is not a tailcall.
10671   validateCCReservedRegs(RegsToPass, MF);
10672   if (!IsTailCall &&
10673       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10674     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10675         MF.getFunction(),
10676         "Return address register required, but has been reserved."});
10677 
10678   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10679   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10680   // split it and then direct call can be matched by PseudoCALL.
10681   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10682     const GlobalValue *GV = S->getGlobal();
10683 
10684     unsigned OpFlags = RISCVII::MO_CALL;
10685     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10686       OpFlags = RISCVII::MO_PLT;
10687 
10688     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10689   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10690     unsigned OpFlags = RISCVII::MO_CALL;
10691 
10692     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10693                                                  nullptr))
10694       OpFlags = RISCVII::MO_PLT;
10695 
10696     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10697   }
10698 
10699   // The first call operand is the chain and the second is the target address.
10700   SmallVector<SDValue, 8> Ops;
10701   Ops.push_back(Chain);
10702   Ops.push_back(Callee);
10703 
10704   // Add argument registers to the end of the list so that they are
10705   // known live into the call.
10706   for (auto &Reg : RegsToPass)
10707     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10708 
10709   if (!IsTailCall) {
10710     // Add a register mask operand representing the call-preserved registers.
10711     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10712     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10713     assert(Mask && "Missing call preserved mask for calling convention");
10714     Ops.push_back(DAG.getRegisterMask(Mask));
10715   }
10716 
10717   // Glue the call to the argument copies, if any.
10718   if (Glue.getNode())
10719     Ops.push_back(Glue);
10720 
10721   // Emit the call.
10722   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10723 
10724   if (IsTailCall) {
10725     MF.getFrameInfo().setHasTailCall();
10726     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10727   }
10728 
10729   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10730   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10731   Glue = Chain.getValue(1);
10732 
10733   // Mark the end of the call, which is glued to the call itself.
10734   Chain = DAG.getCALLSEQ_END(Chain,
10735                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10736                              DAG.getConstant(0, DL, PtrVT, true),
10737                              Glue, DL);
10738   Glue = Chain.getValue(1);
10739 
10740   // Assign locations to each value returned by this call.
10741   SmallVector<CCValAssign, 16> RVLocs;
10742   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10743   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10744 
10745   // Copy all of the result registers out of their specified physreg.
10746   for (auto &VA : RVLocs) {
10747     // Copy the value out
10748     SDValue RetValue =
10749         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10750     // Glue the RetValue to the end of the call sequence
10751     Chain = RetValue.getValue(1);
10752     Glue = RetValue.getValue(2);
10753 
10754     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10755       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10756       SDValue RetValue2 =
10757           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10758       Chain = RetValue2.getValue(1);
10759       Glue = RetValue2.getValue(2);
10760       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10761                              RetValue2);
10762     }
10763 
10764     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10765 
10766     InVals.push_back(RetValue);
10767   }
10768 
10769   return Chain;
10770 }
10771 
10772 bool RISCVTargetLowering::CanLowerReturn(
10773     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10774     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10775   SmallVector<CCValAssign, 16> RVLocs;
10776   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10777 
10778   Optional<unsigned> FirstMaskArgument;
10779   if (Subtarget.hasVInstructions())
10780     FirstMaskArgument = preAssignMask(Outs);
10781 
10782   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10783     MVT VT = Outs[i].VT;
10784     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10785     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10786     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10787                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10788                  *this, FirstMaskArgument))
10789       return false;
10790   }
10791   return true;
10792 }
10793 
10794 SDValue
10795 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10796                                  bool IsVarArg,
10797                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10798                                  const SmallVectorImpl<SDValue> &OutVals,
10799                                  const SDLoc &DL, SelectionDAG &DAG) const {
10800   const MachineFunction &MF = DAG.getMachineFunction();
10801   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10802 
10803   // Stores the assignment of the return value to a location.
10804   SmallVector<CCValAssign, 16> RVLocs;
10805 
10806   // Info about the registers and stack slot.
10807   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10808                  *DAG.getContext());
10809 
10810   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10811                     nullptr, CC_RISCV);
10812 
10813   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10814     report_fatal_error("GHC functions return void only");
10815 
10816   SDValue Glue;
10817   SmallVector<SDValue, 4> RetOps(1, Chain);
10818 
10819   // Copy the result values into the output registers.
10820   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10821     SDValue Val = OutVals[i];
10822     CCValAssign &VA = RVLocs[i];
10823     assert(VA.isRegLoc() && "Can only return in registers!");
10824 
10825     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10826       // Handle returning f64 on RV32D with a soft float ABI.
10827       assert(VA.isRegLoc() && "Expected return via registers");
10828       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10829                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10830       SDValue Lo = SplitF64.getValue(0);
10831       SDValue Hi = SplitF64.getValue(1);
10832       Register RegLo = VA.getLocReg();
10833       assert(RegLo < RISCV::X31 && "Invalid register pair");
10834       Register RegHi = RegLo + 1;
10835 
10836       if (STI.isRegisterReservedByUser(RegLo) ||
10837           STI.isRegisterReservedByUser(RegHi))
10838         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10839             MF.getFunction(),
10840             "Return value register required, but has been reserved."});
10841 
10842       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10843       Glue = Chain.getValue(1);
10844       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10845       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10846       Glue = Chain.getValue(1);
10847       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10848     } else {
10849       // Handle a 'normal' return.
10850       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10851       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10852 
10853       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10854         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10855             MF.getFunction(),
10856             "Return value register required, but has been reserved."});
10857 
10858       // Guarantee that all emitted copies are stuck together.
10859       Glue = Chain.getValue(1);
10860       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10861     }
10862   }
10863 
10864   RetOps[0] = Chain; // Update chain.
10865 
10866   // Add the glue node if we have it.
10867   if (Glue.getNode()) {
10868     RetOps.push_back(Glue);
10869   }
10870 
10871   unsigned RetOpc = RISCVISD::RET_FLAG;
10872   // Interrupt service routines use different return instructions.
10873   const Function &Func = DAG.getMachineFunction().getFunction();
10874   if (Func.hasFnAttribute("interrupt")) {
10875     if (!Func.getReturnType()->isVoidTy())
10876       report_fatal_error(
10877           "Functions with the interrupt attribute must have void return type!");
10878 
10879     MachineFunction &MF = DAG.getMachineFunction();
10880     StringRef Kind =
10881       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10882 
10883     if (Kind == "user")
10884       RetOpc = RISCVISD::URET_FLAG;
10885     else if (Kind == "supervisor")
10886       RetOpc = RISCVISD::SRET_FLAG;
10887     else
10888       RetOpc = RISCVISD::MRET_FLAG;
10889   }
10890 
10891   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10892 }
10893 
10894 void RISCVTargetLowering::validateCCReservedRegs(
10895     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10896     MachineFunction &MF) const {
10897   const Function &F = MF.getFunction();
10898   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10899 
10900   if (llvm::any_of(Regs, [&STI](auto Reg) {
10901         return STI.isRegisterReservedByUser(Reg.first);
10902       }))
10903     F.getContext().diagnose(DiagnosticInfoUnsupported{
10904         F, "Argument register required, but has been reserved."});
10905 }
10906 
10907 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10908   return CI->isTailCall();
10909 }
10910 
10911 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10912 #define NODE_NAME_CASE(NODE)                                                   \
10913   case RISCVISD::NODE:                                                         \
10914     return "RISCVISD::" #NODE;
10915   // clang-format off
10916   switch ((RISCVISD::NodeType)Opcode) {
10917   case RISCVISD::FIRST_NUMBER:
10918     break;
10919   NODE_NAME_CASE(RET_FLAG)
10920   NODE_NAME_CASE(URET_FLAG)
10921   NODE_NAME_CASE(SRET_FLAG)
10922   NODE_NAME_CASE(MRET_FLAG)
10923   NODE_NAME_CASE(CALL)
10924   NODE_NAME_CASE(SELECT_CC)
10925   NODE_NAME_CASE(BR_CC)
10926   NODE_NAME_CASE(BuildPairF64)
10927   NODE_NAME_CASE(SplitF64)
10928   NODE_NAME_CASE(TAIL)
10929   NODE_NAME_CASE(MULHSU)
10930   NODE_NAME_CASE(SLLW)
10931   NODE_NAME_CASE(SRAW)
10932   NODE_NAME_CASE(SRLW)
10933   NODE_NAME_CASE(DIVW)
10934   NODE_NAME_CASE(DIVUW)
10935   NODE_NAME_CASE(REMUW)
10936   NODE_NAME_CASE(ROLW)
10937   NODE_NAME_CASE(RORW)
10938   NODE_NAME_CASE(CLZW)
10939   NODE_NAME_CASE(CTZW)
10940   NODE_NAME_CASE(FSLW)
10941   NODE_NAME_CASE(FSRW)
10942   NODE_NAME_CASE(FSL)
10943   NODE_NAME_CASE(FSR)
10944   NODE_NAME_CASE(FMV_H_X)
10945   NODE_NAME_CASE(FMV_X_ANYEXTH)
10946   NODE_NAME_CASE(FMV_X_SIGNEXTH)
10947   NODE_NAME_CASE(FMV_W_X_RV64)
10948   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10949   NODE_NAME_CASE(FCVT_X)
10950   NODE_NAME_CASE(FCVT_XU)
10951   NODE_NAME_CASE(FCVT_W_RV64)
10952   NODE_NAME_CASE(FCVT_WU_RV64)
10953   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10954   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10955   NODE_NAME_CASE(READ_CYCLE_WIDE)
10956   NODE_NAME_CASE(GREV)
10957   NODE_NAME_CASE(GREVW)
10958   NODE_NAME_CASE(GORC)
10959   NODE_NAME_CASE(GORCW)
10960   NODE_NAME_CASE(SHFL)
10961   NODE_NAME_CASE(SHFLW)
10962   NODE_NAME_CASE(UNSHFL)
10963   NODE_NAME_CASE(UNSHFLW)
10964   NODE_NAME_CASE(BFP)
10965   NODE_NAME_CASE(BFPW)
10966   NODE_NAME_CASE(BCOMPRESS)
10967   NODE_NAME_CASE(BCOMPRESSW)
10968   NODE_NAME_CASE(BDECOMPRESS)
10969   NODE_NAME_CASE(BDECOMPRESSW)
10970   NODE_NAME_CASE(VMV_V_X_VL)
10971   NODE_NAME_CASE(VFMV_V_F_VL)
10972   NODE_NAME_CASE(VMV_X_S)
10973   NODE_NAME_CASE(VMV_S_X_VL)
10974   NODE_NAME_CASE(VFMV_S_F_VL)
10975   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10976   NODE_NAME_CASE(READ_VLENB)
10977   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10978   NODE_NAME_CASE(VSLIDEUP_VL)
10979   NODE_NAME_CASE(VSLIDE1UP_VL)
10980   NODE_NAME_CASE(VSLIDEDOWN_VL)
10981   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10982   NODE_NAME_CASE(VID_VL)
10983   NODE_NAME_CASE(VFNCVT_ROD_VL)
10984   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10985   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10986   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10987   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10988   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10989   NODE_NAME_CASE(VECREDUCE_AND_VL)
10990   NODE_NAME_CASE(VECREDUCE_OR_VL)
10991   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10992   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10993   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10994   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10995   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10996   NODE_NAME_CASE(ADD_VL)
10997   NODE_NAME_CASE(AND_VL)
10998   NODE_NAME_CASE(MUL_VL)
10999   NODE_NAME_CASE(OR_VL)
11000   NODE_NAME_CASE(SDIV_VL)
11001   NODE_NAME_CASE(SHL_VL)
11002   NODE_NAME_CASE(SREM_VL)
11003   NODE_NAME_CASE(SRA_VL)
11004   NODE_NAME_CASE(SRL_VL)
11005   NODE_NAME_CASE(SUB_VL)
11006   NODE_NAME_CASE(UDIV_VL)
11007   NODE_NAME_CASE(UREM_VL)
11008   NODE_NAME_CASE(XOR_VL)
11009   NODE_NAME_CASE(SADDSAT_VL)
11010   NODE_NAME_CASE(UADDSAT_VL)
11011   NODE_NAME_CASE(SSUBSAT_VL)
11012   NODE_NAME_CASE(USUBSAT_VL)
11013   NODE_NAME_CASE(FADD_VL)
11014   NODE_NAME_CASE(FSUB_VL)
11015   NODE_NAME_CASE(FMUL_VL)
11016   NODE_NAME_CASE(FDIV_VL)
11017   NODE_NAME_CASE(FNEG_VL)
11018   NODE_NAME_CASE(FABS_VL)
11019   NODE_NAME_CASE(FSQRT_VL)
11020   NODE_NAME_CASE(FMA_VL)
11021   NODE_NAME_CASE(FCOPYSIGN_VL)
11022   NODE_NAME_CASE(SMIN_VL)
11023   NODE_NAME_CASE(SMAX_VL)
11024   NODE_NAME_CASE(UMIN_VL)
11025   NODE_NAME_CASE(UMAX_VL)
11026   NODE_NAME_CASE(FMINNUM_VL)
11027   NODE_NAME_CASE(FMAXNUM_VL)
11028   NODE_NAME_CASE(MULHS_VL)
11029   NODE_NAME_CASE(MULHU_VL)
11030   NODE_NAME_CASE(FP_TO_SINT_VL)
11031   NODE_NAME_CASE(FP_TO_UINT_VL)
11032   NODE_NAME_CASE(SINT_TO_FP_VL)
11033   NODE_NAME_CASE(UINT_TO_FP_VL)
11034   NODE_NAME_CASE(FP_EXTEND_VL)
11035   NODE_NAME_CASE(FP_ROUND_VL)
11036   NODE_NAME_CASE(VWMUL_VL)
11037   NODE_NAME_CASE(VWMULU_VL)
11038   NODE_NAME_CASE(VWMULSU_VL)
11039   NODE_NAME_CASE(VWADD_VL)
11040   NODE_NAME_CASE(VWADDU_VL)
11041   NODE_NAME_CASE(VWSUB_VL)
11042   NODE_NAME_CASE(VWSUBU_VL)
11043   NODE_NAME_CASE(VWADD_W_VL)
11044   NODE_NAME_CASE(VWADDU_W_VL)
11045   NODE_NAME_CASE(VWSUB_W_VL)
11046   NODE_NAME_CASE(VWSUBU_W_VL)
11047   NODE_NAME_CASE(SETCC_VL)
11048   NODE_NAME_CASE(VSELECT_VL)
11049   NODE_NAME_CASE(VP_MERGE_VL)
11050   NODE_NAME_CASE(VMAND_VL)
11051   NODE_NAME_CASE(VMOR_VL)
11052   NODE_NAME_CASE(VMXOR_VL)
11053   NODE_NAME_CASE(VMCLR_VL)
11054   NODE_NAME_CASE(VMSET_VL)
11055   NODE_NAME_CASE(VRGATHER_VX_VL)
11056   NODE_NAME_CASE(VRGATHER_VV_VL)
11057   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
11058   NODE_NAME_CASE(VSEXT_VL)
11059   NODE_NAME_CASE(VZEXT_VL)
11060   NODE_NAME_CASE(VCPOP_VL)
11061   NODE_NAME_CASE(READ_CSR)
11062   NODE_NAME_CASE(WRITE_CSR)
11063   NODE_NAME_CASE(SWAP_CSR)
11064   }
11065   // clang-format on
11066   return nullptr;
11067 #undef NODE_NAME_CASE
11068 }
11069 
11070 /// getConstraintType - Given a constraint letter, return the type of
11071 /// constraint it is for this target.
11072 RISCVTargetLowering::ConstraintType
11073 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
11074   if (Constraint.size() == 1) {
11075     switch (Constraint[0]) {
11076     default:
11077       break;
11078     case 'f':
11079       return C_RegisterClass;
11080     case 'I':
11081     case 'J':
11082     case 'K':
11083       return C_Immediate;
11084     case 'A':
11085       return C_Memory;
11086     case 'S': // A symbolic address
11087       return C_Other;
11088     }
11089   } else {
11090     if (Constraint == "vr" || Constraint == "vm")
11091       return C_RegisterClass;
11092   }
11093   return TargetLowering::getConstraintType(Constraint);
11094 }
11095 
11096 std::pair<unsigned, const TargetRegisterClass *>
11097 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11098                                                   StringRef Constraint,
11099                                                   MVT VT) const {
11100   // First, see if this is a constraint that directly corresponds to a
11101   // RISCV register class.
11102   if (Constraint.size() == 1) {
11103     switch (Constraint[0]) {
11104     case 'r':
11105       // TODO: Support fixed vectors up to XLen for P extension?
11106       if (VT.isVector())
11107         break;
11108       return std::make_pair(0U, &RISCV::GPRRegClass);
11109     case 'f':
11110       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
11111         return std::make_pair(0U, &RISCV::FPR16RegClass);
11112       if (Subtarget.hasStdExtF() && VT == MVT::f32)
11113         return std::make_pair(0U, &RISCV::FPR32RegClass);
11114       if (Subtarget.hasStdExtD() && VT == MVT::f64)
11115         return std::make_pair(0U, &RISCV::FPR64RegClass);
11116       break;
11117     default:
11118       break;
11119     }
11120   } else if (Constraint == "vr") {
11121     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
11122                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11123       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
11124         return std::make_pair(0U, RC);
11125     }
11126   } else if (Constraint == "vm") {
11127     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
11128       return std::make_pair(0U, &RISCV::VMV0RegClass);
11129   }
11130 
11131   // Clang will correctly decode the usage of register name aliases into their
11132   // official names. However, other frontends like `rustc` do not. This allows
11133   // users of these frontends to use the ABI names for registers in LLVM-style
11134   // register constraints.
11135   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
11136                                .Case("{zero}", RISCV::X0)
11137                                .Case("{ra}", RISCV::X1)
11138                                .Case("{sp}", RISCV::X2)
11139                                .Case("{gp}", RISCV::X3)
11140                                .Case("{tp}", RISCV::X4)
11141                                .Case("{t0}", RISCV::X5)
11142                                .Case("{t1}", RISCV::X6)
11143                                .Case("{t2}", RISCV::X7)
11144                                .Cases("{s0}", "{fp}", RISCV::X8)
11145                                .Case("{s1}", RISCV::X9)
11146                                .Case("{a0}", RISCV::X10)
11147                                .Case("{a1}", RISCV::X11)
11148                                .Case("{a2}", RISCV::X12)
11149                                .Case("{a3}", RISCV::X13)
11150                                .Case("{a4}", RISCV::X14)
11151                                .Case("{a5}", RISCV::X15)
11152                                .Case("{a6}", RISCV::X16)
11153                                .Case("{a7}", RISCV::X17)
11154                                .Case("{s2}", RISCV::X18)
11155                                .Case("{s3}", RISCV::X19)
11156                                .Case("{s4}", RISCV::X20)
11157                                .Case("{s5}", RISCV::X21)
11158                                .Case("{s6}", RISCV::X22)
11159                                .Case("{s7}", RISCV::X23)
11160                                .Case("{s8}", RISCV::X24)
11161                                .Case("{s9}", RISCV::X25)
11162                                .Case("{s10}", RISCV::X26)
11163                                .Case("{s11}", RISCV::X27)
11164                                .Case("{t3}", RISCV::X28)
11165                                .Case("{t4}", RISCV::X29)
11166                                .Case("{t5}", RISCV::X30)
11167                                .Case("{t6}", RISCV::X31)
11168                                .Default(RISCV::NoRegister);
11169   if (XRegFromAlias != RISCV::NoRegister)
11170     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
11171 
11172   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
11173   // TableGen record rather than the AsmName to choose registers for InlineAsm
11174   // constraints, plus we want to match those names to the widest floating point
11175   // register type available, manually select floating point registers here.
11176   //
11177   // The second case is the ABI name of the register, so that frontends can also
11178   // use the ABI names in register constraint lists.
11179   if (Subtarget.hasStdExtF()) {
11180     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
11181                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
11182                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
11183                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
11184                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
11185                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
11186                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
11187                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
11188                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
11189                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
11190                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
11191                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
11192                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
11193                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
11194                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
11195                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
11196                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
11197                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
11198                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
11199                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
11200                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
11201                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
11202                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
11203                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
11204                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
11205                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
11206                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
11207                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
11208                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
11209                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
11210                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
11211                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
11212                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
11213                         .Default(RISCV::NoRegister);
11214     if (FReg != RISCV::NoRegister) {
11215       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
11216       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
11217         unsigned RegNo = FReg - RISCV::F0_F;
11218         unsigned DReg = RISCV::F0_D + RegNo;
11219         return std::make_pair(DReg, &RISCV::FPR64RegClass);
11220       }
11221       if (VT == MVT::f32 || VT == MVT::Other)
11222         return std::make_pair(FReg, &RISCV::FPR32RegClass);
11223       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
11224         unsigned RegNo = FReg - RISCV::F0_F;
11225         unsigned HReg = RISCV::F0_H + RegNo;
11226         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11227       }
11228     }
11229   }
11230 
11231   if (Subtarget.hasVInstructions()) {
11232     Register VReg = StringSwitch<Register>(Constraint.lower())
11233                         .Case("{v0}", RISCV::V0)
11234                         .Case("{v1}", RISCV::V1)
11235                         .Case("{v2}", RISCV::V2)
11236                         .Case("{v3}", RISCV::V3)
11237                         .Case("{v4}", RISCV::V4)
11238                         .Case("{v5}", RISCV::V5)
11239                         .Case("{v6}", RISCV::V6)
11240                         .Case("{v7}", RISCV::V7)
11241                         .Case("{v8}", RISCV::V8)
11242                         .Case("{v9}", RISCV::V9)
11243                         .Case("{v10}", RISCV::V10)
11244                         .Case("{v11}", RISCV::V11)
11245                         .Case("{v12}", RISCV::V12)
11246                         .Case("{v13}", RISCV::V13)
11247                         .Case("{v14}", RISCV::V14)
11248                         .Case("{v15}", RISCV::V15)
11249                         .Case("{v16}", RISCV::V16)
11250                         .Case("{v17}", RISCV::V17)
11251                         .Case("{v18}", RISCV::V18)
11252                         .Case("{v19}", RISCV::V19)
11253                         .Case("{v20}", RISCV::V20)
11254                         .Case("{v21}", RISCV::V21)
11255                         .Case("{v22}", RISCV::V22)
11256                         .Case("{v23}", RISCV::V23)
11257                         .Case("{v24}", RISCV::V24)
11258                         .Case("{v25}", RISCV::V25)
11259                         .Case("{v26}", RISCV::V26)
11260                         .Case("{v27}", RISCV::V27)
11261                         .Case("{v28}", RISCV::V28)
11262                         .Case("{v29}", RISCV::V29)
11263                         .Case("{v30}", RISCV::V30)
11264                         .Case("{v31}", RISCV::V31)
11265                         .Default(RISCV::NoRegister);
11266     if (VReg != RISCV::NoRegister) {
11267       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11268         return std::make_pair(VReg, &RISCV::VMRegClass);
11269       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11270         return std::make_pair(VReg, &RISCV::VRRegClass);
11271       for (const auto *RC :
11272            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11273         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11274           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11275           return std::make_pair(VReg, RC);
11276         }
11277       }
11278     }
11279   }
11280 
11281   std::pair<Register, const TargetRegisterClass *> Res =
11282       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11283 
11284   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11285   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11286   // Subtarget into account.
11287   if (Res.second == &RISCV::GPRF16RegClass ||
11288       Res.second == &RISCV::GPRF32RegClass ||
11289       Res.second == &RISCV::GPRF64RegClass)
11290     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11291 
11292   return Res;
11293 }
11294 
11295 unsigned
11296 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11297   // Currently only support length 1 constraints.
11298   if (ConstraintCode.size() == 1) {
11299     switch (ConstraintCode[0]) {
11300     case 'A':
11301       return InlineAsm::Constraint_A;
11302     default:
11303       break;
11304     }
11305   }
11306 
11307   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11308 }
11309 
11310 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11311     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11312     SelectionDAG &DAG) const {
11313   // Currently only support length 1 constraints.
11314   if (Constraint.length() == 1) {
11315     switch (Constraint[0]) {
11316     case 'I':
11317       // Validate & create a 12-bit signed immediate operand.
11318       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11319         uint64_t CVal = C->getSExtValue();
11320         if (isInt<12>(CVal))
11321           Ops.push_back(
11322               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11323       }
11324       return;
11325     case 'J':
11326       // Validate & create an integer zero operand.
11327       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11328         if (C->getZExtValue() == 0)
11329           Ops.push_back(
11330               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11331       return;
11332     case 'K':
11333       // Validate & create a 5-bit unsigned immediate operand.
11334       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11335         uint64_t CVal = C->getZExtValue();
11336         if (isUInt<5>(CVal))
11337           Ops.push_back(
11338               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11339       }
11340       return;
11341     case 'S':
11342       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11343         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11344                                                  GA->getValueType(0)));
11345       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11346         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11347                                                 BA->getValueType(0)));
11348       }
11349       return;
11350     default:
11351       break;
11352     }
11353   }
11354   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11355 }
11356 
11357 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11358                                                    Instruction *Inst,
11359                                                    AtomicOrdering Ord) const {
11360   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11361     return Builder.CreateFence(Ord);
11362   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11363     return Builder.CreateFence(AtomicOrdering::Release);
11364   return nullptr;
11365 }
11366 
11367 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11368                                                     Instruction *Inst,
11369                                                     AtomicOrdering Ord) const {
11370   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11371     return Builder.CreateFence(AtomicOrdering::Acquire);
11372   return nullptr;
11373 }
11374 
11375 TargetLowering::AtomicExpansionKind
11376 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11377   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11378   // point operations can't be used in an lr/sc sequence without breaking the
11379   // forward-progress guarantee.
11380   if (AI->isFloatingPointOperation())
11381     return AtomicExpansionKind::CmpXChg;
11382 
11383   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11384   if (Size == 8 || Size == 16)
11385     return AtomicExpansionKind::MaskedIntrinsic;
11386   return AtomicExpansionKind::None;
11387 }
11388 
11389 static Intrinsic::ID
11390 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11391   if (XLen == 32) {
11392     switch (BinOp) {
11393     default:
11394       llvm_unreachable("Unexpected AtomicRMW BinOp");
11395     case AtomicRMWInst::Xchg:
11396       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11397     case AtomicRMWInst::Add:
11398       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11399     case AtomicRMWInst::Sub:
11400       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11401     case AtomicRMWInst::Nand:
11402       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11403     case AtomicRMWInst::Max:
11404       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11405     case AtomicRMWInst::Min:
11406       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11407     case AtomicRMWInst::UMax:
11408       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11409     case AtomicRMWInst::UMin:
11410       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11411     }
11412   }
11413 
11414   if (XLen == 64) {
11415     switch (BinOp) {
11416     default:
11417       llvm_unreachable("Unexpected AtomicRMW BinOp");
11418     case AtomicRMWInst::Xchg:
11419       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11420     case AtomicRMWInst::Add:
11421       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11422     case AtomicRMWInst::Sub:
11423       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11424     case AtomicRMWInst::Nand:
11425       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11426     case AtomicRMWInst::Max:
11427       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11428     case AtomicRMWInst::Min:
11429       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11430     case AtomicRMWInst::UMax:
11431       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11432     case AtomicRMWInst::UMin:
11433       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11434     }
11435   }
11436 
11437   llvm_unreachable("Unexpected XLen\n");
11438 }
11439 
11440 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11441     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11442     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11443   unsigned XLen = Subtarget.getXLen();
11444   Value *Ordering =
11445       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11446   Type *Tys[] = {AlignedAddr->getType()};
11447   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11448       AI->getModule(),
11449       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11450 
11451   if (XLen == 64) {
11452     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11453     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11454     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11455   }
11456 
11457   Value *Result;
11458 
11459   // Must pass the shift amount needed to sign extend the loaded value prior
11460   // to performing a signed comparison for min/max. ShiftAmt is the number of
11461   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11462   // is the number of bits to left+right shift the value in order to
11463   // sign-extend.
11464   if (AI->getOperation() == AtomicRMWInst::Min ||
11465       AI->getOperation() == AtomicRMWInst::Max) {
11466     const DataLayout &DL = AI->getModule()->getDataLayout();
11467     unsigned ValWidth =
11468         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11469     Value *SextShamt =
11470         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11471     Result = Builder.CreateCall(LrwOpScwLoop,
11472                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11473   } else {
11474     Result =
11475         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11476   }
11477 
11478   if (XLen == 64)
11479     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11480   return Result;
11481 }
11482 
11483 TargetLowering::AtomicExpansionKind
11484 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11485     AtomicCmpXchgInst *CI) const {
11486   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11487   if (Size == 8 || Size == 16)
11488     return AtomicExpansionKind::MaskedIntrinsic;
11489   return AtomicExpansionKind::None;
11490 }
11491 
11492 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11493     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11494     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11495   unsigned XLen = Subtarget.getXLen();
11496   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11497   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11498   if (XLen == 64) {
11499     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11500     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11501     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11502     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11503   }
11504   Type *Tys[] = {AlignedAddr->getType()};
11505   Function *MaskedCmpXchg =
11506       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11507   Value *Result = Builder.CreateCall(
11508       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11509   if (XLen == 64)
11510     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11511   return Result;
11512 }
11513 
11514 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
11515   return false;
11516 }
11517 
11518 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11519                                                EVT VT) const {
11520   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11521     return false;
11522 
11523   switch (FPVT.getSimpleVT().SimpleTy) {
11524   case MVT::f16:
11525     return Subtarget.hasStdExtZfh();
11526   case MVT::f32:
11527     return Subtarget.hasStdExtF();
11528   case MVT::f64:
11529     return Subtarget.hasStdExtD();
11530   default:
11531     return false;
11532   }
11533 }
11534 
11535 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11536   // If we are using the small code model, we can reduce size of jump table
11537   // entry to 4 bytes.
11538   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11539       getTargetMachine().getCodeModel() == CodeModel::Small) {
11540     return MachineJumpTableInfo::EK_Custom32;
11541   }
11542   return TargetLowering::getJumpTableEncoding();
11543 }
11544 
11545 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11546     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11547     unsigned uid, MCContext &Ctx) const {
11548   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11549          getTargetMachine().getCodeModel() == CodeModel::Small);
11550   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11551 }
11552 
11553 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11554                                                      EVT VT) const {
11555   VT = VT.getScalarType();
11556 
11557   if (!VT.isSimple())
11558     return false;
11559 
11560   switch (VT.getSimpleVT().SimpleTy) {
11561   case MVT::f16:
11562     return Subtarget.hasStdExtZfh();
11563   case MVT::f32:
11564     return Subtarget.hasStdExtF();
11565   case MVT::f64:
11566     return Subtarget.hasStdExtD();
11567   default:
11568     break;
11569   }
11570 
11571   return false;
11572 }
11573 
11574 Register RISCVTargetLowering::getExceptionPointerRegister(
11575     const Constant *PersonalityFn) const {
11576   return RISCV::X10;
11577 }
11578 
11579 Register RISCVTargetLowering::getExceptionSelectorRegister(
11580     const Constant *PersonalityFn) const {
11581   return RISCV::X11;
11582 }
11583 
11584 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11585   // Return false to suppress the unnecessary extensions if the LibCall
11586   // arguments or return value is f32 type for LP64 ABI.
11587   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11588   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11589     return false;
11590 
11591   return true;
11592 }
11593 
11594 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11595   if (Subtarget.is64Bit() && Type == MVT::i32)
11596     return true;
11597 
11598   return IsSigned;
11599 }
11600 
11601 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11602                                                  SDValue C) const {
11603   // Check integral scalar types.
11604   if (VT.isScalarInteger()) {
11605     // Omit the optimization if the sub target has the M extension and the data
11606     // size exceeds XLen.
11607     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11608       return false;
11609     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11610       // Break the MUL to a SLLI and an ADD/SUB.
11611       const APInt &Imm = ConstNode->getAPIntValue();
11612       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11613           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11614         return true;
11615       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11616       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11617           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11618            (Imm - 8).isPowerOf2()))
11619         return true;
11620       // Omit the following optimization if the sub target has the M extension
11621       // and the data size >= XLen.
11622       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11623         return false;
11624       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11625       // a pair of LUI/ADDI.
11626       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11627         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11628         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11629             (1 - ImmS).isPowerOf2())
11630         return true;
11631       }
11632     }
11633   }
11634 
11635   return false;
11636 }
11637 
11638 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
11639                                                       SDValue ConstNode) const {
11640   // Let the DAGCombiner decide for vectors.
11641   EVT VT = AddNode.getValueType();
11642   if (VT.isVector())
11643     return true;
11644 
11645   // Let the DAGCombiner decide for larger types.
11646   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11647     return true;
11648 
11649   // It is worse if c1 is simm12 while c1*c2 is not.
11650   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11651   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11652   const APInt &C1 = C1Node->getAPIntValue();
11653   const APInt &C2 = C2Node->getAPIntValue();
11654   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11655     return false;
11656 
11657   // Default to true and let the DAGCombiner decide.
11658   return true;
11659 }
11660 
11661 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11662     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11663     bool *Fast) const {
11664   if (!VT.isVector())
11665     return false;
11666 
11667   EVT ElemVT = VT.getVectorElementType();
11668   if (Alignment >= ElemVT.getStoreSize()) {
11669     if (Fast)
11670       *Fast = true;
11671     return true;
11672   }
11673 
11674   return false;
11675 }
11676 
11677 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11678     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11679     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11680   bool IsABIRegCopy = CC.hasValue();
11681   EVT ValueVT = Val.getValueType();
11682   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11683     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11684     // and cast to f32.
11685     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11686     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11687     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11688                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11689     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11690     Parts[0] = Val;
11691     return true;
11692   }
11693 
11694   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11695     LLVMContext &Context = *DAG.getContext();
11696     EVT ValueEltVT = ValueVT.getVectorElementType();
11697     EVT PartEltVT = PartVT.getVectorElementType();
11698     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11699     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11700     if (PartVTBitSize % ValueVTBitSize == 0) {
11701       assert(PartVTBitSize >= ValueVTBitSize);
11702       // If the element types are different, bitcast to the same element type of
11703       // PartVT first.
11704       // Give an example here, we want copy a <vscale x 1 x i8> value to
11705       // <vscale x 4 x i16>.
11706       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11707       // subvector, then we can bitcast to <vscale x 4 x i16>.
11708       if (ValueEltVT != PartEltVT) {
11709         if (PartVTBitSize > ValueVTBitSize) {
11710           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11711           assert(Count != 0 && "The number of element should not be zero.");
11712           EVT SameEltTypeVT =
11713               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11714           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11715                             DAG.getUNDEF(SameEltTypeVT), Val,
11716                             DAG.getVectorIdxConstant(0, DL));
11717         }
11718         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11719       } else {
11720         Val =
11721             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11722                         Val, DAG.getVectorIdxConstant(0, DL));
11723       }
11724       Parts[0] = Val;
11725       return true;
11726     }
11727   }
11728   return false;
11729 }
11730 
11731 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11732     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11733     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11734   bool IsABIRegCopy = CC.hasValue();
11735   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11736     SDValue Val = Parts[0];
11737 
11738     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11739     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11740     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11741     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11742     return Val;
11743   }
11744 
11745   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11746     LLVMContext &Context = *DAG.getContext();
11747     SDValue Val = Parts[0];
11748     EVT ValueEltVT = ValueVT.getVectorElementType();
11749     EVT PartEltVT = PartVT.getVectorElementType();
11750     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11751     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11752     if (PartVTBitSize % ValueVTBitSize == 0) {
11753       assert(PartVTBitSize >= ValueVTBitSize);
11754       EVT SameEltTypeVT = ValueVT;
11755       // If the element types are different, convert it to the same element type
11756       // of PartVT.
11757       // Give an example here, we want copy a <vscale x 1 x i8> value from
11758       // <vscale x 4 x i16>.
11759       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11760       // then we can extract <vscale x 1 x i8>.
11761       if (ValueEltVT != PartEltVT) {
11762         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11763         assert(Count != 0 && "The number of element should not be zero.");
11764         SameEltTypeVT =
11765             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11766         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11767       }
11768       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11769                         DAG.getVectorIdxConstant(0, DL));
11770       return Val;
11771     }
11772   }
11773   return SDValue();
11774 }
11775 
11776 SDValue
11777 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11778                                    SelectionDAG &DAG,
11779                                    SmallVectorImpl<SDNode *> &Created) const {
11780   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11781   if (isIntDivCheap(N->getValueType(0), Attr))
11782     return SDValue(N, 0); // Lower SDIV as SDIV
11783 
11784   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11785          "Unexpected divisor!");
11786 
11787   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11788   if (!Subtarget.hasStdExtZbt())
11789     return SDValue();
11790 
11791   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11792   // Besides, more critical path instructions will be generated when dividing
11793   // by 2. So we keep using the original DAGs for these cases.
11794   unsigned Lg2 = Divisor.countTrailingZeros();
11795   if (Lg2 == 1 || Lg2 >= 12)
11796     return SDValue();
11797 
11798   // fold (sdiv X, pow2)
11799   EVT VT = N->getValueType(0);
11800   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11801     return SDValue();
11802 
11803   SDLoc DL(N);
11804   SDValue N0 = N->getOperand(0);
11805   SDValue Zero = DAG.getConstant(0, DL, VT);
11806   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11807 
11808   // Add (N0 < 0) ? Pow2 - 1 : 0;
11809   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
11810   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11811   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11812 
11813   Created.push_back(Cmp.getNode());
11814   Created.push_back(Add.getNode());
11815   Created.push_back(Sel.getNode());
11816 
11817   // Divide by pow2.
11818   SDValue SRA =
11819       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11820 
11821   // If we're dividing by a positive value, we're done.  Otherwise, we must
11822   // negate the result.
11823   if (Divisor.isNonNegative())
11824     return SRA;
11825 
11826   Created.push_back(SRA.getNode());
11827   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11828 }
11829 
11830 #define GET_REGISTER_MATCHER
11831 #include "RISCVGenAsmMatcher.inc"
11832 
11833 Register
11834 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11835                                        const MachineFunction &MF) const {
11836   Register Reg = MatchRegisterAltName(RegName);
11837   if (Reg == RISCV::NoRegister)
11838     Reg = MatchRegisterName(RegName);
11839   if (Reg == RISCV::NoRegister)
11840     report_fatal_error(
11841         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11842   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11843   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11844     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11845                              StringRef(RegName) + "\"."));
11846   return Reg;
11847 }
11848 
11849 namespace llvm {
11850 namespace RISCVVIntrinsicsTable {
11851 
11852 #define GET_RISCVVIntrinsicsTable_IMPL
11853 #include "RISCVGenSearchableTables.inc"
11854 
11855 } // namespace RISCVVIntrinsicsTable
11856 
11857 } // namespace llvm
11858