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};
494 
495     static const unsigned FloatingPointVPOps[] = {
496         ISD::VP_FADD,        ISD::VP_FSUB,        ISD::VP_FMUL,
497         ISD::VP_FDIV,        ISD::VP_FNEG,        ISD::VP_FMA,
498         ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, ISD::VP_REDUCE_FMIN,
499         ISD::VP_REDUCE_FMAX, ISD::VP_MERGE,       ISD::VP_SELECT};
500 
501     if (!Subtarget.is64Bit()) {
502       // We must custom-lower certain vXi64 operations on RV32 due to the vector
503       // element type being illegal.
504       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::i64, Custom);
505       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::i64, Custom);
506 
507       setOperationAction(ISD::VECREDUCE_ADD, MVT::i64, Custom);
508       setOperationAction(ISD::VECREDUCE_AND, MVT::i64, Custom);
509       setOperationAction(ISD::VECREDUCE_OR, MVT::i64, Custom);
510       setOperationAction(ISD::VECREDUCE_XOR, MVT::i64, Custom);
511       setOperationAction(ISD::VECREDUCE_SMAX, MVT::i64, Custom);
512       setOperationAction(ISD::VECREDUCE_SMIN, MVT::i64, Custom);
513       setOperationAction(ISD::VECREDUCE_UMAX, MVT::i64, Custom);
514       setOperationAction(ISD::VECREDUCE_UMIN, MVT::i64, Custom);
515 
516       setOperationAction(ISD::VP_REDUCE_ADD, MVT::i64, Custom);
517       setOperationAction(ISD::VP_REDUCE_AND, MVT::i64, Custom);
518       setOperationAction(ISD::VP_REDUCE_OR, MVT::i64, Custom);
519       setOperationAction(ISD::VP_REDUCE_XOR, MVT::i64, Custom);
520       setOperationAction(ISD::VP_REDUCE_SMAX, MVT::i64, Custom);
521       setOperationAction(ISD::VP_REDUCE_SMIN, MVT::i64, Custom);
522       setOperationAction(ISD::VP_REDUCE_UMAX, MVT::i64, Custom);
523       setOperationAction(ISD::VP_REDUCE_UMIN, MVT::i64, Custom);
524     }
525 
526     for (MVT VT : BoolVecVTs) {
527       setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
528 
529       // Mask VTs are custom-expanded into a series of standard nodes
530       setOperationAction(ISD::TRUNCATE, VT, Custom);
531       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
532       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
533       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
534 
535       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
536       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
537 
538       setOperationAction(ISD::SELECT, VT, Custom);
539       setOperationAction(ISD::SELECT_CC, VT, Expand);
540       setOperationAction(ISD::VSELECT, VT, Expand);
541       setOperationAction(ISD::VP_MERGE, VT, Expand);
542       setOperationAction(ISD::VP_SELECT, VT, Expand);
543 
544       setOperationAction(ISD::VP_AND, VT, Custom);
545       setOperationAction(ISD::VP_OR, VT, Custom);
546       setOperationAction(ISD::VP_XOR, VT, Custom);
547 
548       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
549       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
550       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
551 
552       setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
553       setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
554       setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
555 
556       // RVV has native int->float & float->int conversions where the
557       // element type sizes are within one power-of-two of each other. Any
558       // wider distances between type sizes have to be lowered as sequences
559       // which progressively narrow the gap in stages.
560       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
561       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
562       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
563       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
564 
565       // Expand all extending loads to types larger than this, and truncating
566       // stores from types larger than this.
567       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
568         setTruncStoreAction(OtherVT, VT, Expand);
569         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
570         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
571         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
572       }
573     }
574 
575     for (MVT VT : IntVecVTs) {
576       if (VT.getVectorElementType() == MVT::i64 &&
577           !Subtarget.hasVInstructionsI64())
578         continue;
579 
580       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
581       setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
582 
583       // Vectors implement MULHS/MULHU.
584       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
585       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
586 
587       // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
588       if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) {
589         setOperationAction(ISD::MULHU, VT, Expand);
590         setOperationAction(ISD::MULHS, VT, Expand);
591       }
592 
593       setOperationAction(ISD::SMIN, VT, Legal);
594       setOperationAction(ISD::SMAX, VT, Legal);
595       setOperationAction(ISD::UMIN, VT, Legal);
596       setOperationAction(ISD::UMAX, VT, Legal);
597 
598       setOperationAction(ISD::ROTL, VT, Expand);
599       setOperationAction(ISD::ROTR, VT, Expand);
600 
601       setOperationAction(ISD::CTTZ, VT, Expand);
602       setOperationAction(ISD::CTLZ, VT, Expand);
603       setOperationAction(ISD::CTPOP, VT, Expand);
604 
605       setOperationAction(ISD::BSWAP, VT, Expand);
606 
607       // Custom-lower extensions and truncations from/to mask types.
608       setOperationAction(ISD::ANY_EXTEND, VT, Custom);
609       setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
610       setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
611 
612       // RVV has native int->float & float->int conversions where the
613       // element type sizes are within one power-of-two of each other. Any
614       // wider distances between type sizes have to be lowered as sequences
615       // which progressively narrow the gap in stages.
616       setOperationAction(ISD::SINT_TO_FP, VT, Custom);
617       setOperationAction(ISD::UINT_TO_FP, VT, Custom);
618       setOperationAction(ISD::FP_TO_SINT, VT, Custom);
619       setOperationAction(ISD::FP_TO_UINT, VT, Custom);
620 
621       setOperationAction(ISD::SADDSAT, VT, Legal);
622       setOperationAction(ISD::UADDSAT, VT, Legal);
623       setOperationAction(ISD::SSUBSAT, VT, Legal);
624       setOperationAction(ISD::USUBSAT, VT, Legal);
625 
626       // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
627       // nodes which truncate by one power of two at a time.
628       setOperationAction(ISD::TRUNCATE, VT, Custom);
629 
630       // Custom-lower insert/extract operations to simplify patterns.
631       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
632       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
633 
634       // Custom-lower reduction operations to set up the corresponding custom
635       // nodes' operands.
636       setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
637       setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
638       setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
639       setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
640       setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
641       setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
642       setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
643       setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
644 
645       for (unsigned VPOpc : IntegerVPOps)
646         setOperationAction(VPOpc, VT, Custom);
647 
648       setOperationAction(ISD::LOAD, VT, Custom);
649       setOperationAction(ISD::STORE, VT, Custom);
650 
651       setOperationAction(ISD::MLOAD, VT, Custom);
652       setOperationAction(ISD::MSTORE, VT, Custom);
653       setOperationAction(ISD::MGATHER, VT, Custom);
654       setOperationAction(ISD::MSCATTER, VT, Custom);
655 
656       setOperationAction(ISD::VP_LOAD, VT, Custom);
657       setOperationAction(ISD::VP_STORE, VT, Custom);
658       setOperationAction(ISD::VP_GATHER, VT, Custom);
659       setOperationAction(ISD::VP_SCATTER, VT, Custom);
660 
661       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
662       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
663       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
664 
665       setOperationAction(ISD::SELECT, VT, Custom);
666       setOperationAction(ISD::SELECT_CC, VT, Expand);
667 
668       setOperationAction(ISD::STEP_VECTOR, VT, Custom);
669       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
670 
671       for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
672         setTruncStoreAction(VT, OtherVT, Expand);
673         setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
674         setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
675         setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
676       }
677 
678       // Splice
679       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
680 
681       // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
682       // type that can represent the value exactly.
683       if (VT.getVectorElementType() != MVT::i64) {
684         MVT FloatEltVT =
685             VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
686         EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
687         if (isTypeLegal(FloatVT)) {
688           setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
689           setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
690         }
691       }
692     }
693 
694     // Expand various CCs to best match the RVV ISA, which natively supports UNE
695     // but no other unordered comparisons, and supports all ordered comparisons
696     // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
697     // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
698     // and we pattern-match those back to the "original", swapping operands once
699     // more. This way we catch both operations and both "vf" and "fv" forms with
700     // fewer patterns.
701     static const ISD::CondCode VFPCCToExpand[] = {
702         ISD::SETO,   ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
703         ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
704         ISD::SETGT,  ISD::SETOGT, ISD::SETGE,  ISD::SETOGE,
705     };
706 
707     // Sets common operation actions on RVV floating-point vector types.
708     const auto SetCommonVFPActions = [&](MVT VT) {
709       setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
710       // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
711       // sizes are within one power-of-two of each other. Therefore conversions
712       // between vXf16 and vXf64 must be lowered as sequences which convert via
713       // vXf32.
714       setOperationAction(ISD::FP_ROUND, VT, Custom);
715       setOperationAction(ISD::FP_EXTEND, VT, Custom);
716       // Custom-lower insert/extract operations to simplify patterns.
717       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
718       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
719       // Expand various condition codes (explained above).
720       for (auto CC : VFPCCToExpand)
721         setCondCodeAction(CC, VT, Expand);
722 
723       setOperationAction(ISD::FMINNUM, VT, Legal);
724       setOperationAction(ISD::FMAXNUM, VT, Legal);
725 
726       setOperationAction(ISD::FTRUNC, VT, Custom);
727       setOperationAction(ISD::FCEIL, VT, Custom);
728       setOperationAction(ISD::FFLOOR, VT, Custom);
729       setOperationAction(ISD::FROUND, VT, Custom);
730 
731       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
732       setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
733       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
734       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
735 
736       setOperationAction(ISD::FCOPYSIGN, VT, Legal);
737 
738       setOperationAction(ISD::LOAD, VT, Custom);
739       setOperationAction(ISD::STORE, VT, Custom);
740 
741       setOperationAction(ISD::MLOAD, VT, Custom);
742       setOperationAction(ISD::MSTORE, VT, Custom);
743       setOperationAction(ISD::MGATHER, VT, Custom);
744       setOperationAction(ISD::MSCATTER, VT, Custom);
745 
746       setOperationAction(ISD::VP_LOAD, VT, Custom);
747       setOperationAction(ISD::VP_STORE, VT, Custom);
748       setOperationAction(ISD::VP_GATHER, VT, Custom);
749       setOperationAction(ISD::VP_SCATTER, VT, Custom);
750 
751       setOperationAction(ISD::SELECT, VT, Custom);
752       setOperationAction(ISD::SELECT_CC, VT, Expand);
753 
754       setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
755       setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
756       setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
757 
758       setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
759       setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
760 
761       for (unsigned VPOpc : FloatingPointVPOps)
762         setOperationAction(VPOpc, VT, Custom);
763     };
764 
765     // Sets common extload/truncstore actions on RVV floating-point vector
766     // types.
767     const auto SetCommonVFPExtLoadTruncStoreActions =
768         [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
769           for (auto SmallVT : SmallerVTs) {
770             setTruncStoreAction(VT, SmallVT, Expand);
771             setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
772           }
773         };
774 
775     if (Subtarget.hasVInstructionsF16())
776       for (MVT VT : F16VecVTs)
777         SetCommonVFPActions(VT);
778 
779     for (MVT VT : F32VecVTs) {
780       if (Subtarget.hasVInstructionsF32())
781         SetCommonVFPActions(VT);
782       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
783     }
784 
785     for (MVT VT : F64VecVTs) {
786       if (Subtarget.hasVInstructionsF64())
787         SetCommonVFPActions(VT);
788       SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
789       SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
790     }
791 
792     if (Subtarget.useRVVForFixedLengthVectors()) {
793       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
794         if (!useRVVForFixedLengthVectorVT(VT))
795           continue;
796 
797         // By default everything must be expanded.
798         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
799           setOperationAction(Op, VT, Expand);
800         for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
801           setTruncStoreAction(VT, OtherVT, Expand);
802           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
803           setLoadExtAction(ISD::SEXTLOAD, OtherVT, VT, Expand);
804           setLoadExtAction(ISD::ZEXTLOAD, OtherVT, VT, Expand);
805         }
806 
807         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
808         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
809         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
810 
811         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
812         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
813 
814         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
815         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
816 
817         setOperationAction(ISD::LOAD, VT, Custom);
818         setOperationAction(ISD::STORE, VT, Custom);
819 
820         setOperationAction(ISD::SETCC, VT, Custom);
821 
822         setOperationAction(ISD::SELECT, VT, Custom);
823 
824         setOperationAction(ISD::TRUNCATE, VT, Custom);
825 
826         setOperationAction(ISD::BITCAST, VT, Custom);
827 
828         setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
829         setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
830         setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
831 
832         setOperationAction(ISD::VP_REDUCE_AND, VT, Custom);
833         setOperationAction(ISD::VP_REDUCE_OR, VT, Custom);
834         setOperationAction(ISD::VP_REDUCE_XOR, VT, Custom);
835 
836         setOperationAction(ISD::SINT_TO_FP, VT, Custom);
837         setOperationAction(ISD::UINT_TO_FP, VT, Custom);
838         setOperationAction(ISD::FP_TO_SINT, VT, Custom);
839         setOperationAction(ISD::FP_TO_UINT, VT, Custom);
840 
841         // Operations below are different for between masks and other vectors.
842         if (VT.getVectorElementType() == MVT::i1) {
843           setOperationAction(ISD::VP_AND, VT, Custom);
844           setOperationAction(ISD::VP_OR, VT, Custom);
845           setOperationAction(ISD::VP_XOR, VT, Custom);
846           setOperationAction(ISD::AND, VT, Custom);
847           setOperationAction(ISD::OR, VT, Custom);
848           setOperationAction(ISD::XOR, VT, Custom);
849           continue;
850         }
851 
852         // Use SPLAT_VECTOR to prevent type legalization from destroying the
853         // splats when type legalizing i64 scalar on RV32.
854         // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
855         // improvements first.
856         if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
857           setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
858           setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
859         }
860 
861         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
862         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
863 
864         setOperationAction(ISD::MLOAD, VT, Custom);
865         setOperationAction(ISD::MSTORE, VT, Custom);
866         setOperationAction(ISD::MGATHER, VT, Custom);
867         setOperationAction(ISD::MSCATTER, VT, Custom);
868 
869         setOperationAction(ISD::VP_LOAD, VT, Custom);
870         setOperationAction(ISD::VP_STORE, VT, Custom);
871         setOperationAction(ISD::VP_GATHER, VT, Custom);
872         setOperationAction(ISD::VP_SCATTER, VT, Custom);
873 
874         setOperationAction(ISD::ADD, VT, Custom);
875         setOperationAction(ISD::MUL, VT, Custom);
876         setOperationAction(ISD::SUB, VT, Custom);
877         setOperationAction(ISD::AND, VT, Custom);
878         setOperationAction(ISD::OR, VT, Custom);
879         setOperationAction(ISD::XOR, VT, Custom);
880         setOperationAction(ISD::SDIV, VT, Custom);
881         setOperationAction(ISD::SREM, VT, Custom);
882         setOperationAction(ISD::UDIV, VT, Custom);
883         setOperationAction(ISD::UREM, VT, Custom);
884         setOperationAction(ISD::SHL, VT, Custom);
885         setOperationAction(ISD::SRA, VT, Custom);
886         setOperationAction(ISD::SRL, VT, Custom);
887 
888         setOperationAction(ISD::SMIN, VT, Custom);
889         setOperationAction(ISD::SMAX, VT, Custom);
890         setOperationAction(ISD::UMIN, VT, Custom);
891         setOperationAction(ISD::UMAX, VT, Custom);
892         setOperationAction(ISD::ABS,  VT, Custom);
893 
894         // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
895         if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) {
896           setOperationAction(ISD::MULHS, VT, Custom);
897           setOperationAction(ISD::MULHU, VT, Custom);
898         }
899 
900         setOperationAction(ISD::SADDSAT, VT, Custom);
901         setOperationAction(ISD::UADDSAT, VT, Custom);
902         setOperationAction(ISD::SSUBSAT, VT, Custom);
903         setOperationAction(ISD::USUBSAT, VT, Custom);
904 
905         setOperationAction(ISD::VSELECT, VT, Custom);
906         setOperationAction(ISD::SELECT_CC, VT, Expand);
907 
908         setOperationAction(ISD::ANY_EXTEND, VT, Custom);
909         setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
910         setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
911 
912         // Custom-lower reduction operations to set up the corresponding custom
913         // nodes' operands.
914         setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
915         setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
916         setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
917         setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
918         setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
919 
920         for (unsigned VPOpc : IntegerVPOps)
921           setOperationAction(VPOpc, VT, Custom);
922 
923         // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point
924         // type that can represent the value exactly.
925         if (VT.getVectorElementType() != MVT::i64) {
926           MVT FloatEltVT =
927               VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32;
928           EVT FloatVT =
929               MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
930           if (isTypeLegal(FloatVT)) {
931             setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Custom);
932             setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Custom);
933           }
934         }
935       }
936 
937       for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
938         if (!useRVVForFixedLengthVectorVT(VT))
939           continue;
940 
941         // By default everything must be expanded.
942         for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
943           setOperationAction(Op, VT, Expand);
944         for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
945           setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
946           setTruncStoreAction(VT, OtherVT, Expand);
947         }
948 
949         // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
950         setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
951         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
952 
953         setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
954         setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
955         setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
956         setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
957         setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
958 
959         setOperationAction(ISD::LOAD, VT, Custom);
960         setOperationAction(ISD::STORE, VT, Custom);
961         setOperationAction(ISD::MLOAD, VT, Custom);
962         setOperationAction(ISD::MSTORE, VT, Custom);
963         setOperationAction(ISD::MGATHER, VT, Custom);
964         setOperationAction(ISD::MSCATTER, VT, Custom);
965 
966         setOperationAction(ISD::VP_LOAD, VT, Custom);
967         setOperationAction(ISD::VP_STORE, VT, Custom);
968         setOperationAction(ISD::VP_GATHER, VT, Custom);
969         setOperationAction(ISD::VP_SCATTER, VT, Custom);
970 
971         setOperationAction(ISD::FADD, VT, Custom);
972         setOperationAction(ISD::FSUB, VT, Custom);
973         setOperationAction(ISD::FMUL, VT, Custom);
974         setOperationAction(ISD::FDIV, VT, Custom);
975         setOperationAction(ISD::FNEG, VT, Custom);
976         setOperationAction(ISD::FABS, VT, Custom);
977         setOperationAction(ISD::FCOPYSIGN, VT, Custom);
978         setOperationAction(ISD::FSQRT, VT, Custom);
979         setOperationAction(ISD::FMA, VT, Custom);
980         setOperationAction(ISD::FMINNUM, VT, Custom);
981         setOperationAction(ISD::FMAXNUM, VT, Custom);
982 
983         setOperationAction(ISD::FP_ROUND, VT, Custom);
984         setOperationAction(ISD::FP_EXTEND, VT, Custom);
985 
986         setOperationAction(ISD::FTRUNC, VT, Custom);
987         setOperationAction(ISD::FCEIL, VT, Custom);
988         setOperationAction(ISD::FFLOOR, VT, Custom);
989         setOperationAction(ISD::FROUND, VT, Custom);
990 
991         for (auto CC : VFPCCToExpand)
992           setCondCodeAction(CC, VT, Expand);
993 
994         setOperationAction(ISD::VSELECT, VT, Custom);
995         setOperationAction(ISD::SELECT, VT, Custom);
996         setOperationAction(ISD::SELECT_CC, VT, Expand);
997 
998         setOperationAction(ISD::BITCAST, VT, Custom);
999 
1000         setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
1001         setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
1002         setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
1003         setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
1004 
1005         for (unsigned VPOpc : FloatingPointVPOps)
1006           setOperationAction(VPOpc, VT, Custom);
1007       }
1008 
1009       // Custom-legalize bitcasts from fixed-length vectors to scalar types.
1010       setOperationAction(ISD::BITCAST, MVT::i8, Custom);
1011       setOperationAction(ISD::BITCAST, MVT::i16, Custom);
1012       setOperationAction(ISD::BITCAST, MVT::i32, Custom);
1013       setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1014       if (Subtarget.hasStdExtZfh())
1015         setOperationAction(ISD::BITCAST, MVT::f16, Custom);
1016       if (Subtarget.hasStdExtF())
1017         setOperationAction(ISD::BITCAST, MVT::f32, Custom);
1018       if (Subtarget.hasStdExtD())
1019         setOperationAction(ISD::BITCAST, MVT::f64, Custom);
1020     }
1021   }
1022 
1023   // Function alignments.
1024   const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4);
1025   setMinFunctionAlignment(FunctionAlignment);
1026   setPrefFunctionAlignment(FunctionAlignment);
1027 
1028   setMinimumJumpTableEntries(5);
1029 
1030   // Jumps are expensive, compared to logic
1031   setJumpIsExpensive();
1032 
1033   setTargetDAGCombine(ISD::ADD);
1034   setTargetDAGCombine(ISD::SUB);
1035   setTargetDAGCombine(ISD::AND);
1036   setTargetDAGCombine(ISD::OR);
1037   setTargetDAGCombine(ISD::XOR);
1038   if (Subtarget.hasStdExtZbp()) {
1039     setTargetDAGCombine(ISD::ROTL);
1040     setTargetDAGCombine(ISD::ROTR);
1041   }
1042   setTargetDAGCombine(ISD::ANY_EXTEND);
1043   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1044   if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb())
1045     setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1046   if (Subtarget.hasStdExtF()) {
1047     setTargetDAGCombine(ISD::ZERO_EXTEND);
1048     setTargetDAGCombine(ISD::FP_TO_SINT);
1049     setTargetDAGCombine(ISD::FP_TO_UINT);
1050     setTargetDAGCombine(ISD::FP_TO_SINT_SAT);
1051     setTargetDAGCombine(ISD::FP_TO_UINT_SAT);
1052   }
1053   if (Subtarget.hasVInstructions()) {
1054     setTargetDAGCombine(ISD::FCOPYSIGN);
1055     setTargetDAGCombine(ISD::MGATHER);
1056     setTargetDAGCombine(ISD::MSCATTER);
1057     setTargetDAGCombine(ISD::VP_GATHER);
1058     setTargetDAGCombine(ISD::VP_SCATTER);
1059     setTargetDAGCombine(ISD::SRA);
1060     setTargetDAGCombine(ISD::SRL);
1061     setTargetDAGCombine(ISD::SHL);
1062     setTargetDAGCombine(ISD::STORE);
1063     setTargetDAGCombine(ISD::SPLAT_VECTOR);
1064   }
1065 
1066   setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
1067   setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
1068 }
1069 
1070 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
1071                                             LLVMContext &Context,
1072                                             EVT VT) const {
1073   if (!VT.isVector())
1074     return getPointerTy(DL);
1075   if (Subtarget.hasVInstructions() &&
1076       (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
1077     return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
1078   return VT.changeVectorElementTypeToInteger();
1079 }
1080 
1081 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
1082   return Subtarget.getXLenVT();
1083 }
1084 
1085 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1086                                              const CallInst &I,
1087                                              MachineFunction &MF,
1088                                              unsigned Intrinsic) const {
1089   auto &DL = I.getModule()->getDataLayout();
1090   switch (Intrinsic) {
1091   default:
1092     return false;
1093   case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
1094   case Intrinsic::riscv_masked_atomicrmw_add_i32:
1095   case Intrinsic::riscv_masked_atomicrmw_sub_i32:
1096   case Intrinsic::riscv_masked_atomicrmw_nand_i32:
1097   case Intrinsic::riscv_masked_atomicrmw_max_i32:
1098   case Intrinsic::riscv_masked_atomicrmw_min_i32:
1099   case Intrinsic::riscv_masked_atomicrmw_umax_i32:
1100   case Intrinsic::riscv_masked_atomicrmw_umin_i32:
1101   case Intrinsic::riscv_masked_cmpxchg_i32:
1102     Info.opc = ISD::INTRINSIC_W_CHAIN;
1103     Info.memVT = MVT::i32;
1104     Info.ptrVal = I.getArgOperand(0);
1105     Info.offset = 0;
1106     Info.align = Align(4);
1107     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
1108                  MachineMemOperand::MOVolatile;
1109     return true;
1110   case Intrinsic::riscv_masked_strided_load:
1111     Info.opc = ISD::INTRINSIC_W_CHAIN;
1112     Info.ptrVal = I.getArgOperand(1);
1113     Info.memVT = getValueType(DL, I.getType()->getScalarType());
1114     Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
1115     Info.size = MemoryLocation::UnknownSize;
1116     Info.flags |= MachineMemOperand::MOLoad;
1117     return true;
1118   case Intrinsic::riscv_masked_strided_store:
1119     Info.opc = ISD::INTRINSIC_VOID;
1120     Info.ptrVal = I.getArgOperand(1);
1121     Info.memVT =
1122         getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
1123     Info.align = Align(
1124         DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
1125         8);
1126     Info.size = MemoryLocation::UnknownSize;
1127     Info.flags |= MachineMemOperand::MOStore;
1128     return true;
1129   }
1130 }
1131 
1132 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
1133                                                 const AddrMode &AM, Type *Ty,
1134                                                 unsigned AS,
1135                                                 Instruction *I) const {
1136   // No global is ever allowed as a base.
1137   if (AM.BaseGV)
1138     return false;
1139 
1140   // Require a 12-bit signed offset.
1141   if (!isInt<12>(AM.BaseOffs))
1142     return false;
1143 
1144   switch (AM.Scale) {
1145   case 0: // "r+i" or just "i", depending on HasBaseReg.
1146     break;
1147   case 1:
1148     if (!AM.HasBaseReg) // allow "r+i".
1149       break;
1150     return false; // disallow "r+r" or "r+r+i".
1151   default:
1152     return false;
1153   }
1154 
1155   return true;
1156 }
1157 
1158 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
1159   return isInt<12>(Imm);
1160 }
1161 
1162 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
1163   return isInt<12>(Imm);
1164 }
1165 
1166 // On RV32, 64-bit integers are split into their high and low parts and held
1167 // in two different registers, so the trunc is free since the low register can
1168 // just be used.
1169 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
1170   if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
1171     return false;
1172   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
1173   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
1174   return (SrcBits == 64 && DestBits == 32);
1175 }
1176 
1177 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
1178   if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() ||
1179       !SrcVT.isInteger() || !DstVT.isInteger())
1180     return false;
1181   unsigned SrcBits = SrcVT.getSizeInBits();
1182   unsigned DestBits = DstVT.getSizeInBits();
1183   return (SrcBits == 64 && DestBits == 32);
1184 }
1185 
1186 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
1187   // Zexts are free if they can be combined with a load.
1188   // Don't advertise i32->i64 zextload as being free for RV64. It interacts
1189   // poorly with type legalization of compares preferring sext.
1190   if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
1191     EVT MemVT = LD->getMemoryVT();
1192     if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
1193         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
1194          LD->getExtensionType() == ISD::ZEXTLOAD))
1195       return true;
1196   }
1197 
1198   return TargetLowering::isZExtFree(Val, VT2);
1199 }
1200 
1201 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
1202   return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
1203 }
1204 
1205 bool RISCVTargetLowering::isCheapToSpeculateCttz() const {
1206   return Subtarget.hasStdExtZbb();
1207 }
1208 
1209 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const {
1210   return Subtarget.hasStdExtZbb();
1211 }
1212 
1213 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
1214   EVT VT = Y.getValueType();
1215 
1216   // FIXME: Support vectors once we have tests.
1217   if (VT.isVector())
1218     return false;
1219 
1220   return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() ||
1221           Subtarget.hasStdExtZbkb()) &&
1222          !isa<ConstantSDNode>(Y);
1223 }
1224 
1225 /// Check if sinking \p I's operands to I's basic block is profitable, because
1226 /// the operands can be folded into a target instruction, e.g.
1227 /// splats of scalars can fold into vector instructions.
1228 bool RISCVTargetLowering::shouldSinkOperands(
1229     Instruction *I, SmallVectorImpl<Use *> &Ops) const {
1230   using namespace llvm::PatternMatch;
1231 
1232   if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
1233     return false;
1234 
1235   auto IsSinker = [&](Instruction *I, int Operand) {
1236     switch (I->getOpcode()) {
1237     case Instruction::Add:
1238     case Instruction::Sub:
1239     case Instruction::Mul:
1240     case Instruction::And:
1241     case Instruction::Or:
1242     case Instruction::Xor:
1243     case Instruction::FAdd:
1244     case Instruction::FSub:
1245     case Instruction::FMul:
1246     case Instruction::FDiv:
1247     case Instruction::ICmp:
1248     case Instruction::FCmp:
1249       return true;
1250     case Instruction::Shl:
1251     case Instruction::LShr:
1252     case Instruction::AShr:
1253     case Instruction::UDiv:
1254     case Instruction::SDiv:
1255     case Instruction::URem:
1256     case Instruction::SRem:
1257       return Operand == 1;
1258     case Instruction::Call:
1259       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
1260         switch (II->getIntrinsicID()) {
1261         case Intrinsic::fma:
1262         case Intrinsic::vp_fma:
1263           return Operand == 0 || Operand == 1;
1264         // FIXME: Our patterns can only match vx/vf instructions when the splat
1265         // it on the RHS, because TableGen doesn't recognize our VP operations
1266         // as commutative.
1267         case Intrinsic::vp_add:
1268         case Intrinsic::vp_mul:
1269         case Intrinsic::vp_and:
1270         case Intrinsic::vp_or:
1271         case Intrinsic::vp_xor:
1272         case Intrinsic::vp_fadd:
1273         case Intrinsic::vp_fmul:
1274         case Intrinsic::vp_shl:
1275         case Intrinsic::vp_lshr:
1276         case Intrinsic::vp_ashr:
1277         case Intrinsic::vp_udiv:
1278         case Intrinsic::vp_sdiv:
1279         case Intrinsic::vp_urem:
1280         case Intrinsic::vp_srem:
1281           return Operand == 1;
1282         // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have
1283         // explicit patterns for both LHS and RHS (as 'vr' versions).
1284         case Intrinsic::vp_sub:
1285         case Intrinsic::vp_fsub:
1286         case Intrinsic::vp_fdiv:
1287           return Operand == 0 || Operand == 1;
1288         default:
1289           return false;
1290         }
1291       }
1292       return false;
1293     default:
1294       return false;
1295     }
1296   };
1297 
1298   for (auto OpIdx : enumerate(I->operands())) {
1299     if (!IsSinker(I, OpIdx.index()))
1300       continue;
1301 
1302     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
1303     // Make sure we are not already sinking this operand
1304     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
1305       continue;
1306 
1307     // We are looking for a splat that can be sunk.
1308     if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
1309                              m_Undef(), m_ZeroMask())))
1310       continue;
1311 
1312     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
1313     // and vector registers
1314     for (Use &U : Op->uses()) {
1315       Instruction *Insn = cast<Instruction>(U.getUser());
1316       if (!IsSinker(Insn, U.getOperandNo()))
1317         return false;
1318     }
1319 
1320     Ops.push_back(&Op->getOperandUse(0));
1321     Ops.push_back(&OpIdx.value());
1322   }
1323   return true;
1324 }
1325 
1326 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
1327                                        bool ForCodeSize) const {
1328   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1329   if (VT == MVT::f16 && !Subtarget.hasStdExtZfh())
1330     return false;
1331   if (VT == MVT::f32 && !Subtarget.hasStdExtF())
1332     return false;
1333   if (VT == MVT::f64 && !Subtarget.hasStdExtD())
1334     return false;
1335   return Imm.isZero();
1336 }
1337 
1338 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
1339   return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) ||
1340          (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
1341          (VT == MVT::f64 && Subtarget.hasStdExtD());
1342 }
1343 
1344 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
1345                                                       CallingConv::ID CC,
1346                                                       EVT VT) const {
1347   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1348   // We might still end up using a GPR but that will be decided based on ABI.
1349   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1350   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1351     return MVT::f32;
1352 
1353   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
1354 }
1355 
1356 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
1357                                                            CallingConv::ID CC,
1358                                                            EVT VT) const {
1359   // Use f32 to pass f16 if it is legal and Zfh is not enabled.
1360   // We might still end up using a GPR but that will be decided based on ABI.
1361   // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin.
1362   if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh())
1363     return 1;
1364 
1365   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
1366 }
1367 
1368 // Changes the condition code and swaps operands if necessary, so the SetCC
1369 // operation matches one of the comparisons supported directly by branches
1370 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
1371 // with 1/-1.
1372 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
1373                                     ISD::CondCode &CC, SelectionDAG &DAG) {
1374   // Convert X > -1 to X >= 0.
1375   if (CC == ISD::SETGT && isAllOnesConstant(RHS)) {
1376     RHS = DAG.getConstant(0, DL, RHS.getValueType());
1377     CC = ISD::SETGE;
1378     return;
1379   }
1380   // Convert X < 1 to 0 >= X.
1381   if (CC == ISD::SETLT && isOneConstant(RHS)) {
1382     RHS = LHS;
1383     LHS = DAG.getConstant(0, DL, RHS.getValueType());
1384     CC = ISD::SETGE;
1385     return;
1386   }
1387 
1388   switch (CC) {
1389   default:
1390     break;
1391   case ISD::SETGT:
1392   case ISD::SETLE:
1393   case ISD::SETUGT:
1394   case ISD::SETULE:
1395     CC = ISD::getSetCCSwappedOperands(CC);
1396     std::swap(LHS, RHS);
1397     break;
1398   }
1399 }
1400 
1401 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
1402   assert(VT.isScalableVector() && "Expecting a scalable vector type");
1403   unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
1404   if (VT.getVectorElementType() == MVT::i1)
1405     KnownSize *= 8;
1406 
1407   switch (KnownSize) {
1408   default:
1409     llvm_unreachable("Invalid LMUL.");
1410   case 8:
1411     return RISCVII::VLMUL::LMUL_F8;
1412   case 16:
1413     return RISCVII::VLMUL::LMUL_F4;
1414   case 32:
1415     return RISCVII::VLMUL::LMUL_F2;
1416   case 64:
1417     return RISCVII::VLMUL::LMUL_1;
1418   case 128:
1419     return RISCVII::VLMUL::LMUL_2;
1420   case 256:
1421     return RISCVII::VLMUL::LMUL_4;
1422   case 512:
1423     return RISCVII::VLMUL::LMUL_8;
1424   }
1425 }
1426 
1427 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
1428   switch (LMul) {
1429   default:
1430     llvm_unreachable("Invalid LMUL.");
1431   case RISCVII::VLMUL::LMUL_F8:
1432   case RISCVII::VLMUL::LMUL_F4:
1433   case RISCVII::VLMUL::LMUL_F2:
1434   case RISCVII::VLMUL::LMUL_1:
1435     return RISCV::VRRegClassID;
1436   case RISCVII::VLMUL::LMUL_2:
1437     return RISCV::VRM2RegClassID;
1438   case RISCVII::VLMUL::LMUL_4:
1439     return RISCV::VRM4RegClassID;
1440   case RISCVII::VLMUL::LMUL_8:
1441     return RISCV::VRM8RegClassID;
1442   }
1443 }
1444 
1445 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
1446   RISCVII::VLMUL LMUL = getLMUL(VT);
1447   if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
1448       LMUL == RISCVII::VLMUL::LMUL_F4 ||
1449       LMUL == RISCVII::VLMUL::LMUL_F2 ||
1450       LMUL == RISCVII::VLMUL::LMUL_1) {
1451     static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
1452                   "Unexpected subreg numbering");
1453     return RISCV::sub_vrm1_0 + Index;
1454   }
1455   if (LMUL == RISCVII::VLMUL::LMUL_2) {
1456     static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
1457                   "Unexpected subreg numbering");
1458     return RISCV::sub_vrm2_0 + Index;
1459   }
1460   if (LMUL == RISCVII::VLMUL::LMUL_4) {
1461     static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
1462                   "Unexpected subreg numbering");
1463     return RISCV::sub_vrm4_0 + Index;
1464   }
1465   llvm_unreachable("Invalid vector type.");
1466 }
1467 
1468 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
1469   if (VT.getVectorElementType() == MVT::i1)
1470     return RISCV::VRRegClassID;
1471   return getRegClassIDForLMUL(getLMUL(VT));
1472 }
1473 
1474 // Attempt to decompose a subvector insert/extract between VecVT and
1475 // SubVecVT via subregister indices. Returns the subregister index that
1476 // can perform the subvector insert/extract with the given element index, as
1477 // well as the index corresponding to any leftover subvectors that must be
1478 // further inserted/extracted within the register class for SubVecVT.
1479 std::pair<unsigned, unsigned>
1480 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
1481     MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
1482     const RISCVRegisterInfo *TRI) {
1483   static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
1484                  RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
1485                  RISCV::VRM2RegClassID > RISCV::VRRegClassID),
1486                 "Register classes not ordered");
1487   unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
1488   unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
1489   // Try to compose a subregister index that takes us from the incoming
1490   // LMUL>1 register class down to the outgoing one. At each step we half
1491   // the LMUL:
1492   //   nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
1493   // Note that this is not guaranteed to find a subregister index, such as
1494   // when we are extracting from one VR type to another.
1495   unsigned SubRegIdx = RISCV::NoSubRegister;
1496   for (const unsigned RCID :
1497        {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
1498     if (VecRegClassID > RCID && SubRegClassID <= RCID) {
1499       VecVT = VecVT.getHalfNumVectorElementsVT();
1500       bool IsHi =
1501           InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
1502       SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
1503                                             getSubregIndexByMVT(VecVT, IsHi));
1504       if (IsHi)
1505         InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
1506     }
1507   return {SubRegIdx, InsertExtractIdx};
1508 }
1509 
1510 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
1511 // stores for those types.
1512 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
1513   return !Subtarget.useRVVForFixedLengthVectors() ||
1514          (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
1515 }
1516 
1517 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
1518   if (ScalarTy->isPointerTy())
1519     return true;
1520 
1521   if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
1522       ScalarTy->isIntegerTy(32))
1523     return true;
1524 
1525   if (ScalarTy->isIntegerTy(64))
1526     return Subtarget.hasVInstructionsI64();
1527 
1528   if (ScalarTy->isHalfTy())
1529     return Subtarget.hasVInstructionsF16();
1530   if (ScalarTy->isFloatTy())
1531     return Subtarget.hasVInstructionsF32();
1532   if (ScalarTy->isDoubleTy())
1533     return Subtarget.hasVInstructionsF64();
1534 
1535   return false;
1536 }
1537 
1538 static SDValue getVLOperand(SDValue Op) {
1539   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1540           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
1541          "Unexpected opcode");
1542   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
1543   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
1544   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
1545       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
1546   if (!II)
1547     return SDValue();
1548   return Op.getOperand(II->VLOperand + 1 + HasChain);
1549 }
1550 
1551 static bool useRVVForFixedLengthVectorVT(MVT VT,
1552                                          const RISCVSubtarget &Subtarget) {
1553   assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
1554   if (!Subtarget.useRVVForFixedLengthVectors())
1555     return false;
1556 
1557   // We only support a set of vector types with a consistent maximum fixed size
1558   // across all supported vector element types to avoid legalization issues.
1559   // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
1560   // fixed-length vector type we support is 1024 bytes.
1561   if (VT.getFixedSizeInBits() > 1024 * 8)
1562     return false;
1563 
1564   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1565 
1566   MVT EltVT = VT.getVectorElementType();
1567 
1568   // Don't use RVV for vectors we cannot scalarize if required.
1569   switch (EltVT.SimpleTy) {
1570   // i1 is supported but has different rules.
1571   default:
1572     return false;
1573   case MVT::i1:
1574     // Masks can only use a single register.
1575     if (VT.getVectorNumElements() > MinVLen)
1576       return false;
1577     MinVLen /= 8;
1578     break;
1579   case MVT::i8:
1580   case MVT::i16:
1581   case MVT::i32:
1582     break;
1583   case MVT::i64:
1584     if (!Subtarget.hasVInstructionsI64())
1585       return false;
1586     break;
1587   case MVT::f16:
1588     if (!Subtarget.hasVInstructionsF16())
1589       return false;
1590     break;
1591   case MVT::f32:
1592     if (!Subtarget.hasVInstructionsF32())
1593       return false;
1594     break;
1595   case MVT::f64:
1596     if (!Subtarget.hasVInstructionsF64())
1597       return false;
1598     break;
1599   }
1600 
1601   // Reject elements larger than ELEN.
1602   if (EltVT.getSizeInBits() > Subtarget.getMaxELENForFixedLengthVectors())
1603     return false;
1604 
1605   unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
1606   // Don't use RVV for types that don't fit.
1607   if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
1608     return false;
1609 
1610   // TODO: Perhaps an artificial restriction, but worth having whilst getting
1611   // the base fixed length RVV support in place.
1612   if (!VT.isPow2VectorType())
1613     return false;
1614 
1615   return true;
1616 }
1617 
1618 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
1619   return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
1620 }
1621 
1622 // Return the largest legal scalable vector type that matches VT's element type.
1623 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
1624                                             const RISCVSubtarget &Subtarget) {
1625   // This may be called before legal types are setup.
1626   assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
1627           useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
1628          "Expected legal fixed length vector!");
1629 
1630   unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits();
1631   unsigned MaxELen = Subtarget.getMaxELENForFixedLengthVectors();
1632 
1633   MVT EltVT = VT.getVectorElementType();
1634   switch (EltVT.SimpleTy) {
1635   default:
1636     llvm_unreachable("unexpected element type for RVV container");
1637   case MVT::i1:
1638   case MVT::i8:
1639   case MVT::i16:
1640   case MVT::i32:
1641   case MVT::i64:
1642   case MVT::f16:
1643   case MVT::f32:
1644   case MVT::f64: {
1645     // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
1646     // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
1647     // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
1648     unsigned NumElts =
1649         (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
1650     NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
1651     assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
1652     return MVT::getScalableVectorVT(EltVT, NumElts);
1653   }
1654   }
1655 }
1656 
1657 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
1658                                             const RISCVSubtarget &Subtarget) {
1659   return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
1660                                           Subtarget);
1661 }
1662 
1663 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
1664   return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
1665 }
1666 
1667 // Grow V to consume an entire RVV register.
1668 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1669                                        const RISCVSubtarget &Subtarget) {
1670   assert(VT.isScalableVector() &&
1671          "Expected to convert into a scalable vector!");
1672   assert(V.getValueType().isFixedLengthVector() &&
1673          "Expected a fixed length vector operand!");
1674   SDLoc DL(V);
1675   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1676   return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
1677 }
1678 
1679 // Shrink V so it's just big enough to maintain a VT's worth of data.
1680 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
1681                                          const RISCVSubtarget &Subtarget) {
1682   assert(VT.isFixedLengthVector() &&
1683          "Expected to convert into a fixed length vector!");
1684   assert(V.getValueType().isScalableVector() &&
1685          "Expected a scalable vector operand!");
1686   SDLoc DL(V);
1687   SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
1688   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
1689 }
1690 
1691 // Gets the two common "VL" operands: an all-ones mask and the vector length.
1692 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
1693 // the vector type that it is contained in.
1694 static std::pair<SDValue, SDValue>
1695 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
1696                 const RISCVSubtarget &Subtarget) {
1697   assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
1698   MVT XLenVT = Subtarget.getXLenVT();
1699   SDValue VL = VecVT.isFixedLengthVector()
1700                    ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT)
1701                    : DAG.getRegister(RISCV::X0, XLenVT);
1702   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
1703   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
1704   return {Mask, VL};
1705 }
1706 
1707 // As above but assuming the given type is a scalable vector type.
1708 static std::pair<SDValue, SDValue>
1709 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
1710                         const RISCVSubtarget &Subtarget) {
1711   assert(VecVT.isScalableVector() && "Expecting a scalable vector");
1712   return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
1713 }
1714 
1715 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
1716 // of either is (currently) supported. This can get us into an infinite loop
1717 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
1718 // as a ..., etc.
1719 // Until either (or both) of these can reliably lower any node, reporting that
1720 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
1721 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
1722 // which is not desirable.
1723 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
1724     EVT VT, unsigned DefinedValues) const {
1725   return false;
1726 }
1727 
1728 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
1729                                   const RISCVSubtarget &Subtarget) {
1730   // RISCV FP-to-int conversions saturate to the destination register size, but
1731   // don't produce 0 for nan. We can use a conversion instruction and fix the
1732   // nan case with a compare and a select.
1733   SDValue Src = Op.getOperand(0);
1734 
1735   EVT DstVT = Op.getValueType();
1736   EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1737 
1738   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
1739   unsigned Opc;
1740   if (SatVT == DstVT)
1741     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
1742   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
1743     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
1744   else
1745     return SDValue();
1746   // FIXME: Support other SatVTs by clamping before or after the conversion.
1747 
1748   SDLoc DL(Op);
1749   SDValue FpToInt = DAG.getNode(
1750       Opc, DL, DstVT, Src,
1751       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
1752 
1753   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
1754   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
1755 }
1756 
1757 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain
1758 // and back. Taking care to avoid converting values that are nan or already
1759 // correct.
1760 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't
1761 // have FRM dependencies modeled yet.
1762 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) {
1763   MVT VT = Op.getSimpleValueType();
1764   assert(VT.isVector() && "Unexpected type");
1765 
1766   SDLoc DL(Op);
1767 
1768   // Freeze the source since we are increasing the number of uses.
1769   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1770 
1771   // Truncate to integer and convert back to FP.
1772   MVT IntVT = VT.changeVectorElementTypeToInteger();
1773   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src);
1774   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1775 
1776   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1777 
1778   if (Op.getOpcode() == ISD::FCEIL) {
1779     // If the truncated value is the greater than or equal to the original
1780     // value, we've computed the ceil. Otherwise, we went the wrong way and
1781     // need to increase by 1.
1782     // FIXME: This should use a masked operation. Handle here or in isel?
1783     SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated,
1784                                  DAG.getConstantFP(1.0, DL, VT));
1785     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT);
1786     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1787   } else if (Op.getOpcode() == ISD::FFLOOR) {
1788     // If the truncated value is the less than or equal to the original value,
1789     // we've computed the floor. Otherwise, we went the wrong way and need to
1790     // decrease by 1.
1791     // FIXME: This should use a masked operation. Handle here or in isel?
1792     SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated,
1793                                  DAG.getConstantFP(1.0, DL, VT));
1794     SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT);
1795     Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated);
1796   }
1797 
1798   // Restore the original sign so that -0.0 is preserved.
1799   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1800 
1801   // Determine the largest integer that can be represented exactly. This and
1802   // values larger than it don't have any fractional bits so don't need to
1803   // be converted.
1804   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1805   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1806   APFloat MaxVal = APFloat(FltSem);
1807   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1808                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1809   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1810 
1811   // If abs(Src) was larger than MaxVal or nan, keep it.
1812   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1813   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1814   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1815 }
1816 
1817 // ISD::FROUND is defined to round to nearest with ties rounding away from 0.
1818 // This mode isn't supported in vector hardware on RISCV. But as long as we
1819 // aren't compiling with trapping math, we can emulate this with
1820 // floor(X + copysign(nextafter(0.5, 0.0), X)).
1821 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM
1822 // dependencies modeled yet.
1823 // FIXME: Use masked operations to avoid final merge.
1824 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) {
1825   MVT VT = Op.getSimpleValueType();
1826   assert(VT.isVector() && "Unexpected type");
1827 
1828   SDLoc DL(Op);
1829 
1830   // Freeze the source since we are increasing the number of uses.
1831   SDValue Src = DAG.getFreeze(Op.getOperand(0));
1832 
1833   // We do the conversion on the absolute value and fix the sign at the end.
1834   SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src);
1835 
1836   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
1837   bool Ignored;
1838   APFloat Point5Pred = APFloat(0.5f);
1839   Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored);
1840   Point5Pred.next(/*nextDown*/ true);
1841 
1842   // Add the adjustment.
1843   SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs,
1844                                DAG.getConstantFP(Point5Pred, DL, VT));
1845 
1846   // Truncate to integer and convert back to fp.
1847   MVT IntVT = VT.changeVectorElementTypeToInteger();
1848   SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust);
1849   Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated);
1850 
1851   // Restore the original sign.
1852   Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src);
1853 
1854   // Determine the largest integer that can be represented exactly. This and
1855   // values larger than it don't have any fractional bits so don't need to
1856   // be converted.
1857   unsigned Precision = APFloat::semanticsPrecision(FltSem);
1858   APFloat MaxVal = APFloat(FltSem);
1859   MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
1860                           /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
1861   SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
1862 
1863   // If abs(Src) was larger than MaxVal or nan, keep it.
1864   MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1865   SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT);
1866   return DAG.getSelect(DL, VT, Setcc, Truncated, Src);
1867 }
1868 
1869 static SDValue lowerSPLAT_VECTOR(SDValue Op, SelectionDAG &DAG,
1870                                  const RISCVSubtarget &Subtarget) {
1871   MVT VT = Op.getSimpleValueType();
1872   assert(VT.isFixedLengthVector() && "Unexpected vector!");
1873 
1874   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1875 
1876   SDLoc DL(Op);
1877   SDValue Mask, VL;
1878   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
1879 
1880   unsigned Opc =
1881       VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
1882   SDValue Splat = DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
1883                               Op.getOperand(0), VL);
1884   return convertFromScalableVector(VT, Splat, DAG, Subtarget);
1885 }
1886 
1887 struct VIDSequence {
1888   int64_t StepNumerator;
1889   unsigned StepDenominator;
1890   int64_t Addend;
1891 };
1892 
1893 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
1894 // to the (non-zero) step S and start value X. This can be then lowered as the
1895 // RVV sequence (VID * S) + X, for example.
1896 // The step S is represented as an integer numerator divided by a positive
1897 // denominator. Note that the implementation currently only identifies
1898 // sequences in which either the numerator is +/- 1 or the denominator is 1. It
1899 // cannot detect 2/3, for example.
1900 // Note that this method will also match potentially unappealing index
1901 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
1902 // determine whether this is worth generating code for.
1903 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
1904   unsigned NumElts = Op.getNumOperands();
1905   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
1906   if (!Op.getValueType().isInteger())
1907     return None;
1908 
1909   Optional<unsigned> SeqStepDenom;
1910   Optional<int64_t> SeqStepNum, SeqAddend;
1911   Optional<std::pair<uint64_t, unsigned>> PrevElt;
1912   unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
1913   for (unsigned Idx = 0; Idx < NumElts; Idx++) {
1914     // Assume undef elements match the sequence; we just have to be careful
1915     // when interpolating across them.
1916     if (Op.getOperand(Idx).isUndef())
1917       continue;
1918     // The BUILD_VECTOR must be all constants.
1919     if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
1920       return None;
1921 
1922     uint64_t Val = Op.getConstantOperandVal(Idx) &
1923                    maskTrailingOnes<uint64_t>(EltSizeInBits);
1924 
1925     if (PrevElt) {
1926       // Calculate the step since the last non-undef element, and ensure
1927       // it's consistent across the entire sequence.
1928       unsigned IdxDiff = Idx - PrevElt->second;
1929       int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
1930 
1931       // A zero-value value difference means that we're somewhere in the middle
1932       // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
1933       // step change before evaluating the sequence.
1934       if (ValDiff != 0) {
1935         int64_t Remainder = ValDiff % IdxDiff;
1936         // Normalize the step if it's greater than 1.
1937         if (Remainder != ValDiff) {
1938           // The difference must cleanly divide the element span.
1939           if (Remainder != 0)
1940             return None;
1941           ValDiff /= IdxDiff;
1942           IdxDiff = 1;
1943         }
1944 
1945         if (!SeqStepNum)
1946           SeqStepNum = ValDiff;
1947         else if (ValDiff != SeqStepNum)
1948           return None;
1949 
1950         if (!SeqStepDenom)
1951           SeqStepDenom = IdxDiff;
1952         else if (IdxDiff != *SeqStepDenom)
1953           return None;
1954       }
1955     }
1956 
1957     // Record and/or check any addend.
1958     if (SeqStepNum && SeqStepDenom) {
1959       uint64_t ExpectedVal =
1960           (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
1961       int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
1962       if (!SeqAddend)
1963         SeqAddend = Addend;
1964       else if (SeqAddend != Addend)
1965         return None;
1966     }
1967 
1968     // Record this non-undef element for later.
1969     if (!PrevElt || PrevElt->first != Val)
1970       PrevElt = std::make_pair(Val, Idx);
1971   }
1972   // We need to have logged both a step and an addend for this to count as
1973   // a legal index sequence.
1974   if (!SeqStepNum || !SeqStepDenom || !SeqAddend)
1975     return None;
1976 
1977   return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
1978 }
1979 
1980 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
1981 // and lower it as a VRGATHER_VX_VL from the source vector.
1982 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
1983                                   SelectionDAG &DAG,
1984                                   const RISCVSubtarget &Subtarget) {
1985   if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
1986     return SDValue();
1987   SDValue Vec = SplatVal.getOperand(0);
1988   // Only perform this optimization on vectors of the same size for simplicity.
1989   if (Vec.getValueType() != VT)
1990     return SDValue();
1991   SDValue Idx = SplatVal.getOperand(1);
1992   // The index must be a legal type.
1993   if (Idx.getValueType() != Subtarget.getXLenVT())
1994     return SDValue();
1995 
1996   MVT ContainerVT = VT;
1997   if (VT.isFixedLengthVector()) {
1998     ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
1999     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
2000   }
2001 
2002   SDValue Mask, VL;
2003   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2004 
2005   SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
2006                                Idx, Mask, VL);
2007 
2008   if (!VT.isFixedLengthVector())
2009     return Gather;
2010 
2011   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2012 }
2013 
2014 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
2015                                  const RISCVSubtarget &Subtarget) {
2016   MVT VT = Op.getSimpleValueType();
2017   assert(VT.isFixedLengthVector() && "Unexpected vector!");
2018 
2019   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2020 
2021   SDLoc DL(Op);
2022   SDValue Mask, VL;
2023   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2024 
2025   MVT XLenVT = Subtarget.getXLenVT();
2026   unsigned NumElts = Op.getNumOperands();
2027 
2028   if (VT.getVectorElementType() == MVT::i1) {
2029     if (ISD::isBuildVectorAllZeros(Op.getNode())) {
2030       SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
2031       return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
2032     }
2033 
2034     if (ISD::isBuildVectorAllOnes(Op.getNode())) {
2035       SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
2036       return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
2037     }
2038 
2039     // Lower constant mask BUILD_VECTORs via an integer vector type, in
2040     // scalar integer chunks whose bit-width depends on the number of mask
2041     // bits and XLEN.
2042     // First, determine the most appropriate scalar integer type to use. This
2043     // is at most XLenVT, but may be shrunk to a smaller vector element type
2044     // according to the size of the final vector - use i8 chunks rather than
2045     // XLenVT if we're producing a v8i1. This results in more consistent
2046     // codegen across RV32 and RV64.
2047     unsigned NumViaIntegerBits =
2048         std::min(std::max(NumElts, 8u), Subtarget.getXLen());
2049     NumViaIntegerBits = std::min(NumViaIntegerBits,
2050                                  Subtarget.getMaxELENForFixedLengthVectors());
2051     if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
2052       // If we have to use more than one INSERT_VECTOR_ELT then this
2053       // optimization is likely to increase code size; avoid peforming it in
2054       // such a case. We can use a load from a constant pool in this case.
2055       if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
2056         return SDValue();
2057       // Now we can create our integer vector type. Note that it may be larger
2058       // than the resulting mask type: v4i1 would use v1i8 as its integer type.
2059       MVT IntegerViaVecVT =
2060           MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
2061                            divideCeil(NumElts, NumViaIntegerBits));
2062 
2063       uint64_t Bits = 0;
2064       unsigned BitPos = 0, IntegerEltIdx = 0;
2065       SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
2066 
2067       for (unsigned I = 0; I < NumElts; I++, BitPos++) {
2068         // Once we accumulate enough bits to fill our scalar type, insert into
2069         // our vector and clear our accumulated data.
2070         if (I != 0 && I % NumViaIntegerBits == 0) {
2071           if (NumViaIntegerBits <= 32)
2072             Bits = SignExtend64(Bits, 32);
2073           SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2074           Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
2075                             Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2076           Bits = 0;
2077           BitPos = 0;
2078           IntegerEltIdx++;
2079         }
2080         SDValue V = Op.getOperand(I);
2081         bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
2082         Bits |= ((uint64_t)BitValue << BitPos);
2083       }
2084 
2085       // Insert the (remaining) scalar value into position in our integer
2086       // vector type.
2087       if (NumViaIntegerBits <= 32)
2088         Bits = SignExtend64(Bits, 32);
2089       SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
2090       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
2091                         DAG.getConstant(IntegerEltIdx, DL, XLenVT));
2092 
2093       if (NumElts < NumViaIntegerBits) {
2094         // If we're producing a smaller vector than our minimum legal integer
2095         // type, bitcast to the equivalent (known-legal) mask type, and extract
2096         // our final mask.
2097         assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
2098         Vec = DAG.getBitcast(MVT::v8i1, Vec);
2099         Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
2100                           DAG.getConstant(0, DL, XLenVT));
2101       } else {
2102         // Else we must have produced an integer type with the same size as the
2103         // mask type; bitcast for the final result.
2104         assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
2105         Vec = DAG.getBitcast(VT, Vec);
2106       }
2107 
2108       return Vec;
2109     }
2110 
2111     // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
2112     // vector type, we have a legal equivalently-sized i8 type, so we can use
2113     // that.
2114     MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
2115     SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
2116 
2117     SDValue WideVec;
2118     if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2119       // For a splat, perform a scalar truncate before creating the wider
2120       // vector.
2121       assert(Splat.getValueType() == XLenVT &&
2122              "Unexpected type for i1 splat value");
2123       Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
2124                           DAG.getConstant(1, DL, XLenVT));
2125       WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
2126     } else {
2127       SmallVector<SDValue, 8> Ops(Op->op_values());
2128       WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
2129       SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
2130       WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
2131     }
2132 
2133     return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
2134   }
2135 
2136   if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
2137     if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
2138       return Gather;
2139     unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
2140                                         : RISCVISD::VMV_V_X_VL;
2141     Splat =
2142         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
2143     return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2144   }
2145 
2146   // Try and match index sequences, which we can lower to the vid instruction
2147   // with optional modifications. An all-undef vector is matched by
2148   // getSplatValue, above.
2149   if (auto SimpleVID = isSimpleVIDSequence(Op)) {
2150     int64_t StepNumerator = SimpleVID->StepNumerator;
2151     unsigned StepDenominator = SimpleVID->StepDenominator;
2152     int64_t Addend = SimpleVID->Addend;
2153 
2154     assert(StepNumerator != 0 && "Invalid step");
2155     bool Negate = false;
2156     int64_t SplatStepVal = StepNumerator;
2157     unsigned StepOpcode = ISD::MUL;
2158     if (StepNumerator != 1) {
2159       if (isPowerOf2_64(std::abs(StepNumerator))) {
2160         Negate = StepNumerator < 0;
2161         StepOpcode = ISD::SHL;
2162         SplatStepVal = Log2_64(std::abs(StepNumerator));
2163       }
2164     }
2165 
2166     // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
2167     // threshold since it's the immediate value many RVV instructions accept.
2168     // There is no vmul.vi instruction so ensure multiply constant can fit in
2169     // a single addi instruction.
2170     if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
2171          (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
2172         isPowerOf2_32(StepDenominator) && isInt<5>(Addend)) {
2173       SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL);
2174       // Convert right out of the scalable type so we can use standard ISD
2175       // nodes for the rest of the computation. If we used scalable types with
2176       // these, we'd lose the fixed-length vector info and generate worse
2177       // vsetvli code.
2178       VID = convertFromScalableVector(VT, VID, DAG, Subtarget);
2179       if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
2180           (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
2181         SDValue SplatStep = DAG.getSplatVector(
2182             VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
2183         VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep);
2184       }
2185       if (StepDenominator != 1) {
2186         SDValue SplatStep = DAG.getSplatVector(
2187             VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
2188         VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep);
2189       }
2190       if (Addend != 0 || Negate) {
2191         SDValue SplatAddend =
2192             DAG.getSplatVector(VT, DL, DAG.getConstant(Addend, DL, XLenVT));
2193         VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID);
2194       }
2195       return VID;
2196     }
2197   }
2198 
2199   // Attempt to detect "hidden" splats, which only reveal themselves as splats
2200   // when re-interpreted as a vector with a larger element type. For example,
2201   //   v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
2202   // could be instead splat as
2203   //   v2i32 = build_vector i32 0x00010000, i32 0x00010000
2204   // TODO: This optimization could also work on non-constant splats, but it
2205   // would require bit-manipulation instructions to construct the splat value.
2206   SmallVector<SDValue> Sequence;
2207   unsigned EltBitSize = VT.getScalarSizeInBits();
2208   const auto *BV = cast<BuildVectorSDNode>(Op);
2209   if (VT.isInteger() && EltBitSize < 64 &&
2210       ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
2211       BV->getRepeatedSequence(Sequence) &&
2212       (Sequence.size() * EltBitSize) <= 64) {
2213     unsigned SeqLen = Sequence.size();
2214     MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
2215     MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
2216     assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
2217             ViaIntVT == MVT::i64) &&
2218            "Unexpected sequence type");
2219 
2220     unsigned EltIdx = 0;
2221     uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
2222     uint64_t SplatValue = 0;
2223     // Construct the amalgamated value which can be splatted as this larger
2224     // vector type.
2225     for (const auto &SeqV : Sequence) {
2226       if (!SeqV.isUndef())
2227         SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
2228                        << (EltIdx * EltBitSize));
2229       EltIdx++;
2230     }
2231 
2232     // On RV64, sign-extend from 32 to 64 bits where possible in order to
2233     // achieve better constant materializion.
2234     if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
2235       SplatValue = SignExtend64(SplatValue, 32);
2236 
2237     // Since we can't introduce illegal i64 types at this stage, we can only
2238     // perform an i64 splat on RV32 if it is its own sign-extended value. That
2239     // way we can use RVV instructions to splat.
2240     assert((ViaIntVT.bitsLE(XLenVT) ||
2241             (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
2242            "Unexpected bitcast sequence");
2243     if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
2244       SDValue ViaVL =
2245           DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
2246       MVT ViaContainerVT =
2247           getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
2248       SDValue Splat =
2249           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
2250                       DAG.getUNDEF(ViaContainerVT),
2251                       DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
2252       Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
2253       return DAG.getBitcast(VT, Splat);
2254     }
2255   }
2256 
2257   // Try and optimize BUILD_VECTORs with "dominant values" - these are values
2258   // which constitute a large proportion of the elements. In such cases we can
2259   // splat a vector with the dominant element and make up the shortfall with
2260   // INSERT_VECTOR_ELTs.
2261   // Note that this includes vectors of 2 elements by association. The
2262   // upper-most element is the "dominant" one, allowing us to use a splat to
2263   // "insert" the upper element, and an insert of the lower element at position
2264   // 0, which improves codegen.
2265   SDValue DominantValue;
2266   unsigned MostCommonCount = 0;
2267   DenseMap<SDValue, unsigned> ValueCounts;
2268   unsigned NumUndefElts =
2269       count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
2270 
2271   // Track the number of scalar loads we know we'd be inserting, estimated as
2272   // any non-zero floating-point constant. Other kinds of element are either
2273   // already in registers or are materialized on demand. The threshold at which
2274   // a vector load is more desirable than several scalar materializion and
2275   // vector-insertion instructions is not known.
2276   unsigned NumScalarLoads = 0;
2277 
2278   for (SDValue V : Op->op_values()) {
2279     if (V.isUndef())
2280       continue;
2281 
2282     ValueCounts.insert(std::make_pair(V, 0));
2283     unsigned &Count = ValueCounts[V];
2284 
2285     if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
2286       NumScalarLoads += !CFP->isExactlyValue(+0.0);
2287 
2288     // Is this value dominant? In case of a tie, prefer the highest element as
2289     // it's cheaper to insert near the beginning of a vector than it is at the
2290     // end.
2291     if (++Count >= MostCommonCount) {
2292       DominantValue = V;
2293       MostCommonCount = Count;
2294     }
2295   }
2296 
2297   assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
2298   unsigned NumDefElts = NumElts - NumUndefElts;
2299   unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
2300 
2301   // Don't perform this optimization when optimizing for size, since
2302   // materializing elements and inserting them tends to cause code bloat.
2303   if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
2304       ((MostCommonCount > DominantValueCountThreshold) ||
2305        (ValueCounts.size() <= Log2_32(NumDefElts)))) {
2306     // Start by splatting the most common element.
2307     SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
2308 
2309     DenseSet<SDValue> Processed{DominantValue};
2310     MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
2311     for (const auto &OpIdx : enumerate(Op->ops())) {
2312       const SDValue &V = OpIdx.value();
2313       if (V.isUndef() || !Processed.insert(V).second)
2314         continue;
2315       if (ValueCounts[V] == 1) {
2316         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
2317                           DAG.getConstant(OpIdx.index(), DL, XLenVT));
2318       } else {
2319         // Blend in all instances of this value using a VSELECT, using a
2320         // mask where each bit signals whether that element is the one
2321         // we're after.
2322         SmallVector<SDValue> Ops;
2323         transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
2324           return DAG.getConstant(V == V1, DL, XLenVT);
2325         });
2326         Vec = DAG.getNode(ISD::VSELECT, DL, VT,
2327                           DAG.getBuildVector(SelMaskTy, DL, Ops),
2328                           DAG.getSplatBuildVector(VT, DL, V), Vec);
2329       }
2330     }
2331 
2332     return Vec;
2333   }
2334 
2335   return SDValue();
2336 }
2337 
2338 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2339                                    SDValue Lo, SDValue Hi, SDValue VL,
2340                                    SelectionDAG &DAG) {
2341   bool HasPassthru = Passthru && !Passthru.isUndef();
2342   if (!HasPassthru && !Passthru)
2343     Passthru = DAG.getUNDEF(VT);
2344   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
2345     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
2346     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
2347     // If Hi constant is all the same sign bit as Lo, lower this as a custom
2348     // node in order to try and match RVV vector/scalar instructions.
2349     if ((LoC >> 31) == HiC)
2350       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
2351 
2352     // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
2353     // vmv.v.x whose EEW = 32 to lower it.
2354     auto *Const = dyn_cast<ConstantSDNode>(VL);
2355     if (LoC == HiC && Const && Const->isAllOnesValue()) {
2356       MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
2357       // TODO: if vl <= min(VLMAX), we can also do this. But we could not
2358       // access the subtarget here now.
2359       auto InterVec = DAG.getNode(
2360           RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
2361                                   DAG.getRegister(RISCV::X0, MVT::i32));
2362       return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
2363     }
2364   }
2365 
2366   // Fall back to a stack store and stride x0 vector load.
2367   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
2368                      Hi, VL);
2369 }
2370 
2371 // Called by type legalization to handle splat of i64 on RV32.
2372 // FIXME: We can optimize this when the type has sign or zero bits in one
2373 // of the halves.
2374 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
2375                                    SDValue Scalar, SDValue VL,
2376                                    SelectionDAG &DAG) {
2377   assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
2378   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2379                            DAG.getConstant(0, DL, MVT::i32));
2380   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
2381                            DAG.getConstant(1, DL, MVT::i32));
2382   return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
2383 }
2384 
2385 // This function lowers a splat of a scalar operand Splat with the vector
2386 // length VL. It ensures the final sequence is type legal, which is useful when
2387 // lowering a splat after type legalization.
2388 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
2389                                 MVT VT, SDLoc DL, SelectionDAG &DAG,
2390                                 const RISCVSubtarget &Subtarget) {
2391   bool HasPassthru = Passthru && !Passthru.isUndef();
2392   if (!HasPassthru && !Passthru)
2393     Passthru = DAG.getUNDEF(VT);
2394   if (VT.isFloatingPoint()) {
2395     // If VL is 1, we could use vfmv.s.f.
2396     if (isOneConstant(VL))
2397       return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
2398     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
2399   }
2400 
2401   MVT XLenVT = Subtarget.getXLenVT();
2402 
2403   // Simplest case is that the operand needs to be promoted to XLenVT.
2404   if (Scalar.getValueType().bitsLE(XLenVT)) {
2405     // If the operand is a constant, sign extend to increase our chances
2406     // of being able to use a .vi instruction. ANY_EXTEND would become a
2407     // a zero extend and the simm5 check in isel would fail.
2408     // FIXME: Should we ignore the upper bits in isel instead?
2409     unsigned ExtOpc =
2410         isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
2411     Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
2412     ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
2413     // If VL is 1 and the scalar value won't benefit from immediate, we could
2414     // use vmv.s.x.
2415     if (isOneConstant(VL) &&
2416         (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
2417       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
2418     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
2419   }
2420 
2421   assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
2422          "Unexpected scalar for splat lowering!");
2423 
2424   if (isOneConstant(VL) && isNullConstant(Scalar))
2425     return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
2426                        DAG.getConstant(0, DL, XLenVT), VL);
2427 
2428   // Otherwise use the more complicated splatting algorithm.
2429   return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
2430 }
2431 
2432 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
2433                                 const RISCVSubtarget &Subtarget) {
2434   // We need to be able to widen elements to the next larger integer type.
2435   if (VT.getScalarSizeInBits() >= Subtarget.getMaxELENForFixedLengthVectors())
2436     return false;
2437 
2438   int Size = Mask.size();
2439   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
2440 
2441   int Srcs[] = {-1, -1};
2442   for (int i = 0; i != Size; ++i) {
2443     // Ignore undef elements.
2444     if (Mask[i] < 0)
2445       continue;
2446 
2447     // Is this an even or odd element.
2448     int Pol = i % 2;
2449 
2450     // Ensure we consistently use the same source for this element polarity.
2451     int Src = Mask[i] / Size;
2452     if (Srcs[Pol] < 0)
2453       Srcs[Pol] = Src;
2454     if (Srcs[Pol] != Src)
2455       return false;
2456 
2457     // Make sure the element within the source is appropriate for this element
2458     // in the destination.
2459     int Elt = Mask[i] % Size;
2460     if (Elt != i / 2)
2461       return false;
2462   }
2463 
2464   // We need to find a source for each polarity and they can't be the same.
2465   if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
2466     return false;
2467 
2468   // Swap the sources if the second source was in the even polarity.
2469   SwapSources = Srcs[0] > Srcs[1];
2470 
2471   return true;
2472 }
2473 
2474 /// Match shuffles that concatenate two vectors, rotate the concatenation,
2475 /// and then extract the original number of elements from the rotated result.
2476 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
2477 /// returned rotation amount is for a rotate right, where elements move from
2478 /// higher elements to lower elements. \p LoSrc indicates the first source
2479 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
2480 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
2481 /// 0 or 1 if a rotation is found.
2482 ///
2483 /// NOTE: We talk about rotate to the right which matches how bit shift and
2484 /// rotate instructions are described where LSBs are on the right, but LLVM IR
2485 /// and the table below write vectors with the lowest elements on the left.
2486 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
2487   int Size = Mask.size();
2488 
2489   // We need to detect various ways of spelling a rotation:
2490   //   [11, 12, 13, 14, 15,  0,  1,  2]
2491   //   [-1, 12, 13, 14, -1, -1,  1, -1]
2492   //   [-1, -1, -1, -1, -1, -1,  1,  2]
2493   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
2494   //   [-1,  4,  5,  6, -1, -1,  9, -1]
2495   //   [-1,  4,  5,  6, -1, -1, -1, -1]
2496   int Rotation = 0;
2497   LoSrc = -1;
2498   HiSrc = -1;
2499   for (int i = 0; i != Size; ++i) {
2500     int M = Mask[i];
2501     if (M < 0)
2502       continue;
2503 
2504     // Determine where a rotate vector would have started.
2505     int StartIdx = i - (M % Size);
2506     // The identity rotation isn't interesting, stop.
2507     if (StartIdx == 0)
2508       return -1;
2509 
2510     // If we found the tail of a vector the rotation must be the missing
2511     // front. If we found the head of a vector, it must be how much of the
2512     // head.
2513     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
2514 
2515     if (Rotation == 0)
2516       Rotation = CandidateRotation;
2517     else if (Rotation != CandidateRotation)
2518       // The rotations don't match, so we can't match this mask.
2519       return -1;
2520 
2521     // Compute which value this mask is pointing at.
2522     int MaskSrc = M < Size ? 0 : 1;
2523 
2524     // Compute which of the two target values this index should be assigned to.
2525     // This reflects whether the high elements are remaining or the low elemnts
2526     // are remaining.
2527     int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
2528 
2529     // Either set up this value if we've not encountered it before, or check
2530     // that it remains consistent.
2531     if (TargetSrc < 0)
2532       TargetSrc = MaskSrc;
2533     else if (TargetSrc != MaskSrc)
2534       // This may be a rotation, but it pulls from the inputs in some
2535       // unsupported interleaving.
2536       return -1;
2537   }
2538 
2539   // Check that we successfully analyzed the mask, and normalize the results.
2540   assert(Rotation != 0 && "Failed to locate a viable rotation!");
2541   assert((LoSrc >= 0 || HiSrc >= 0) &&
2542          "Failed to find a rotated input vector!");
2543 
2544   return Rotation;
2545 }
2546 
2547 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
2548                                    const RISCVSubtarget &Subtarget) {
2549   SDValue V1 = Op.getOperand(0);
2550   SDValue V2 = Op.getOperand(1);
2551   SDLoc DL(Op);
2552   MVT XLenVT = Subtarget.getXLenVT();
2553   MVT VT = Op.getSimpleValueType();
2554   unsigned NumElts = VT.getVectorNumElements();
2555   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
2556 
2557   MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
2558 
2559   SDValue TrueMask, VL;
2560   std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2561 
2562   if (SVN->isSplat()) {
2563     const int Lane = SVN->getSplatIndex();
2564     if (Lane >= 0) {
2565       MVT SVT = VT.getVectorElementType();
2566 
2567       // Turn splatted vector load into a strided load with an X0 stride.
2568       SDValue V = V1;
2569       // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
2570       // with undef.
2571       // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
2572       int Offset = Lane;
2573       if (V.getOpcode() == ISD::CONCAT_VECTORS) {
2574         int OpElements =
2575             V.getOperand(0).getSimpleValueType().getVectorNumElements();
2576         V = V.getOperand(Offset / OpElements);
2577         Offset %= OpElements;
2578       }
2579 
2580       // We need to ensure the load isn't atomic or volatile.
2581       if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
2582         auto *Ld = cast<LoadSDNode>(V);
2583         Offset *= SVT.getStoreSize();
2584         SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
2585                                                    TypeSize::Fixed(Offset), DL);
2586 
2587         // If this is SEW=64 on RV32, use a strided load with a stride of x0.
2588         if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
2589           SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
2590           SDValue IntID =
2591               DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
2592           SDValue Ops[] = {Ld->getChain(),
2593                            IntID,
2594                            DAG.getUNDEF(ContainerVT),
2595                            NewAddr,
2596                            DAG.getRegister(RISCV::X0, XLenVT),
2597                            VL};
2598           SDValue NewLoad = DAG.getMemIntrinsicNode(
2599               ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
2600               DAG.getMachineFunction().getMachineMemOperand(
2601                   Ld->getMemOperand(), Offset, SVT.getStoreSize()));
2602           DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
2603           return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
2604         }
2605 
2606         // Otherwise use a scalar load and splat. This will give the best
2607         // opportunity to fold a splat into the operation. ISel can turn it into
2608         // the x0 strided load if we aren't able to fold away the select.
2609         if (SVT.isFloatingPoint())
2610           V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
2611                           Ld->getPointerInfo().getWithOffset(Offset),
2612                           Ld->getOriginalAlign(),
2613                           Ld->getMemOperand()->getFlags());
2614         else
2615           V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
2616                              Ld->getPointerInfo().getWithOffset(Offset), SVT,
2617                              Ld->getOriginalAlign(),
2618                              Ld->getMemOperand()->getFlags());
2619         DAG.makeEquivalentMemoryOrdering(Ld, V);
2620 
2621         unsigned Opc =
2622             VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
2623         SDValue Splat =
2624             DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
2625         return convertFromScalableVector(VT, Splat, DAG, Subtarget);
2626       }
2627 
2628       V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2629       assert(Lane < (int)NumElts && "Unexpected lane!");
2630       SDValue Gather =
2631           DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1,
2632                       DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL);
2633       return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2634     }
2635   }
2636 
2637   ArrayRef<int> Mask = SVN->getMask();
2638 
2639   // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
2640   // be undef which can be handled with a single SLIDEDOWN/UP.
2641   int LoSrc, HiSrc;
2642   int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
2643   if (Rotation > 0) {
2644     SDValue LoV, HiV;
2645     if (LoSrc >= 0) {
2646       LoV = LoSrc == 0 ? V1 : V2;
2647       LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
2648     }
2649     if (HiSrc >= 0) {
2650       HiV = HiSrc == 0 ? V1 : V2;
2651       HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
2652     }
2653 
2654     // We found a rotation. We need to slide HiV down by Rotation. Then we need
2655     // to slide LoV up by (NumElts - Rotation).
2656     unsigned InvRotate = NumElts - Rotation;
2657 
2658     SDValue Res = DAG.getUNDEF(ContainerVT);
2659     if (HiV) {
2660       // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
2661       // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
2662       // causes multiple vsetvlis in some test cases such as lowering
2663       // reduce.mul
2664       SDValue DownVL = VL;
2665       if (LoV)
2666         DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
2667       Res =
2668           DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV,
2669                       DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL);
2670     }
2671     if (LoV)
2672       Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV,
2673                         DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL);
2674 
2675     return convertFromScalableVector(VT, Res, DAG, Subtarget);
2676   }
2677 
2678   // Detect an interleave shuffle and lower to
2679   // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
2680   bool SwapSources;
2681   if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
2682     // Swap sources if needed.
2683     if (SwapSources)
2684       std::swap(V1, V2);
2685 
2686     // Extract the lower half of the vectors.
2687     MVT HalfVT = VT.getHalfNumVectorElementsVT();
2688     V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
2689                      DAG.getConstant(0, DL, XLenVT));
2690     V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
2691                      DAG.getConstant(0, DL, XLenVT));
2692 
2693     // Double the element width and halve the number of elements in an int type.
2694     unsigned EltBits = VT.getScalarSizeInBits();
2695     MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
2696     MVT WideIntVT =
2697         MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
2698     // Convert this to a scalable vector. We need to base this on the
2699     // destination size to ensure there's always a type with a smaller LMUL.
2700     MVT WideIntContainerVT =
2701         getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
2702 
2703     // Convert sources to scalable vectors with the same element count as the
2704     // larger type.
2705     MVT HalfContainerVT = MVT::getVectorVT(
2706         VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
2707     V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
2708     V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
2709 
2710     // Cast sources to integer.
2711     MVT IntEltVT = MVT::getIntegerVT(EltBits);
2712     MVT IntHalfVT =
2713         MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
2714     V1 = DAG.getBitcast(IntHalfVT, V1);
2715     V2 = DAG.getBitcast(IntHalfVT, V2);
2716 
2717     // Freeze V2 since we use it twice and we need to be sure that the add and
2718     // multiply see the same value.
2719     V2 = DAG.getFreeze(V2);
2720 
2721     // Recreate TrueMask using the widened type's element count.
2722     MVT MaskVT =
2723         MVT::getVectorVT(MVT::i1, HalfContainerVT.getVectorElementCount());
2724     TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
2725 
2726     // Widen V1 and V2 with 0s and add one copy of V2 to V1.
2727     SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1,
2728                               V2, TrueMask, VL);
2729     // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
2730     SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
2731                                      DAG.getUNDEF(IntHalfVT),
2732                                      DAG.getAllOnesConstant(DL, XLenVT));
2733     SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT,
2734                                    V2, Multiplier, TrueMask, VL);
2735     // Add the new copies to our previous addition giving us 2^eltbits copies of
2736     // V2. This is equivalent to shifting V2 left by eltbits. This should
2737     // combine with the vwmulu.vv above to form vwmaccu.vv.
2738     Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
2739                       TrueMask, VL);
2740     // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
2741     // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
2742     // vector VT.
2743     ContainerVT =
2744         MVT::getVectorVT(VT.getVectorElementType(),
2745                          WideIntContainerVT.getVectorElementCount() * 2);
2746     Add = DAG.getBitcast(ContainerVT, Add);
2747     return convertFromScalableVector(VT, Add, DAG, Subtarget);
2748   }
2749 
2750   // Detect shuffles which can be re-expressed as vector selects; these are
2751   // shuffles in which each element in the destination is taken from an element
2752   // at the corresponding index in either source vectors.
2753   bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
2754     int MaskIndex = MaskIdx.value();
2755     return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
2756   });
2757 
2758   assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
2759 
2760   SmallVector<SDValue> MaskVals;
2761   // As a backup, shuffles can be lowered via a vrgather instruction, possibly
2762   // merged with a second vrgather.
2763   SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
2764 
2765   // By default we preserve the original operand order, and use a mask to
2766   // select LHS as true and RHS as false. However, since RVV vector selects may
2767   // feature splats but only on the LHS, we may choose to invert our mask and
2768   // instead select between RHS and LHS.
2769   bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
2770   bool InvertMask = IsSelect == SwapOps;
2771 
2772   // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
2773   // half.
2774   DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
2775 
2776   // Now construct the mask that will be used by the vselect or blended
2777   // vrgather operation. For vrgathers, construct the appropriate indices into
2778   // each vector.
2779   for (int MaskIndex : Mask) {
2780     bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
2781     MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
2782     if (!IsSelect) {
2783       bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
2784       GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
2785                                      ? DAG.getConstant(MaskIndex, DL, XLenVT)
2786                                      : DAG.getUNDEF(XLenVT));
2787       GatherIndicesRHS.push_back(
2788           IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
2789                             : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
2790       if (IsLHSOrUndefIndex && MaskIndex >= 0)
2791         ++LHSIndexCounts[MaskIndex];
2792       if (!IsLHSOrUndefIndex)
2793         ++RHSIndexCounts[MaskIndex - NumElts];
2794     }
2795   }
2796 
2797   if (SwapOps) {
2798     std::swap(V1, V2);
2799     std::swap(GatherIndicesLHS, GatherIndicesRHS);
2800   }
2801 
2802   assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
2803   MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
2804   SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
2805 
2806   if (IsSelect)
2807     return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
2808 
2809   if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
2810     // On such a large vector we're unable to use i8 as the index type.
2811     // FIXME: We could promote the index to i16 and use vrgatherei16, but that
2812     // may involve vector splitting if we're already at LMUL=8, or our
2813     // user-supplied maximum fixed-length LMUL.
2814     return SDValue();
2815   }
2816 
2817   unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
2818   unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
2819   MVT IndexVT = VT.changeTypeToInteger();
2820   // Since we can't introduce illegal index types at this stage, use i16 and
2821   // vrgatherei16 if the corresponding index type for plain vrgather is greater
2822   // than XLenVT.
2823   if (IndexVT.getScalarType().bitsGT(XLenVT)) {
2824     GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
2825     IndexVT = IndexVT.changeVectorElementType(MVT::i16);
2826   }
2827 
2828   MVT IndexContainerVT =
2829       ContainerVT.changeVectorElementType(IndexVT.getScalarType());
2830 
2831   SDValue Gather;
2832   // TODO: This doesn't trigger for i64 vectors on RV32, since there we
2833   // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
2834   if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
2835     Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
2836                               Subtarget);
2837   } else {
2838     V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
2839     // If only one index is used, we can use a "splat" vrgather.
2840     // TODO: We can splat the most-common index and fix-up any stragglers, if
2841     // that's beneficial.
2842     if (LHSIndexCounts.size() == 1) {
2843       int SplatIndex = LHSIndexCounts.begin()->getFirst();
2844       Gather =
2845           DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
2846                       DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2847     } else {
2848       SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
2849       LHSIndices =
2850           convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
2851 
2852       Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
2853                            TrueMask, VL);
2854     }
2855   }
2856 
2857   // If a second vector operand is used by this shuffle, blend it in with an
2858   // additional vrgather.
2859   if (!V2.isUndef()) {
2860     V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
2861     // If only one index is used, we can use a "splat" vrgather.
2862     // TODO: We can splat the most-common index and fix-up any stragglers, if
2863     // that's beneficial.
2864     if (RHSIndexCounts.size() == 1) {
2865       int SplatIndex = RHSIndexCounts.begin()->getFirst();
2866       V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
2867                        DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL);
2868     } else {
2869       SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
2870       RHSIndices =
2871           convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
2872       V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask,
2873                        VL);
2874     }
2875 
2876     MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
2877     SelectMask =
2878         convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
2879 
2880     Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2,
2881                          Gather, VL);
2882   }
2883 
2884   return convertFromScalableVector(VT, Gather, DAG, Subtarget);
2885 }
2886 
2887 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
2888   // Support splats for any type. These should type legalize well.
2889   if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
2890     return true;
2891 
2892   // Only support legal VTs for other shuffles for now.
2893   if (!isTypeLegal(VT))
2894     return false;
2895 
2896   MVT SVT = VT.getSimpleVT();
2897 
2898   bool SwapSources;
2899   int LoSrc, HiSrc;
2900   return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
2901          isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
2902 }
2903 
2904 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT,
2905                                      SDLoc DL, SelectionDAG &DAG,
2906                                      const RISCVSubtarget &Subtarget) {
2907   if (VT.isScalableVector())
2908     return DAG.getFPExtendOrRound(Op, DL, VT);
2909   assert(VT.isFixedLengthVector() &&
2910          "Unexpected value type for RVV FP extend/round lowering");
2911   SDValue Mask, VL;
2912   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
2913   unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType())
2914                         ? RISCVISD::FP_EXTEND_VL
2915                         : RISCVISD::FP_ROUND_VL;
2916   return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL);
2917 }
2918 
2919 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
2920 // the exponent.
2921 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
2922   MVT VT = Op.getSimpleValueType();
2923   unsigned EltSize = VT.getScalarSizeInBits();
2924   SDValue Src = Op.getOperand(0);
2925   SDLoc DL(Op);
2926 
2927   // We need a FP type that can represent the value.
2928   // TODO: Use f16 for i8 when possible?
2929   MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32;
2930   MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
2931 
2932   // Legal types should have been checked in the RISCVTargetLowering
2933   // constructor.
2934   // TODO: Splitting may make sense in some cases.
2935   assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
2936          "Expected legal float type!");
2937 
2938   // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
2939   // The trailing zero count is equal to log2 of this single bit value.
2940   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
2941     SDValue Neg =
2942         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src);
2943     Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
2944   }
2945 
2946   // We have a legal FP type, convert to it.
2947   SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
2948   // Bitcast to integer and shift the exponent to the LSB.
2949   EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
2950   SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
2951   unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
2952   SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
2953                               DAG.getConstant(ShiftAmt, DL, IntVT));
2954   // Truncate back to original type to allow vnsrl.
2955   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift);
2956   // The exponent contains log2 of the value in biased form.
2957   unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
2958 
2959   // For trailing zeros, we just need to subtract the bias.
2960   if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
2961     return DAG.getNode(ISD::SUB, DL, VT, Trunc,
2962                        DAG.getConstant(ExponentBias, DL, VT));
2963 
2964   // For leading zeros, we need to remove the bias and convert from log2 to
2965   // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
2966   unsigned Adjust = ExponentBias + (EltSize - 1);
2967   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc);
2968 }
2969 
2970 // While RVV has alignment restrictions, we should always be able to load as a
2971 // legal equivalently-sized byte-typed vector instead. This method is
2972 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
2973 // the load is already correctly-aligned, it returns SDValue().
2974 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
2975                                                     SelectionDAG &DAG) const {
2976   auto *Load = cast<LoadSDNode>(Op);
2977   assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
2978 
2979   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
2980                                      Load->getMemoryVT(),
2981                                      *Load->getMemOperand()))
2982     return SDValue();
2983 
2984   SDLoc DL(Op);
2985   MVT VT = Op.getSimpleValueType();
2986   unsigned EltSizeBits = VT.getScalarSizeInBits();
2987   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
2988          "Unexpected unaligned RVV load type");
2989   MVT NewVT =
2990       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
2991   assert(NewVT.isValid() &&
2992          "Expecting equally-sized RVV vector types to be legal");
2993   SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
2994                           Load->getPointerInfo(), Load->getOriginalAlign(),
2995                           Load->getMemOperand()->getFlags());
2996   return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
2997 }
2998 
2999 // While RVV has alignment restrictions, we should always be able to store as a
3000 // legal equivalently-sized byte-typed vector instead. This method is
3001 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
3002 // returns SDValue() if the store is already correctly aligned.
3003 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
3004                                                      SelectionDAG &DAG) const {
3005   auto *Store = cast<StoreSDNode>(Op);
3006   assert(Store && Store->getValue().getValueType().isVector() &&
3007          "Expected vector store");
3008 
3009   if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
3010                                      Store->getMemoryVT(),
3011                                      *Store->getMemOperand()))
3012     return SDValue();
3013 
3014   SDLoc DL(Op);
3015   SDValue StoredVal = Store->getValue();
3016   MVT VT = StoredVal.getSimpleValueType();
3017   unsigned EltSizeBits = VT.getScalarSizeInBits();
3018   assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
3019          "Unexpected unaligned RVV store type");
3020   MVT NewVT =
3021       MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
3022   assert(NewVT.isValid() &&
3023          "Expecting equally-sized RVV vector types to be legal");
3024   StoredVal = DAG.getBitcast(NewVT, StoredVal);
3025   return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
3026                       Store->getPointerInfo(), Store->getOriginalAlign(),
3027                       Store->getMemOperand()->getFlags());
3028 }
3029 
3030 SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
3031                                             SelectionDAG &DAG) const {
3032   switch (Op.getOpcode()) {
3033   default:
3034     report_fatal_error("unimplemented operand");
3035   case ISD::GlobalAddress:
3036     return lowerGlobalAddress(Op, DAG);
3037   case ISD::BlockAddress:
3038     return lowerBlockAddress(Op, DAG);
3039   case ISD::ConstantPool:
3040     return lowerConstantPool(Op, DAG);
3041   case ISD::JumpTable:
3042     return lowerJumpTable(Op, DAG);
3043   case ISD::GlobalTLSAddress:
3044     return lowerGlobalTLSAddress(Op, DAG);
3045   case ISD::SELECT:
3046     return lowerSELECT(Op, DAG);
3047   case ISD::BRCOND:
3048     return lowerBRCOND(Op, DAG);
3049   case ISD::VASTART:
3050     return lowerVASTART(Op, DAG);
3051   case ISD::FRAMEADDR:
3052     return lowerFRAMEADDR(Op, DAG);
3053   case ISD::RETURNADDR:
3054     return lowerRETURNADDR(Op, DAG);
3055   case ISD::SHL_PARTS:
3056     return lowerShiftLeftParts(Op, DAG);
3057   case ISD::SRA_PARTS:
3058     return lowerShiftRightParts(Op, DAG, true);
3059   case ISD::SRL_PARTS:
3060     return lowerShiftRightParts(Op, DAG, false);
3061   case ISD::BITCAST: {
3062     SDLoc DL(Op);
3063     EVT VT = Op.getValueType();
3064     SDValue Op0 = Op.getOperand(0);
3065     EVT Op0VT = Op0.getValueType();
3066     MVT XLenVT = Subtarget.getXLenVT();
3067     if (VT.isFixedLengthVector()) {
3068       // We can handle fixed length vector bitcasts with a simple replacement
3069       // in isel.
3070       if (Op0VT.isFixedLengthVector())
3071         return Op;
3072       // When bitcasting from scalar to fixed-length vector, insert the scalar
3073       // into a one-element vector of the result type, and perform a vector
3074       // bitcast.
3075       if (!Op0VT.isVector()) {
3076         EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
3077         if (!isTypeLegal(BVT))
3078           return SDValue();
3079         return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
3080                                               DAG.getUNDEF(BVT), Op0,
3081                                               DAG.getConstant(0, DL, XLenVT)));
3082       }
3083       return SDValue();
3084     }
3085     // Custom-legalize bitcasts from fixed-length vector types to scalar types
3086     // thus: bitcast the vector to a one-element vector type whose element type
3087     // is the same as the result type, and extract the first element.
3088     if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
3089       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
3090       if (!isTypeLegal(BVT))
3091         return SDValue();
3092       SDValue BVec = DAG.getBitcast(BVT, Op0);
3093       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
3094                          DAG.getConstant(0, DL, XLenVT));
3095     }
3096     if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) {
3097       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
3098       SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
3099       return FPConv;
3100     }
3101     if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
3102         Subtarget.hasStdExtF()) {
3103       SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
3104       SDValue FPConv =
3105           DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
3106       return FPConv;
3107     }
3108     return SDValue();
3109   }
3110   case ISD::INTRINSIC_WO_CHAIN:
3111     return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3112   case ISD::INTRINSIC_W_CHAIN:
3113     return LowerINTRINSIC_W_CHAIN(Op, DAG);
3114   case ISD::INTRINSIC_VOID:
3115     return LowerINTRINSIC_VOID(Op, DAG);
3116   case ISD::BSWAP:
3117   case ISD::BITREVERSE: {
3118     MVT VT = Op.getSimpleValueType();
3119     SDLoc DL(Op);
3120     if (Subtarget.hasStdExtZbp()) {
3121       // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining.
3122       // Start with the maximum immediate value which is the bitwidth - 1.
3123       unsigned Imm = VT.getSizeInBits() - 1;
3124       // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
3125       if (Op.getOpcode() == ISD::BSWAP)
3126         Imm &= ~0x7U;
3127       return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0),
3128                          DAG.getConstant(Imm, DL, VT));
3129     }
3130     assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
3131     assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
3132     // Expand bitreverse to a bswap(rev8) followed by brev8.
3133     SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
3134     // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized
3135     // as brev8 by an isel pattern.
3136     return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap,
3137                        DAG.getConstant(7, DL, VT));
3138   }
3139   case ISD::FSHL:
3140   case ISD::FSHR: {
3141     MVT VT = Op.getSimpleValueType();
3142     assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization");
3143     SDLoc DL(Op);
3144     // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only
3145     // use log(XLen) bits. Mask the shift amount accordingly to prevent
3146     // accidentally setting the extra bit.
3147     unsigned ShAmtWidth = Subtarget.getXLen() - 1;
3148     SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2),
3149                                 DAG.getConstant(ShAmtWidth, DL, VT));
3150     // fshl and fshr concatenate their operands in the same order. fsr and fsl
3151     // instruction use different orders. fshl will return its first operand for
3152     // shift of zero, fshr will return its second operand. fsl and fsr both
3153     // return rs1 so the ISD nodes need to have different operand orders.
3154     // Shift amount is in rs2.
3155     SDValue Op0 = Op.getOperand(0);
3156     SDValue Op1 = Op.getOperand(1);
3157     unsigned Opc = RISCVISD::FSL;
3158     if (Op.getOpcode() == ISD::FSHR) {
3159       std::swap(Op0, Op1);
3160       Opc = RISCVISD::FSR;
3161     }
3162     return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt);
3163   }
3164   case ISD::TRUNCATE: {
3165     SDLoc DL(Op);
3166     MVT VT = Op.getSimpleValueType();
3167     // Only custom-lower vector truncates
3168     if (!VT.isVector())
3169       return Op;
3170 
3171     // Truncates to mask types are handled differently
3172     if (VT.getVectorElementType() == MVT::i1)
3173       return lowerVectorMaskTrunc(Op, DAG);
3174 
3175     // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
3176     // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
3177     // truncate by one power of two at a time.
3178     MVT DstEltVT = VT.getVectorElementType();
3179 
3180     SDValue Src = Op.getOperand(0);
3181     MVT SrcVT = Src.getSimpleValueType();
3182     MVT SrcEltVT = SrcVT.getVectorElementType();
3183 
3184     assert(DstEltVT.bitsLT(SrcEltVT) &&
3185            isPowerOf2_64(DstEltVT.getSizeInBits()) &&
3186            isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
3187            "Unexpected vector truncate lowering");
3188 
3189     MVT ContainerVT = SrcVT;
3190     if (SrcVT.isFixedLengthVector()) {
3191       ContainerVT = getContainerForFixedLengthVector(SrcVT);
3192       Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
3193     }
3194 
3195     SDValue Result = Src;
3196     SDValue Mask, VL;
3197     std::tie(Mask, VL) =
3198         getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
3199     LLVMContext &Context = *DAG.getContext();
3200     const ElementCount Count = ContainerVT.getVectorElementCount();
3201     do {
3202       SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
3203       EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
3204       Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
3205                            Mask, VL);
3206     } while (SrcEltVT != DstEltVT);
3207 
3208     if (SrcVT.isFixedLengthVector())
3209       Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
3210 
3211     return Result;
3212   }
3213   case ISD::ANY_EXTEND:
3214   case ISD::ZERO_EXTEND:
3215     if (Op.getOperand(0).getValueType().isVector() &&
3216         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3217       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
3218     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
3219   case ISD::SIGN_EXTEND:
3220     if (Op.getOperand(0).getValueType().isVector() &&
3221         Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3222       return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
3223     return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
3224   case ISD::SPLAT_VECTOR_PARTS:
3225     return lowerSPLAT_VECTOR_PARTS(Op, DAG);
3226   case ISD::INSERT_VECTOR_ELT:
3227     return lowerINSERT_VECTOR_ELT(Op, DAG);
3228   case ISD::EXTRACT_VECTOR_ELT:
3229     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3230   case ISD::VSCALE: {
3231     MVT VT = Op.getSimpleValueType();
3232     SDLoc DL(Op);
3233     SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
3234     // We define our scalable vector types for lmul=1 to use a 64 bit known
3235     // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
3236     // vscale as VLENB / 8.
3237     static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
3238     if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock)
3239       report_fatal_error("Support for VLEN==32 is incomplete.");
3240     if (isa<ConstantSDNode>(Op.getOperand(0))) {
3241       // We assume VLENB is a multiple of 8. We manually choose the best shift
3242       // here because SimplifyDemandedBits isn't always able to simplify it.
3243       uint64_t Val = Op.getConstantOperandVal(0);
3244       if (isPowerOf2_64(Val)) {
3245         uint64_t Log2 = Log2_64(Val);
3246         if (Log2 < 3)
3247           return DAG.getNode(ISD::SRL, DL, VT, VLENB,
3248                              DAG.getConstant(3 - Log2, DL, VT));
3249         if (Log2 > 3)
3250           return DAG.getNode(ISD::SHL, DL, VT, VLENB,
3251                              DAG.getConstant(Log2 - 3, DL, VT));
3252         return VLENB;
3253       }
3254       // If the multiplier is a multiple of 8, scale it down to avoid needing
3255       // to shift the VLENB value.
3256       if ((Val % 8) == 0)
3257         return DAG.getNode(ISD::MUL, DL, VT, VLENB,
3258                            DAG.getConstant(Val / 8, DL, VT));
3259     }
3260 
3261     SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
3262                                  DAG.getConstant(3, DL, VT));
3263     return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
3264   }
3265   case ISD::FPOWI: {
3266     // Custom promote f16 powi with illegal i32 integer type on RV64. Once
3267     // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
3268     if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
3269         Op.getOperand(1).getValueType() == MVT::i32) {
3270       SDLoc DL(Op);
3271       SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
3272       SDValue Powi =
3273           DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
3274       return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
3275                          DAG.getIntPtrConstant(0, DL));
3276     }
3277     return SDValue();
3278   }
3279   case ISD::FP_EXTEND: {
3280     // RVV can only do fp_extend to types double the size as the source. We
3281     // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going
3282     // via f32.
3283     SDLoc DL(Op);
3284     MVT VT = Op.getSimpleValueType();
3285     SDValue Src = Op.getOperand(0);
3286     MVT SrcVT = Src.getSimpleValueType();
3287 
3288     // Prepare any fixed-length vector operands.
3289     MVT ContainerVT = VT;
3290     if (SrcVT.isFixedLengthVector()) {
3291       ContainerVT = getContainerForFixedLengthVector(VT);
3292       MVT SrcContainerVT =
3293           ContainerVT.changeVectorElementType(SrcVT.getVectorElementType());
3294       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3295     }
3296 
3297     if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 ||
3298         SrcVT.getVectorElementType() != MVT::f16) {
3299       // For scalable vectors, we only need to close the gap between
3300       // vXf16->vXf64.
3301       if (!VT.isFixedLengthVector())
3302         return Op;
3303       // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version.
3304       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3305       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3306     }
3307 
3308     MVT InterVT = VT.changeVectorElementType(MVT::f32);
3309     MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32);
3310     SDValue IntermediateExtend = getRVVFPExtendOrRound(
3311         Src, InterVT, InterContainerVT, DL, DAG, Subtarget);
3312 
3313     SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT,
3314                                            DL, DAG, Subtarget);
3315     if (VT.isFixedLengthVector())
3316       return convertFromScalableVector(VT, Extend, DAG, Subtarget);
3317     return Extend;
3318   }
3319   case ISD::FP_ROUND: {
3320     // RVV can only do fp_round to types half the size as the source. We
3321     // custom-lower f64->f16 rounds via RVV's round-to-odd float
3322     // conversion instruction.
3323     SDLoc DL(Op);
3324     MVT VT = Op.getSimpleValueType();
3325     SDValue Src = Op.getOperand(0);
3326     MVT SrcVT = Src.getSimpleValueType();
3327 
3328     // Prepare any fixed-length vector operands.
3329     MVT ContainerVT = VT;
3330     if (VT.isFixedLengthVector()) {
3331       MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3332       ContainerVT =
3333           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3334       Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3335     }
3336 
3337     if (!VT.isVector() || VT.getVectorElementType() != MVT::f16 ||
3338         SrcVT.getVectorElementType() != MVT::f64) {
3339       // For scalable vectors, we only need to close the gap between
3340       // vXf64<->vXf16.
3341       if (!VT.isFixedLengthVector())
3342         return Op;
3343       // For fixed-length vectors, lower the FP_ROUND to a custom "VL" version.
3344       Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget);
3345       return convertFromScalableVector(VT, Src, DAG, Subtarget);
3346     }
3347 
3348     SDValue Mask, VL;
3349     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3350 
3351     MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
3352     SDValue IntermediateRound =
3353         DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL);
3354     SDValue Round = getRVVFPExtendOrRound(IntermediateRound, VT, ContainerVT,
3355                                           DL, DAG, Subtarget);
3356 
3357     if (VT.isFixedLengthVector())
3358       return convertFromScalableVector(VT, Round, DAG, Subtarget);
3359     return Round;
3360   }
3361   case ISD::FP_TO_SINT:
3362   case ISD::FP_TO_UINT:
3363   case ISD::SINT_TO_FP:
3364   case ISD::UINT_TO_FP: {
3365     // RVV can only do fp<->int conversions to types half/double the size as
3366     // the source. We custom-lower any conversions that do two hops into
3367     // sequences.
3368     MVT VT = Op.getSimpleValueType();
3369     if (!VT.isVector())
3370       return Op;
3371     SDLoc DL(Op);
3372     SDValue Src = Op.getOperand(0);
3373     MVT EltVT = VT.getVectorElementType();
3374     MVT SrcVT = Src.getSimpleValueType();
3375     MVT SrcEltVT = SrcVT.getVectorElementType();
3376     unsigned EltSize = EltVT.getSizeInBits();
3377     unsigned SrcEltSize = SrcEltVT.getSizeInBits();
3378     assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
3379            "Unexpected vector element types");
3380 
3381     bool IsInt2FP = SrcEltVT.isInteger();
3382     // Widening conversions
3383     if (EltSize > SrcEltSize && (EltSize / SrcEltSize >= 4)) {
3384       if (IsInt2FP) {
3385         // Do a regular integer sign/zero extension then convert to float.
3386         MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltVT.getSizeInBits()),
3387                                       VT.getVectorElementCount());
3388         unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
3389                                  ? ISD::ZERO_EXTEND
3390                                  : ISD::SIGN_EXTEND;
3391         SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
3392         return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
3393       }
3394       // FP2Int
3395       assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
3396       // Do one doubling fp_extend then complete the operation by converting
3397       // to int.
3398       MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3399       SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
3400       return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
3401     }
3402 
3403     // Narrowing conversions
3404     if (SrcEltSize > EltSize && (SrcEltSize / EltSize >= 4)) {
3405       if (IsInt2FP) {
3406         // One narrowing int_to_fp, then an fp_round.
3407         assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
3408         MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
3409         SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
3410         return DAG.getFPExtendOrRound(Int2FP, DL, VT);
3411       }
3412       // FP2Int
3413       // One narrowing fp_to_int, then truncate the integer. If the float isn't
3414       // representable by the integer, the result is poison.
3415       MVT IVecVT =
3416           MVT::getVectorVT(MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2),
3417                            VT.getVectorElementCount());
3418       SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
3419       return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
3420     }
3421 
3422     // Scalable vectors can exit here. Patterns will handle equally-sized
3423     // conversions halving/doubling ones.
3424     if (!VT.isFixedLengthVector())
3425       return Op;
3426 
3427     // For fixed-length vectors we lower to a custom "VL" node.
3428     unsigned RVVOpc = 0;
3429     switch (Op.getOpcode()) {
3430     default:
3431       llvm_unreachable("Impossible opcode");
3432     case ISD::FP_TO_SINT:
3433       RVVOpc = RISCVISD::FP_TO_SINT_VL;
3434       break;
3435     case ISD::FP_TO_UINT:
3436       RVVOpc = RISCVISD::FP_TO_UINT_VL;
3437       break;
3438     case ISD::SINT_TO_FP:
3439       RVVOpc = RISCVISD::SINT_TO_FP_VL;
3440       break;
3441     case ISD::UINT_TO_FP:
3442       RVVOpc = RISCVISD::UINT_TO_FP_VL;
3443       break;
3444     }
3445 
3446     MVT ContainerVT, SrcContainerVT;
3447     // Derive the reference container type from the larger vector type.
3448     if (SrcEltSize > EltSize) {
3449       SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
3450       ContainerVT =
3451           SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
3452     } else {
3453       ContainerVT = getContainerForFixedLengthVector(VT);
3454       SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT);
3455     }
3456 
3457     SDValue Mask, VL;
3458     std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
3459 
3460     Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
3461     Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
3462     return convertFromScalableVector(VT, Src, DAG, Subtarget);
3463   }
3464   case ISD::FP_TO_SINT_SAT:
3465   case ISD::FP_TO_UINT_SAT:
3466     return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
3467   case ISD::FTRUNC:
3468   case ISD::FCEIL:
3469   case ISD::FFLOOR:
3470     return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG);
3471   case ISD::FROUND:
3472     return lowerFROUND(Op, DAG);
3473   case ISD::VECREDUCE_ADD:
3474   case ISD::VECREDUCE_UMAX:
3475   case ISD::VECREDUCE_SMAX:
3476   case ISD::VECREDUCE_UMIN:
3477   case ISD::VECREDUCE_SMIN:
3478     return lowerVECREDUCE(Op, DAG);
3479   case ISD::VECREDUCE_AND:
3480   case ISD::VECREDUCE_OR:
3481   case ISD::VECREDUCE_XOR:
3482     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
3483       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
3484     return lowerVECREDUCE(Op, DAG);
3485   case ISD::VECREDUCE_FADD:
3486   case ISD::VECREDUCE_SEQ_FADD:
3487   case ISD::VECREDUCE_FMIN:
3488   case ISD::VECREDUCE_FMAX:
3489     return lowerFPVECREDUCE(Op, DAG);
3490   case ISD::VP_REDUCE_ADD:
3491   case ISD::VP_REDUCE_UMAX:
3492   case ISD::VP_REDUCE_SMAX:
3493   case ISD::VP_REDUCE_UMIN:
3494   case ISD::VP_REDUCE_SMIN:
3495   case ISD::VP_REDUCE_FADD:
3496   case ISD::VP_REDUCE_SEQ_FADD:
3497   case ISD::VP_REDUCE_FMIN:
3498   case ISD::VP_REDUCE_FMAX:
3499     return lowerVPREDUCE(Op, DAG);
3500   case ISD::VP_REDUCE_AND:
3501   case ISD::VP_REDUCE_OR:
3502   case ISD::VP_REDUCE_XOR:
3503     if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
3504       return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
3505     return lowerVPREDUCE(Op, DAG);
3506   case ISD::INSERT_SUBVECTOR:
3507     return lowerINSERT_SUBVECTOR(Op, DAG);
3508   case ISD::EXTRACT_SUBVECTOR:
3509     return lowerEXTRACT_SUBVECTOR(Op, DAG);
3510   case ISD::STEP_VECTOR:
3511     return lowerSTEP_VECTOR(Op, DAG);
3512   case ISD::VECTOR_REVERSE:
3513     return lowerVECTOR_REVERSE(Op, DAG);
3514   case ISD::VECTOR_SPLICE:
3515     return lowerVECTOR_SPLICE(Op, DAG);
3516   case ISD::BUILD_VECTOR:
3517     return lowerBUILD_VECTOR(Op, DAG, Subtarget);
3518   case ISD::SPLAT_VECTOR:
3519     if (Op.getValueType().getVectorElementType() == MVT::i1)
3520       return lowerVectorMaskSplat(Op, DAG);
3521     return lowerSPLAT_VECTOR(Op, DAG, Subtarget);
3522   case ISD::VECTOR_SHUFFLE:
3523     return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
3524   case ISD::CONCAT_VECTORS: {
3525     // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
3526     // better than going through the stack, as the default expansion does.
3527     SDLoc DL(Op);
3528     MVT VT = Op.getSimpleValueType();
3529     unsigned NumOpElts =
3530         Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
3531     SDValue Vec = DAG.getUNDEF(VT);
3532     for (const auto &OpIdx : enumerate(Op->ops())) {
3533       SDValue SubVec = OpIdx.value();
3534       // Don't insert undef subvectors.
3535       if (SubVec.isUndef())
3536         continue;
3537       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
3538                         DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
3539     }
3540     return Vec;
3541   }
3542   case ISD::LOAD:
3543     if (auto V = expandUnalignedRVVLoad(Op, DAG))
3544       return V;
3545     if (Op.getValueType().isFixedLengthVector())
3546       return lowerFixedLengthVectorLoadToRVV(Op, DAG);
3547     return Op;
3548   case ISD::STORE:
3549     if (auto V = expandUnalignedRVVStore(Op, DAG))
3550       return V;
3551     if (Op.getOperand(1).getValueType().isFixedLengthVector())
3552       return lowerFixedLengthVectorStoreToRVV(Op, DAG);
3553     return Op;
3554   case ISD::MLOAD:
3555   case ISD::VP_LOAD:
3556     return lowerMaskedLoad(Op, DAG);
3557   case ISD::MSTORE:
3558   case ISD::VP_STORE:
3559     return lowerMaskedStore(Op, DAG);
3560   case ISD::SETCC:
3561     return lowerFixedLengthVectorSetccToRVV(Op, DAG);
3562   case ISD::ADD:
3563     return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL);
3564   case ISD::SUB:
3565     return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL);
3566   case ISD::MUL:
3567     return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL);
3568   case ISD::MULHS:
3569     return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL);
3570   case ISD::MULHU:
3571     return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL);
3572   case ISD::AND:
3573     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
3574                                               RISCVISD::AND_VL);
3575   case ISD::OR:
3576     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
3577                                               RISCVISD::OR_VL);
3578   case ISD::XOR:
3579     return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
3580                                               RISCVISD::XOR_VL);
3581   case ISD::SDIV:
3582     return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL);
3583   case ISD::SREM:
3584     return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL);
3585   case ISD::UDIV:
3586     return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL);
3587   case ISD::UREM:
3588     return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL);
3589   case ISD::SHL:
3590   case ISD::SRA:
3591   case ISD::SRL:
3592     if (Op.getSimpleValueType().isFixedLengthVector())
3593       return lowerFixedLengthVectorShiftToRVV(Op, DAG);
3594     // This can be called for an i32 shift amount that needs to be promoted.
3595     assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
3596            "Unexpected custom legalisation");
3597     return SDValue();
3598   case ISD::SADDSAT:
3599     return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL);
3600   case ISD::UADDSAT:
3601     return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL);
3602   case ISD::SSUBSAT:
3603     return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL);
3604   case ISD::USUBSAT:
3605     return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL);
3606   case ISD::FADD:
3607     return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL);
3608   case ISD::FSUB:
3609     return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL);
3610   case ISD::FMUL:
3611     return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL);
3612   case ISD::FDIV:
3613     return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL);
3614   case ISD::FNEG:
3615     return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
3616   case ISD::FABS:
3617     return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
3618   case ISD::FSQRT:
3619     return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
3620   case ISD::FMA:
3621     return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL);
3622   case ISD::SMIN:
3623     return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL);
3624   case ISD::SMAX:
3625     return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL);
3626   case ISD::UMIN:
3627     return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL);
3628   case ISD::UMAX:
3629     return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL);
3630   case ISD::FMINNUM:
3631     return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL);
3632   case ISD::FMAXNUM:
3633     return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL);
3634   case ISD::ABS:
3635     return lowerABS(Op, DAG);
3636   case ISD::CTLZ_ZERO_UNDEF:
3637   case ISD::CTTZ_ZERO_UNDEF:
3638     return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
3639   case ISD::VSELECT:
3640     return lowerFixedLengthVectorSelectToRVV(Op, DAG);
3641   case ISD::FCOPYSIGN:
3642     return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
3643   case ISD::MGATHER:
3644   case ISD::VP_GATHER:
3645     return lowerMaskedGather(Op, DAG);
3646   case ISD::MSCATTER:
3647   case ISD::VP_SCATTER:
3648     return lowerMaskedScatter(Op, DAG);
3649   case ISD::FLT_ROUNDS_:
3650     return lowerGET_ROUNDING(Op, DAG);
3651   case ISD::SET_ROUNDING:
3652     return lowerSET_ROUNDING(Op, DAG);
3653   case ISD::VP_SELECT:
3654     return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
3655   case ISD::VP_MERGE:
3656     return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
3657   case ISD::VP_ADD:
3658     return lowerVPOp(Op, DAG, RISCVISD::ADD_VL);
3659   case ISD::VP_SUB:
3660     return lowerVPOp(Op, DAG, RISCVISD::SUB_VL);
3661   case ISD::VP_MUL:
3662     return lowerVPOp(Op, DAG, RISCVISD::MUL_VL);
3663   case ISD::VP_SDIV:
3664     return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL);
3665   case ISD::VP_UDIV:
3666     return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL);
3667   case ISD::VP_SREM:
3668     return lowerVPOp(Op, DAG, RISCVISD::SREM_VL);
3669   case ISD::VP_UREM:
3670     return lowerVPOp(Op, DAG, RISCVISD::UREM_VL);
3671   case ISD::VP_AND:
3672     return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
3673   case ISD::VP_OR:
3674     return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
3675   case ISD::VP_XOR:
3676     return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
3677   case ISD::VP_ASHR:
3678     return lowerVPOp(Op, DAG, RISCVISD::SRA_VL);
3679   case ISD::VP_LSHR:
3680     return lowerVPOp(Op, DAG, RISCVISD::SRL_VL);
3681   case ISD::VP_SHL:
3682     return lowerVPOp(Op, DAG, RISCVISD::SHL_VL);
3683   case ISD::VP_FADD:
3684     return lowerVPOp(Op, DAG, RISCVISD::FADD_VL);
3685   case ISD::VP_FSUB:
3686     return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL);
3687   case ISD::VP_FMUL:
3688     return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL);
3689   case ISD::VP_FDIV:
3690     return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL);
3691   case ISD::VP_FNEG:
3692     return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
3693   case ISD::VP_FMA:
3694     return lowerVPOp(Op, DAG, RISCVISD::FMA_VL);
3695   }
3696 }
3697 
3698 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
3699                              SelectionDAG &DAG, unsigned Flags) {
3700   return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
3701 }
3702 
3703 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
3704                              SelectionDAG &DAG, unsigned Flags) {
3705   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
3706                                    Flags);
3707 }
3708 
3709 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
3710                              SelectionDAG &DAG, unsigned Flags) {
3711   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
3712                                    N->getOffset(), Flags);
3713 }
3714 
3715 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
3716                              SelectionDAG &DAG, unsigned Flags) {
3717   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
3718 }
3719 
3720 template <class NodeTy>
3721 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3722                                      bool IsLocal) const {
3723   SDLoc DL(N);
3724   EVT Ty = getPointerTy(DAG.getDataLayout());
3725 
3726   if (isPositionIndependent()) {
3727     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3728     if (IsLocal)
3729       // Use PC-relative addressing to access the symbol. This generates the
3730       // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
3731       // %pcrel_lo(auipc)).
3732       return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3733 
3734     // Use PC-relative addressing to access the GOT for this symbol, then load
3735     // the address from the GOT. This generates the pattern (PseudoLA sym),
3736     // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
3737     return SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0);
3738   }
3739 
3740   switch (getTargetMachine().getCodeModel()) {
3741   default:
3742     report_fatal_error("Unsupported code model for lowering");
3743   case CodeModel::Small: {
3744     // Generate a sequence for accessing addresses within the first 2 GiB of
3745     // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
3746     SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
3747     SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
3748     SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3749     return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0);
3750   }
3751   case CodeModel::Medium: {
3752     // Generate a sequence for accessing addresses within any 2GiB range within
3753     // the address space. This generates the pattern (PseudoLLA sym), which
3754     // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
3755     SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
3756     return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0);
3757   }
3758   }
3759 }
3760 
3761 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
3762                                                 SelectionDAG &DAG) const {
3763   SDLoc DL(Op);
3764   EVT Ty = Op.getValueType();
3765   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3766   int64_t Offset = N->getOffset();
3767   MVT XLenVT = Subtarget.getXLenVT();
3768 
3769   const GlobalValue *GV = N->getGlobal();
3770   bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3771   SDValue Addr = getAddr(N, DAG, IsLocal);
3772 
3773   // In order to maximise the opportunity for common subexpression elimination,
3774   // emit a separate ADD node for the global address offset instead of folding
3775   // it in the global address node. Later peephole optimisations may choose to
3776   // fold it back in when profitable.
3777   if (Offset != 0)
3778     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3779                        DAG.getConstant(Offset, DL, XLenVT));
3780   return Addr;
3781 }
3782 
3783 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
3784                                                SelectionDAG &DAG) const {
3785   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
3786 
3787   return getAddr(N, DAG);
3788 }
3789 
3790 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
3791                                                SelectionDAG &DAG) const {
3792   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
3793 
3794   return getAddr(N, DAG);
3795 }
3796 
3797 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
3798                                             SelectionDAG &DAG) const {
3799   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
3800 
3801   return getAddr(N, DAG);
3802 }
3803 
3804 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
3805                                               SelectionDAG &DAG,
3806                                               bool UseGOT) const {
3807   SDLoc DL(N);
3808   EVT Ty = getPointerTy(DAG.getDataLayout());
3809   const GlobalValue *GV = N->getGlobal();
3810   MVT XLenVT = Subtarget.getXLenVT();
3811 
3812   if (UseGOT) {
3813     // Use PC-relative addressing to access the GOT for this TLS symbol, then
3814     // load the address from the GOT and add the thread pointer. This generates
3815     // the pattern (PseudoLA_TLS_IE sym), which expands to
3816     // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
3817     SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3818     SDValue Load =
3819         SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0);
3820 
3821     // Add the thread pointer.
3822     SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3823     return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
3824   }
3825 
3826   // Generate a sequence for accessing the address relative to the thread
3827   // pointer, with the appropriate adjustment for the thread pointer offset.
3828   // This generates the pattern
3829   // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
3830   SDValue AddrHi =
3831       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
3832   SDValue AddrAdd =
3833       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
3834   SDValue AddrLo =
3835       DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
3836 
3837   SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0);
3838   SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
3839   SDValue MNAdd = SDValue(
3840       DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd),
3841       0);
3842   return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0);
3843 }
3844 
3845 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
3846                                                SelectionDAG &DAG) const {
3847   SDLoc DL(N);
3848   EVT Ty = getPointerTy(DAG.getDataLayout());
3849   IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
3850   const GlobalValue *GV = N->getGlobal();
3851 
3852   // Use a PC-relative addressing mode to access the global dynamic GOT address.
3853   // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
3854   // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
3855   SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
3856   SDValue Load =
3857       SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0);
3858 
3859   // Prepare argument list to generate call.
3860   ArgListTy Args;
3861   ArgListEntry Entry;
3862   Entry.Node = Load;
3863   Entry.Ty = CallTy;
3864   Args.push_back(Entry);
3865 
3866   // Setup call to __tls_get_addr.
3867   TargetLowering::CallLoweringInfo CLI(DAG);
3868   CLI.setDebugLoc(DL)
3869       .setChain(DAG.getEntryNode())
3870       .setLibCallee(CallingConv::C, CallTy,
3871                     DAG.getExternalSymbol("__tls_get_addr", Ty),
3872                     std::move(Args));
3873 
3874   return LowerCallTo(CLI).first;
3875 }
3876 
3877 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
3878                                                    SelectionDAG &DAG) const {
3879   SDLoc DL(Op);
3880   EVT Ty = Op.getValueType();
3881   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
3882   int64_t Offset = N->getOffset();
3883   MVT XLenVT = Subtarget.getXLenVT();
3884 
3885   TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
3886 
3887   if (DAG.getMachineFunction().getFunction().getCallingConv() ==
3888       CallingConv::GHC)
3889     report_fatal_error("In GHC calling convention TLS is not supported");
3890 
3891   SDValue Addr;
3892   switch (Model) {
3893   case TLSModel::LocalExec:
3894     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
3895     break;
3896   case TLSModel::InitialExec:
3897     Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
3898     break;
3899   case TLSModel::LocalDynamic:
3900   case TLSModel::GeneralDynamic:
3901     Addr = getDynamicTLSAddr(N, DAG);
3902     break;
3903   }
3904 
3905   // In order to maximise the opportunity for common subexpression elimination,
3906   // emit a separate ADD node for the global address offset instead of folding
3907   // it in the global address node. Later peephole optimisations may choose to
3908   // fold it back in when profitable.
3909   if (Offset != 0)
3910     return DAG.getNode(ISD::ADD, DL, Ty, Addr,
3911                        DAG.getConstant(Offset, DL, XLenVT));
3912   return Addr;
3913 }
3914 
3915 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3916   SDValue CondV = Op.getOperand(0);
3917   SDValue TrueV = Op.getOperand(1);
3918   SDValue FalseV = Op.getOperand(2);
3919   SDLoc DL(Op);
3920   MVT VT = Op.getSimpleValueType();
3921   MVT XLenVT = Subtarget.getXLenVT();
3922 
3923   // Lower vector SELECTs to VSELECTs by splatting the condition.
3924   if (VT.isVector()) {
3925     MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
3926     SDValue CondSplat = VT.isScalableVector()
3927                             ? DAG.getSplatVector(SplatCondVT, DL, CondV)
3928                             : DAG.getSplatBuildVector(SplatCondVT, DL, CondV);
3929     return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
3930   }
3931 
3932   // If the result type is XLenVT and CondV is the output of a SETCC node
3933   // which also operated on XLenVT inputs, then merge the SETCC node into the
3934   // lowered RISCVISD::SELECT_CC to take advantage of the integer
3935   // compare+branch instructions. i.e.:
3936   // (select (setcc lhs, rhs, cc), truev, falsev)
3937   // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
3938   if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC &&
3939       CondV.getOperand(0).getSimpleValueType() == XLenVT) {
3940     SDValue LHS = CondV.getOperand(0);
3941     SDValue RHS = CondV.getOperand(1);
3942     const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2));
3943     ISD::CondCode CCVal = CC->get();
3944 
3945     // Special case for a select of 2 constants that have a diffence of 1.
3946     // Normally this is done by DAGCombine, but if the select is introduced by
3947     // type legalization or op legalization, we miss it. Restricting to SETLT
3948     // case for now because that is what signed saturating add/sub need.
3949     // FIXME: We don't need the condition to be SETLT or even a SETCC,
3950     // but we would probably want to swap the true/false values if the condition
3951     // is SETGE/SETLE to avoid an XORI.
3952     if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
3953         CCVal == ISD::SETLT) {
3954       const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
3955       const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
3956       if (TrueVal - 1 == FalseVal)
3957         return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV);
3958       if (TrueVal + 1 == FalseVal)
3959         return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV);
3960     }
3961 
3962     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3963 
3964     SDValue TargetCC = DAG.getCondCode(CCVal);
3965     SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
3966     return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3967   }
3968 
3969   // Otherwise:
3970   // (select condv, truev, falsev)
3971   // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
3972   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
3973   SDValue SetNE = DAG.getCondCode(ISD::SETNE);
3974 
3975   SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
3976 
3977   return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops);
3978 }
3979 
3980 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
3981   SDValue CondV = Op.getOperand(1);
3982   SDLoc DL(Op);
3983   MVT XLenVT = Subtarget.getXLenVT();
3984 
3985   if (CondV.getOpcode() == ISD::SETCC &&
3986       CondV.getOperand(0).getValueType() == XLenVT) {
3987     SDValue LHS = CondV.getOperand(0);
3988     SDValue RHS = CondV.getOperand(1);
3989     ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
3990 
3991     translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
3992 
3993     SDValue TargetCC = DAG.getCondCode(CCVal);
3994     return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3995                        LHS, RHS, TargetCC, Op.getOperand(2));
3996   }
3997 
3998   return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
3999                      CondV, DAG.getConstant(0, DL, XLenVT),
4000                      DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
4001 }
4002 
4003 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
4004   MachineFunction &MF = DAG.getMachineFunction();
4005   RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
4006 
4007   SDLoc DL(Op);
4008   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
4009                                  getPointerTy(MF.getDataLayout()));
4010 
4011   // vastart just stores the address of the VarArgsFrameIndex slot into the
4012   // memory location argument.
4013   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4014   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
4015                       MachinePointerInfo(SV));
4016 }
4017 
4018 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
4019                                             SelectionDAG &DAG) const {
4020   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4021   MachineFunction &MF = DAG.getMachineFunction();
4022   MachineFrameInfo &MFI = MF.getFrameInfo();
4023   MFI.setFrameAddressIsTaken(true);
4024   Register FrameReg = RI.getFrameRegister(MF);
4025   int XLenInBytes = Subtarget.getXLen() / 8;
4026 
4027   EVT VT = Op.getValueType();
4028   SDLoc DL(Op);
4029   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
4030   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4031   while (Depth--) {
4032     int Offset = -(XLenInBytes * 2);
4033     SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
4034                               DAG.getIntPtrConstant(Offset, DL));
4035     FrameAddr =
4036         DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
4037   }
4038   return FrameAddr;
4039 }
4040 
4041 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
4042                                              SelectionDAG &DAG) const {
4043   const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
4044   MachineFunction &MF = DAG.getMachineFunction();
4045   MachineFrameInfo &MFI = MF.getFrameInfo();
4046   MFI.setReturnAddressIsTaken(true);
4047   MVT XLenVT = Subtarget.getXLenVT();
4048   int XLenInBytes = Subtarget.getXLen() / 8;
4049 
4050   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4051     return SDValue();
4052 
4053   EVT VT = Op.getValueType();
4054   SDLoc DL(Op);
4055   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4056   if (Depth) {
4057     int Off = -XLenInBytes;
4058     SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
4059     SDValue Offset = DAG.getConstant(Off, DL, VT);
4060     return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4061                        DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4062                        MachinePointerInfo());
4063   }
4064 
4065   // Return the value of the return address register, marking it an implicit
4066   // live-in.
4067   Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
4068   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
4069 }
4070 
4071 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
4072                                                  SelectionDAG &DAG) const {
4073   SDLoc DL(Op);
4074   SDValue Lo = Op.getOperand(0);
4075   SDValue Hi = Op.getOperand(1);
4076   SDValue Shamt = Op.getOperand(2);
4077   EVT VT = Lo.getValueType();
4078 
4079   // if Shamt-XLEN < 0: // Shamt < XLEN
4080   //   Lo = Lo << Shamt
4081   //   Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
4082   // else:
4083   //   Lo = 0
4084   //   Hi = Lo << (Shamt-XLEN)
4085 
4086   SDValue Zero = DAG.getConstant(0, DL, VT);
4087   SDValue One = DAG.getConstant(1, DL, VT);
4088   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4089   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4090   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4091   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4092 
4093   SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
4094   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
4095   SDValue ShiftRightLo =
4096       DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
4097   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
4098   SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
4099   SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
4100 
4101   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4102 
4103   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
4104   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4105 
4106   SDValue Parts[2] = {Lo, Hi};
4107   return DAG.getMergeValues(Parts, DL);
4108 }
4109 
4110 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
4111                                                   bool IsSRA) const {
4112   SDLoc DL(Op);
4113   SDValue Lo = Op.getOperand(0);
4114   SDValue Hi = Op.getOperand(1);
4115   SDValue Shamt = Op.getOperand(2);
4116   EVT VT = Lo.getValueType();
4117 
4118   // SRA expansion:
4119   //   if Shamt-XLEN < 0: // Shamt < XLEN
4120   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4121   //     Hi = Hi >>s Shamt
4122   //   else:
4123   //     Lo = Hi >>s (Shamt-XLEN);
4124   //     Hi = Hi >>s (XLEN-1)
4125   //
4126   // SRL expansion:
4127   //   if Shamt-XLEN < 0: // Shamt < XLEN
4128   //     Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
4129   //     Hi = Hi >>u Shamt
4130   //   else:
4131   //     Lo = Hi >>u (Shamt-XLEN);
4132   //     Hi = 0;
4133 
4134   unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
4135 
4136   SDValue Zero = DAG.getConstant(0, DL, VT);
4137   SDValue One = DAG.getConstant(1, DL, VT);
4138   SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
4139   SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
4140   SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
4141   SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1);
4142 
4143   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
4144   SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
4145   SDValue ShiftLeftHi =
4146       DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
4147   SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
4148   SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
4149   SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
4150   SDValue HiFalse =
4151       IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
4152 
4153   SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
4154 
4155   Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
4156   Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
4157 
4158   SDValue Parts[2] = {Lo, Hi};
4159   return DAG.getMergeValues(Parts, DL);
4160 }
4161 
4162 // Lower splats of i1 types to SETCC. For each mask vector type, we have a
4163 // legal equivalently-sized i8 type, so we can use that as a go-between.
4164 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
4165                                                   SelectionDAG &DAG) const {
4166   SDLoc DL(Op);
4167   MVT VT = Op.getSimpleValueType();
4168   SDValue SplatVal = Op.getOperand(0);
4169   // All-zeros or all-ones splats are handled specially.
4170   if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
4171     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4172     return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
4173   }
4174   if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
4175     SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
4176     return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
4177   }
4178   MVT XLenVT = Subtarget.getXLenVT();
4179   assert(SplatVal.getValueType() == XLenVT &&
4180          "Unexpected type for i1 splat value");
4181   MVT InterVT = VT.changeVectorElementType(MVT::i8);
4182   SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
4183                          DAG.getConstant(1, DL, XLenVT));
4184   SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
4185   SDValue Zero = DAG.getConstant(0, DL, InterVT);
4186   return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
4187 }
4188 
4189 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
4190 // illegal (currently only vXi64 RV32).
4191 // FIXME: We could also catch non-constant sign-extended i32 values and lower
4192 // them to VMV_V_X_VL.
4193 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
4194                                                      SelectionDAG &DAG) const {
4195   SDLoc DL(Op);
4196   MVT VecVT = Op.getSimpleValueType();
4197   assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
4198          "Unexpected SPLAT_VECTOR_PARTS lowering");
4199 
4200   assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
4201   SDValue Lo = Op.getOperand(0);
4202   SDValue Hi = Op.getOperand(1);
4203 
4204   if (VecVT.isFixedLengthVector()) {
4205     MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4206     SDLoc DL(Op);
4207     SDValue Mask, VL;
4208     std::tie(Mask, VL) =
4209         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4210 
4211     SDValue Res =
4212         splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
4213     return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
4214   }
4215 
4216   if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
4217     int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
4218     int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
4219     // If Hi constant is all the same sign bit as Lo, lower this as a custom
4220     // node in order to try and match RVV vector/scalar instructions.
4221     if ((LoC >> 31) == HiC)
4222       return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4223                          Lo, DAG.getRegister(RISCV::X0, MVT::i32));
4224   }
4225 
4226   // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
4227   if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
4228       isa<ConstantSDNode>(Hi.getOperand(1)) &&
4229       Hi.getConstantOperandVal(1) == 31)
4230     return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
4231                        DAG.getRegister(RISCV::X0, MVT::i32));
4232 
4233   // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
4234   return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
4235                      DAG.getUNDEF(VecVT), Lo, Hi,
4236                      DAG.getRegister(RISCV::X0, MVT::i32));
4237 }
4238 
4239 // Custom-lower extensions from mask vectors by using a vselect either with 1
4240 // for zero/any-extension or -1 for sign-extension:
4241 //   (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
4242 // Note that any-extension is lowered identically to zero-extension.
4243 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
4244                                                 int64_t ExtTrueVal) const {
4245   SDLoc DL(Op);
4246   MVT VecVT = Op.getSimpleValueType();
4247   SDValue Src = Op.getOperand(0);
4248   // Only custom-lower extensions from mask types
4249   assert(Src.getValueType().isVector() &&
4250          Src.getValueType().getVectorElementType() == MVT::i1);
4251 
4252   MVT XLenVT = Subtarget.getXLenVT();
4253   SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
4254   SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
4255 
4256   if (VecVT.isScalableVector()) {
4257     // Be careful not to introduce illegal scalar types at this stage, and be
4258     // careful also about splatting constants as on RV32, vXi64 SPLAT_VECTOR is
4259     // illegal and must be expanded. Since we know that the constants are
4260     // sign-extended 32-bit values, we use VMV_V_X_VL directly.
4261     bool IsRV32E64 =
4262         !Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64;
4263 
4264     if (!IsRV32E64) {
4265       SplatZero = DAG.getSplatVector(VecVT, DL, SplatZero);
4266       SplatTrueVal = DAG.getSplatVector(VecVT, DL, SplatTrueVal);
4267     } else {
4268       SplatZero =
4269           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4270                       SplatZero, DAG.getRegister(RISCV::X0, XLenVT));
4271       SplatTrueVal =
4272           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
4273                       SplatTrueVal, DAG.getRegister(RISCV::X0, XLenVT));
4274     }
4275 
4276     return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
4277   }
4278 
4279   MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
4280   MVT I1ContainerVT =
4281       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4282 
4283   SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
4284 
4285   SDValue Mask, VL;
4286   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4287 
4288   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4289                           DAG.getUNDEF(ContainerVT), SplatZero, VL);
4290   SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4291                              DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
4292   SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
4293                                SplatTrueVal, SplatZero, VL);
4294 
4295   return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
4296 }
4297 
4298 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
4299     SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
4300   MVT ExtVT = Op.getSimpleValueType();
4301   // Only custom-lower extensions from fixed-length vector types.
4302   if (!ExtVT.isFixedLengthVector())
4303     return Op;
4304   MVT VT = Op.getOperand(0).getSimpleValueType();
4305   // Grab the canonical container type for the extended type. Infer the smaller
4306   // type from that to ensure the same number of vector elements, as we know
4307   // the LMUL will be sufficient to hold the smaller type.
4308   MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
4309   // Get the extended container type manually to ensure the same number of
4310   // vector elements between source and dest.
4311   MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
4312                                      ContainerExtVT.getVectorElementCount());
4313 
4314   SDValue Op1 =
4315       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
4316 
4317   SDLoc DL(Op);
4318   SDValue Mask, VL;
4319   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
4320 
4321   SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
4322 
4323   return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
4324 }
4325 
4326 // Custom-lower truncations from vectors to mask vectors by using a mask and a
4327 // setcc operation:
4328 //   (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
4329 SDValue RISCVTargetLowering::lowerVectorMaskTrunc(SDValue Op,
4330                                                   SelectionDAG &DAG) const {
4331   SDLoc DL(Op);
4332   EVT MaskVT = Op.getValueType();
4333   // Only expect to custom-lower truncations to mask types
4334   assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
4335          "Unexpected type for vector mask lowering");
4336   SDValue Src = Op.getOperand(0);
4337   MVT VecVT = Src.getSimpleValueType();
4338 
4339   // If this is a fixed vector, we need to convert it to a scalable vector.
4340   MVT ContainerVT = VecVT;
4341   if (VecVT.isFixedLengthVector()) {
4342     ContainerVT = getContainerForFixedLengthVector(VecVT);
4343     Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
4344   }
4345 
4346   SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
4347   SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
4348 
4349   SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4350                          DAG.getUNDEF(ContainerVT), SplatOne);
4351   SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
4352                           DAG.getUNDEF(ContainerVT), SplatZero);
4353 
4354   if (VecVT.isScalableVector()) {
4355     SDValue Trunc = DAG.getNode(ISD::AND, DL, VecVT, Src, SplatOne);
4356     return DAG.getSetCC(DL, MaskVT, Trunc, SplatZero, ISD::SETNE);
4357   }
4358 
4359   SDValue Mask, VL;
4360   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4361 
4362   MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
4363   SDValue Trunc =
4364       DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL);
4365   Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero,
4366                       DAG.getCondCode(ISD::SETNE), Mask, VL);
4367   return convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
4368 }
4369 
4370 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
4371 // first position of a vector, and that vector is slid up to the insert index.
4372 // By limiting the active vector length to index+1 and merging with the
4373 // original vector (with an undisturbed tail policy for elements >= VL), we
4374 // achieve the desired result of leaving all elements untouched except the one
4375 // at VL-1, which is replaced with the desired value.
4376 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4377                                                     SelectionDAG &DAG) const {
4378   SDLoc DL(Op);
4379   MVT VecVT = Op.getSimpleValueType();
4380   SDValue Vec = Op.getOperand(0);
4381   SDValue Val = Op.getOperand(1);
4382   SDValue Idx = Op.getOperand(2);
4383 
4384   if (VecVT.getVectorElementType() == MVT::i1) {
4385     // FIXME: For now we just promote to an i8 vector and insert into that,
4386     // but this is probably not optimal.
4387     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4388     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4389     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
4390     return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
4391   }
4392 
4393   MVT ContainerVT = VecVT;
4394   // If the operand is a fixed-length vector, convert to a scalable one.
4395   if (VecVT.isFixedLengthVector()) {
4396     ContainerVT = getContainerForFixedLengthVector(VecVT);
4397     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4398   }
4399 
4400   MVT XLenVT = Subtarget.getXLenVT();
4401 
4402   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
4403   bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
4404   // Even i64-element vectors on RV32 can be lowered without scalar
4405   // legalization if the most-significant 32 bits of the value are not affected
4406   // by the sign-extension of the lower 32 bits.
4407   // TODO: We could also catch sign extensions of a 32-bit value.
4408   if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
4409     const auto *CVal = cast<ConstantSDNode>(Val);
4410     if (isInt<32>(CVal->getSExtValue())) {
4411       IsLegalInsert = true;
4412       Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4413     }
4414   }
4415 
4416   SDValue Mask, VL;
4417   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
4418 
4419   SDValue ValInVec;
4420 
4421   if (IsLegalInsert) {
4422     unsigned Opc =
4423         VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
4424     if (isNullConstant(Idx)) {
4425       Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
4426       if (!VecVT.isFixedLengthVector())
4427         return Vec;
4428       return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
4429     }
4430     ValInVec =
4431         DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL);
4432   } else {
4433     // On RV32, i64-element vectors must be specially handled to place the
4434     // value at element 0, by using two vslide1up instructions in sequence on
4435     // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
4436     // this.
4437     SDValue One = DAG.getConstant(1, DL, XLenVT);
4438     SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
4439     SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
4440     MVT I32ContainerVT =
4441         MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
4442     SDValue I32Mask =
4443         getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
4444     // Limit the active VL to two.
4445     SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
4446     // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied
4447     // undef doesn't obey the earlyclobber constraint. Just splat a zero value.
4448     ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT,
4449                            DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL);
4450     // First slide in the hi value, then the lo in underneath it.
4451     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4452                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
4453                            I32Mask, InsertI64VL);
4454     ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT,
4455                            DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo,
4456                            I32Mask, InsertI64VL);
4457     // Bitcast back to the right container type.
4458     ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
4459   }
4460 
4461   // Now that the value is in a vector, slide it into position.
4462   SDValue InsertVL =
4463       DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
4464   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
4465                                 ValInVec, Idx, Mask, InsertVL);
4466   if (!VecVT.isFixedLengthVector())
4467     return Slideup;
4468   return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
4469 }
4470 
4471 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
4472 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
4473 // types this is done using VMV_X_S to allow us to glean information about the
4474 // sign bits of the result.
4475 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4476                                                      SelectionDAG &DAG) const {
4477   SDLoc DL(Op);
4478   SDValue Idx = Op.getOperand(1);
4479   SDValue Vec = Op.getOperand(0);
4480   EVT EltVT = Op.getValueType();
4481   MVT VecVT = Vec.getSimpleValueType();
4482   MVT XLenVT = Subtarget.getXLenVT();
4483 
4484   if (VecVT.getVectorElementType() == MVT::i1) {
4485     if (VecVT.isFixedLengthVector()) {
4486       unsigned NumElts = VecVT.getVectorNumElements();
4487       if (NumElts >= 8) {
4488         MVT WideEltVT;
4489         unsigned WidenVecLen;
4490         SDValue ExtractElementIdx;
4491         SDValue ExtractBitIdx;
4492         unsigned MaxEEW = Subtarget.getMaxELENForFixedLengthVectors();
4493         MVT LargestEltVT = MVT::getIntegerVT(
4494             std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
4495         if (NumElts <= LargestEltVT.getSizeInBits()) {
4496           assert(isPowerOf2_32(NumElts) &&
4497                  "the number of elements should be power of 2");
4498           WideEltVT = MVT::getIntegerVT(NumElts);
4499           WidenVecLen = 1;
4500           ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
4501           ExtractBitIdx = Idx;
4502         } else {
4503           WideEltVT = LargestEltVT;
4504           WidenVecLen = NumElts / WideEltVT.getSizeInBits();
4505           // extract element index = index / element width
4506           ExtractElementIdx = DAG.getNode(
4507               ISD::SRL, DL, XLenVT, Idx,
4508               DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
4509           // mask bit index = index % element width
4510           ExtractBitIdx = DAG.getNode(
4511               ISD::AND, DL, XLenVT, Idx,
4512               DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
4513         }
4514         MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
4515         Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
4516         SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
4517                                          Vec, ExtractElementIdx);
4518         // Extract the bit from GPR.
4519         SDValue ShiftRight =
4520             DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
4521         return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
4522                            DAG.getConstant(1, DL, XLenVT));
4523       }
4524     }
4525     // Otherwise, promote to an i8 vector and extract from that.
4526     MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
4527     Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
4528     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
4529   }
4530 
4531   // If this is a fixed vector, we need to convert it to a scalable vector.
4532   MVT ContainerVT = VecVT;
4533   if (VecVT.isFixedLengthVector()) {
4534     ContainerVT = getContainerForFixedLengthVector(VecVT);
4535     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
4536   }
4537 
4538   // If the index is 0, the vector is already in the right position.
4539   if (!isNullConstant(Idx)) {
4540     // Use a VL of 1 to avoid processing more elements than we need.
4541     SDValue VL = DAG.getConstant(1, DL, XLenVT);
4542     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4543     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4544     Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
4545                       DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
4546   }
4547 
4548   if (!EltVT.isInteger()) {
4549     // Floating-point extracts are handled in TableGen.
4550     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
4551                        DAG.getConstant(0, DL, XLenVT));
4552   }
4553 
4554   SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
4555   return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
4556 }
4557 
4558 // Some RVV intrinsics may claim that they want an integer operand to be
4559 // promoted or expanded.
4560 static SDValue lowerVectorIntrinsicSplats(SDValue Op, SelectionDAG &DAG,
4561                                           const RISCVSubtarget &Subtarget) {
4562   assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
4563           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
4564          "Unexpected opcode");
4565 
4566   if (!Subtarget.hasVInstructions())
4567     return SDValue();
4568 
4569   bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
4570   unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
4571   SDLoc DL(Op);
4572 
4573   const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
4574       RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
4575   if (!II || !II->hasSplatOperand())
4576     return SDValue();
4577 
4578   unsigned SplatOp = II->SplatOperand + 1 + HasChain;
4579   assert(SplatOp < Op.getNumOperands());
4580 
4581   SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
4582   SDValue &ScalarOp = Operands[SplatOp];
4583   MVT OpVT = ScalarOp.getSimpleValueType();
4584   MVT XLenVT = Subtarget.getXLenVT();
4585 
4586   // If this isn't a scalar, or its type is XLenVT we're done.
4587   if (!OpVT.isScalarInteger() || OpVT == XLenVT)
4588     return SDValue();
4589 
4590   // Simplest case is that the operand needs to be promoted to XLenVT.
4591   if (OpVT.bitsLT(XLenVT)) {
4592     // If the operand is a constant, sign extend to increase our chances
4593     // of being able to use a .vi instruction. ANY_EXTEND would become a
4594     // a zero extend and the simm5 check in isel would fail.
4595     // FIXME: Should we ignore the upper bits in isel instead?
4596     unsigned ExtOpc =
4597         isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
4598     ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
4599     return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4600   }
4601 
4602   // Use the previous operand to get the vXi64 VT. The result might be a mask
4603   // VT for compares. Using the previous operand assumes that the previous
4604   // operand will never have a smaller element size than a scalar operand and
4605   // that a widening operation never uses SEW=64.
4606   // NOTE: If this fails the below assert, we can probably just find the
4607   // element count from any operand or result and use it to construct the VT.
4608   assert(II->SplatOperand > 0 && "Unexpected splat operand!");
4609   MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
4610 
4611   // The more complex case is when the scalar is larger than XLenVT.
4612   assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
4613          VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
4614 
4615   // If this is a sign-extended 32-bit constant, we can truncate it and rely
4616   // on the instruction to sign-extend since SEW>XLEN.
4617   if (auto *CVal = dyn_cast<ConstantSDNode>(ScalarOp)) {
4618     if (isInt<32>(CVal->getSExtValue())) {
4619       ScalarOp = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
4620       return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4621     }
4622   }
4623 
4624   // We need to convert the scalar to a splat vector.
4625   // FIXME: Can we implicitly truncate the scalar if it is known to
4626   // be sign extended?
4627   SDValue VL = getVLOperand(Op);
4628   assert(VL.getValueType() == XLenVT);
4629   ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
4630   return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
4631 }
4632 
4633 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4634                                                      SelectionDAG &DAG) const {
4635   unsigned IntNo = Op.getConstantOperandVal(0);
4636   SDLoc DL(Op);
4637   MVT XLenVT = Subtarget.getXLenVT();
4638 
4639   switch (IntNo) {
4640   default:
4641     break; // Don't custom lower most intrinsics.
4642   case Intrinsic::thread_pointer: {
4643     EVT PtrVT = getPointerTy(DAG.getDataLayout());
4644     return DAG.getRegister(RISCV::X4, PtrVT);
4645   }
4646   case Intrinsic::riscv_orc_b:
4647   case Intrinsic::riscv_brev8: {
4648     // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8.
4649     unsigned Opc =
4650         IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC;
4651     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4652                        DAG.getConstant(7, DL, XLenVT));
4653   }
4654   case Intrinsic::riscv_grev:
4655   case Intrinsic::riscv_gorc: {
4656     unsigned Opc =
4657         IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC;
4658     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4659   }
4660   case Intrinsic::riscv_zip:
4661   case Intrinsic::riscv_unzip: {
4662     // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip.
4663     // For i32 the immdiate is 15. For i64 the immediate is 31.
4664     unsigned Opc =
4665         IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4666     unsigned BitWidth = Op.getValueSizeInBits();
4667     assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width");
4668     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1),
4669                        DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT));
4670   }
4671   case Intrinsic::riscv_shfl:
4672   case Intrinsic::riscv_unshfl: {
4673     unsigned Opc =
4674         IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
4675     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4676   }
4677   case Intrinsic::riscv_bcompress:
4678   case Intrinsic::riscv_bdecompress: {
4679     unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS
4680                                                        : RISCVISD::BDECOMPRESS;
4681     return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2));
4682   }
4683   case Intrinsic::riscv_bfp:
4684     return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1),
4685                        Op.getOperand(2));
4686   case Intrinsic::riscv_fsl:
4687     return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1),
4688                        Op.getOperand(2), Op.getOperand(3));
4689   case Intrinsic::riscv_fsr:
4690     return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1),
4691                        Op.getOperand(2), Op.getOperand(3));
4692   case Intrinsic::riscv_vmv_x_s:
4693     assert(Op.getValueType() == XLenVT && "Unexpected VT!");
4694     return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
4695                        Op.getOperand(1));
4696   case Intrinsic::riscv_vmv_v_x:
4697     return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
4698                             Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
4699                             Subtarget);
4700   case Intrinsic::riscv_vfmv_v_f:
4701     return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
4702                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4703   case Intrinsic::riscv_vmv_s_x: {
4704     SDValue Scalar = Op.getOperand(2);
4705 
4706     if (Scalar.getValueType().bitsLE(XLenVT)) {
4707       Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
4708       return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
4709                          Op.getOperand(1), Scalar, Op.getOperand(3));
4710     }
4711 
4712     assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
4713 
4714     // This is an i64 value that lives in two scalar registers. We have to
4715     // insert this in a convoluted way. First we build vXi64 splat containing
4716     // the/ two values that we assemble using some bit math. Next we'll use
4717     // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
4718     // to merge element 0 from our splat into the source vector.
4719     // FIXME: This is probably not the best way to do this, but it is
4720     // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
4721     // point.
4722     //   sw lo, (a0)
4723     //   sw hi, 4(a0)
4724     //   vlse vX, (a0)
4725     //
4726     //   vid.v      vVid
4727     //   vmseq.vx   mMask, vVid, 0
4728     //   vmerge.vvm vDest, vSrc, vVal, mMask
4729     MVT VT = Op.getSimpleValueType();
4730     SDValue Vec = Op.getOperand(1);
4731     SDValue VL = getVLOperand(Op);
4732 
4733     SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
4734     if (Op.getOperand(1).isUndef())
4735       return SplattedVal;
4736     SDValue SplattedIdx =
4737         DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
4738                     DAG.getConstant(0, DL, MVT::i32), VL);
4739 
4740     MVT MaskVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
4741     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
4742     SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
4743     SDValue SelectCond =
4744         DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx,
4745                     DAG.getCondCode(ISD::SETEQ), Mask, VL);
4746     return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
4747                        Vec, VL);
4748   }
4749   case Intrinsic::riscv_vslide1up:
4750   case Intrinsic::riscv_vslide1down:
4751   case Intrinsic::riscv_vslide1up_mask:
4752   case Intrinsic::riscv_vslide1down_mask: {
4753     // We need to special case these when the scalar is larger than XLen.
4754     unsigned NumOps = Op.getNumOperands();
4755     bool IsMasked = NumOps == 7;
4756     SDValue Scalar = Op.getOperand(3);
4757     if (Scalar.getValueType().bitsLE(XLenVT))
4758       break;
4759 
4760     // Splatting a sign extended constant is fine.
4761     if (auto *CVal = dyn_cast<ConstantSDNode>(Scalar))
4762       if (isInt<32>(CVal->getSExtValue()))
4763         break;
4764 
4765     MVT VT = Op.getSimpleValueType();
4766     assert(VT.getVectorElementType() == MVT::i64 &&
4767            Scalar.getValueType() == MVT::i64 && "Unexpected VTs");
4768 
4769     // Convert the vector source to the equivalent nxvXi32 vector.
4770     MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
4771     SDValue Vec = DAG.getBitcast(I32VT, Op.getOperand(2));
4772 
4773     SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4774                                    DAG.getConstant(0, DL, XLenVT));
4775     SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
4776                                    DAG.getConstant(1, DL, XLenVT));
4777 
4778     // Double the VL since we halved SEW.
4779     SDValue VL = getVLOperand(Op);
4780     SDValue I32VL =
4781         DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
4782 
4783     MVT I32MaskVT = MVT::getVectorVT(MVT::i1, I32VT.getVectorElementCount());
4784     SDValue I32Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, I32MaskVT, VL);
4785 
4786     // Shift the two scalar parts in using SEW=32 slide1up/slide1down
4787     // instructions.
4788     SDValue Passthru = DAG.getBitcast(I32VT, Op.getOperand(1));
4789     if (!IsMasked) {
4790       if (IntNo == Intrinsic::riscv_vslide1up) {
4791         Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4792                           ScalarHi, I32Mask, I32VL);
4793         Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
4794                           ScalarLo, I32Mask, I32VL);
4795       } else {
4796         Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4797                           ScalarLo, I32Mask, I32VL);
4798         Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
4799                           ScalarHi, I32Mask, I32VL);
4800       }
4801     } else {
4802       // TODO Those VSLIDE1 could be TAMA because we use vmerge to select
4803       // maskedoff
4804       SDValue Undef = DAG.getUNDEF(I32VT);
4805       if (IntNo == Intrinsic::riscv_vslide1up_mask) {
4806         Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Undef, Vec,
4807                           ScalarHi, I32Mask, I32VL);
4808         Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Undef, Vec,
4809                           ScalarLo, I32Mask, I32VL);
4810       } else {
4811         Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Undef, Vec,
4812                           ScalarLo, I32Mask, I32VL);
4813         Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Undef, Vec,
4814                           ScalarHi, I32Mask, I32VL);
4815       }
4816     }
4817 
4818     // Convert back to nxvXi64.
4819     Vec = DAG.getBitcast(VT, Vec);
4820 
4821     if (!IsMasked)
4822       return Vec;
4823     // Apply mask after the operation.
4824     SDValue Mask = Op.getOperand(NumOps - 3);
4825     SDValue MaskedOff = Op.getOperand(1);
4826     // Assume Policy operand is the last operand.
4827     uint64_t Policy = Op.getConstantOperandVal(NumOps - 1);
4828     // We don't need to select maskedoff if it's undef.
4829     if (MaskedOff.isUndef())
4830       return Vec;
4831     // TAMU
4832     if (Policy == RISCVII::TAIL_AGNOSTIC)
4833       return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
4834                          VL);
4835     // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
4836     // It's fine because vmerge does not care mask policy.
4837     return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, VL);
4838   }
4839   }
4840 
4841   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4842 }
4843 
4844 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4845                                                     SelectionDAG &DAG) const {
4846   unsigned IntNo = Op.getConstantOperandVal(1);
4847   switch (IntNo) {
4848   default:
4849     break;
4850   case Intrinsic::riscv_masked_strided_load: {
4851     SDLoc DL(Op);
4852     MVT XLenVT = Subtarget.getXLenVT();
4853 
4854     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4855     // the selection of the masked intrinsics doesn't do this for us.
4856     SDValue Mask = Op.getOperand(5);
4857     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4858 
4859     MVT VT = Op->getSimpleValueType(0);
4860     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4861 
4862     SDValue PassThru = Op.getOperand(2);
4863     if (!IsUnmasked) {
4864       MVT MaskVT =
4865           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4866       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4867       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
4868     }
4869 
4870     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4871 
4872     SDValue IntID = DAG.getTargetConstant(
4873         IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
4874         XLenVT);
4875 
4876     auto *Load = cast<MemIntrinsicSDNode>(Op);
4877     SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
4878     if (IsUnmasked)
4879       Ops.push_back(DAG.getUNDEF(ContainerVT));
4880     else
4881       Ops.push_back(PassThru);
4882     Ops.push_back(Op.getOperand(3)); // Ptr
4883     Ops.push_back(Op.getOperand(4)); // Stride
4884     if (!IsUnmasked)
4885       Ops.push_back(Mask);
4886     Ops.push_back(VL);
4887     if (!IsUnmasked) {
4888       SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
4889       Ops.push_back(Policy);
4890     }
4891 
4892     SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
4893     SDValue Result =
4894         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
4895                                 Load->getMemoryVT(), Load->getMemOperand());
4896     SDValue Chain = Result.getValue(1);
4897     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
4898     return DAG.getMergeValues({Result, Chain}, DL);
4899   }
4900   }
4901 
4902   return lowerVectorIntrinsicSplats(Op, DAG, Subtarget);
4903 }
4904 
4905 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
4906                                                  SelectionDAG &DAG) const {
4907   unsigned IntNo = Op.getConstantOperandVal(1);
4908   switch (IntNo) {
4909   default:
4910     break;
4911   case Intrinsic::riscv_masked_strided_store: {
4912     SDLoc DL(Op);
4913     MVT XLenVT = Subtarget.getXLenVT();
4914 
4915     // If the mask is known to be all ones, optimize to an unmasked intrinsic;
4916     // the selection of the masked intrinsics doesn't do this for us.
4917     SDValue Mask = Op.getOperand(5);
4918     bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
4919 
4920     SDValue Val = Op.getOperand(2);
4921     MVT VT = Val.getSimpleValueType();
4922     MVT ContainerVT = getContainerForFixedLengthVector(VT);
4923 
4924     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
4925     if (!IsUnmasked) {
4926       MVT MaskVT =
4927           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
4928       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
4929     }
4930 
4931     SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT);
4932 
4933     SDValue IntID = DAG.getTargetConstant(
4934         IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
4935         XLenVT);
4936 
4937     auto *Store = cast<MemIntrinsicSDNode>(Op);
4938     SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
4939     Ops.push_back(Val);
4940     Ops.push_back(Op.getOperand(3)); // Ptr
4941     Ops.push_back(Op.getOperand(4)); // Stride
4942     if (!IsUnmasked)
4943       Ops.push_back(Mask);
4944     Ops.push_back(VL);
4945 
4946     return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
4947                                    Ops, Store->getMemoryVT(),
4948                                    Store->getMemOperand());
4949   }
4950   }
4951 
4952   return SDValue();
4953 }
4954 
4955 static MVT getLMUL1VT(MVT VT) {
4956   assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
4957          "Unexpected vector MVT");
4958   return MVT::getScalableVectorVT(
4959       VT.getVectorElementType(),
4960       RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
4961 }
4962 
4963 static unsigned getRVVReductionOp(unsigned ISDOpcode) {
4964   switch (ISDOpcode) {
4965   default:
4966     llvm_unreachable("Unhandled reduction");
4967   case ISD::VECREDUCE_ADD:
4968     return RISCVISD::VECREDUCE_ADD_VL;
4969   case ISD::VECREDUCE_UMAX:
4970     return RISCVISD::VECREDUCE_UMAX_VL;
4971   case ISD::VECREDUCE_SMAX:
4972     return RISCVISD::VECREDUCE_SMAX_VL;
4973   case ISD::VECREDUCE_UMIN:
4974     return RISCVISD::VECREDUCE_UMIN_VL;
4975   case ISD::VECREDUCE_SMIN:
4976     return RISCVISD::VECREDUCE_SMIN_VL;
4977   case ISD::VECREDUCE_AND:
4978     return RISCVISD::VECREDUCE_AND_VL;
4979   case ISD::VECREDUCE_OR:
4980     return RISCVISD::VECREDUCE_OR_VL;
4981   case ISD::VECREDUCE_XOR:
4982     return RISCVISD::VECREDUCE_XOR_VL;
4983   }
4984 }
4985 
4986 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
4987                                                          SelectionDAG &DAG,
4988                                                          bool IsVP) const {
4989   SDLoc DL(Op);
4990   SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
4991   MVT VecVT = Vec.getSimpleValueType();
4992   assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
4993           Op.getOpcode() == ISD::VECREDUCE_OR ||
4994           Op.getOpcode() == ISD::VECREDUCE_XOR ||
4995           Op.getOpcode() == ISD::VP_REDUCE_AND ||
4996           Op.getOpcode() == ISD::VP_REDUCE_OR ||
4997           Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
4998          "Unexpected reduction lowering");
4999 
5000   MVT XLenVT = Subtarget.getXLenVT();
5001   assert(Op.getValueType() == XLenVT &&
5002          "Expected reduction output to be legalized to XLenVT");
5003 
5004   MVT ContainerVT = VecVT;
5005   if (VecVT.isFixedLengthVector()) {
5006     ContainerVT = getContainerForFixedLengthVector(VecVT);
5007     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5008   }
5009 
5010   SDValue Mask, VL;
5011   if (IsVP) {
5012     Mask = Op.getOperand(2);
5013     VL = Op.getOperand(3);
5014   } else {
5015     std::tie(Mask, VL) =
5016         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5017   }
5018 
5019   unsigned BaseOpc;
5020   ISD::CondCode CC;
5021   SDValue Zero = DAG.getConstant(0, DL, XLenVT);
5022 
5023   switch (Op.getOpcode()) {
5024   default:
5025     llvm_unreachable("Unhandled reduction");
5026   case ISD::VECREDUCE_AND:
5027   case ISD::VP_REDUCE_AND: {
5028     // vcpop ~x == 0
5029     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
5030     Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
5031     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5032     CC = ISD::SETEQ;
5033     BaseOpc = ISD::AND;
5034     break;
5035   }
5036   case ISD::VECREDUCE_OR:
5037   case ISD::VP_REDUCE_OR:
5038     // vcpop x != 0
5039     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5040     CC = ISD::SETNE;
5041     BaseOpc = ISD::OR;
5042     break;
5043   case ISD::VECREDUCE_XOR:
5044   case ISD::VP_REDUCE_XOR: {
5045     // ((vcpop x) & 1) != 0
5046     SDValue One = DAG.getConstant(1, DL, XLenVT);
5047     Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
5048     Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
5049     CC = ISD::SETNE;
5050     BaseOpc = ISD::XOR;
5051     break;
5052   }
5053   }
5054 
5055   SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
5056 
5057   if (!IsVP)
5058     return SetCC;
5059 
5060   // Now include the start value in the operation.
5061   // Note that we must return the start value when no elements are operated
5062   // upon. The vcpop instructions we've emitted in each case above will return
5063   // 0 for an inactive vector, and so we've already received the neutral value:
5064   // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
5065   // can simply include the start value.
5066   return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
5067 }
5068 
5069 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
5070                                             SelectionDAG &DAG) const {
5071   SDLoc DL(Op);
5072   SDValue Vec = Op.getOperand(0);
5073   EVT VecEVT = Vec.getValueType();
5074 
5075   unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
5076 
5077   // Due to ordering in legalize types we may have a vector type that needs to
5078   // be split. Do that manually so we can get down to a legal type.
5079   while (getTypeAction(*DAG.getContext(), VecEVT) ==
5080          TargetLowering::TypeSplitVector) {
5081     SDValue Lo, Hi;
5082     std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL);
5083     VecEVT = Lo.getValueType();
5084     Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
5085   }
5086 
5087   // TODO: The type may need to be widened rather than split. Or widened before
5088   // it can be split.
5089   if (!isTypeLegal(VecEVT))
5090     return SDValue();
5091 
5092   MVT VecVT = VecEVT.getSimpleVT();
5093   MVT VecEltVT = VecVT.getVectorElementType();
5094   unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
5095 
5096   MVT ContainerVT = VecVT;
5097   if (VecVT.isFixedLengthVector()) {
5098     ContainerVT = getContainerForFixedLengthVector(VecVT);
5099     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5100   }
5101 
5102   MVT M1VT = getLMUL1VT(ContainerVT);
5103   MVT XLenVT = Subtarget.getXLenVT();
5104 
5105   SDValue Mask, VL;
5106   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5107 
5108   SDValue NeutralElem =
5109       DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
5110   SDValue IdentitySplat =
5111       lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT),
5112                        M1VT, DL, DAG, Subtarget);
5113   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec,
5114                                   IdentitySplat, Mask, VL);
5115   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5116                              DAG.getConstant(0, DL, XLenVT));
5117   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5118 }
5119 
5120 // Given a reduction op, this function returns the matching reduction opcode,
5121 // the vector SDValue and the scalar SDValue required to lower this to a
5122 // RISCVISD node.
5123 static std::tuple<unsigned, SDValue, SDValue>
5124 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
5125   SDLoc DL(Op);
5126   auto Flags = Op->getFlags();
5127   unsigned Opcode = Op.getOpcode();
5128   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
5129   switch (Opcode) {
5130   default:
5131     llvm_unreachable("Unhandled reduction");
5132   case ISD::VECREDUCE_FADD: {
5133     // Use positive zero if we can. It is cheaper to materialize.
5134     SDValue Zero =
5135         DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
5136     return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
5137   }
5138   case ISD::VECREDUCE_SEQ_FADD:
5139     return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
5140                            Op.getOperand(0));
5141   case ISD::VECREDUCE_FMIN:
5142     return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
5143                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5144   case ISD::VECREDUCE_FMAX:
5145     return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
5146                            DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
5147   }
5148 }
5149 
5150 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
5151                                               SelectionDAG &DAG) const {
5152   SDLoc DL(Op);
5153   MVT VecEltVT = Op.getSimpleValueType();
5154 
5155   unsigned RVVOpcode;
5156   SDValue VectorVal, ScalarVal;
5157   std::tie(RVVOpcode, VectorVal, ScalarVal) =
5158       getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
5159   MVT VecVT = VectorVal.getSimpleValueType();
5160 
5161   MVT ContainerVT = VecVT;
5162   if (VecVT.isFixedLengthVector()) {
5163     ContainerVT = getContainerForFixedLengthVector(VecVT);
5164     VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
5165   }
5166 
5167   MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType());
5168   MVT XLenVT = Subtarget.getXLenVT();
5169 
5170   SDValue Mask, VL;
5171   std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
5172 
5173   SDValue ScalarSplat =
5174       lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT),
5175                        M1VT, DL, DAG, Subtarget);
5176   SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT),
5177                                   VectorVal, ScalarSplat, Mask, VL);
5178   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction,
5179                      DAG.getConstant(0, DL, XLenVT));
5180 }
5181 
5182 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
5183   switch (ISDOpcode) {
5184   default:
5185     llvm_unreachable("Unhandled reduction");
5186   case ISD::VP_REDUCE_ADD:
5187     return RISCVISD::VECREDUCE_ADD_VL;
5188   case ISD::VP_REDUCE_UMAX:
5189     return RISCVISD::VECREDUCE_UMAX_VL;
5190   case ISD::VP_REDUCE_SMAX:
5191     return RISCVISD::VECREDUCE_SMAX_VL;
5192   case ISD::VP_REDUCE_UMIN:
5193     return RISCVISD::VECREDUCE_UMIN_VL;
5194   case ISD::VP_REDUCE_SMIN:
5195     return RISCVISD::VECREDUCE_SMIN_VL;
5196   case ISD::VP_REDUCE_AND:
5197     return RISCVISD::VECREDUCE_AND_VL;
5198   case ISD::VP_REDUCE_OR:
5199     return RISCVISD::VECREDUCE_OR_VL;
5200   case ISD::VP_REDUCE_XOR:
5201     return RISCVISD::VECREDUCE_XOR_VL;
5202   case ISD::VP_REDUCE_FADD:
5203     return RISCVISD::VECREDUCE_FADD_VL;
5204   case ISD::VP_REDUCE_SEQ_FADD:
5205     return RISCVISD::VECREDUCE_SEQ_FADD_VL;
5206   case ISD::VP_REDUCE_FMAX:
5207     return RISCVISD::VECREDUCE_FMAX_VL;
5208   case ISD::VP_REDUCE_FMIN:
5209     return RISCVISD::VECREDUCE_FMIN_VL;
5210   }
5211 }
5212 
5213 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
5214                                            SelectionDAG &DAG) const {
5215   SDLoc DL(Op);
5216   SDValue Vec = Op.getOperand(1);
5217   EVT VecEVT = Vec.getValueType();
5218 
5219   // TODO: The type may need to be widened rather than split. Or widened before
5220   // it can be split.
5221   if (!isTypeLegal(VecEVT))
5222     return SDValue();
5223 
5224   MVT VecVT = VecEVT.getSimpleVT();
5225   MVT VecEltVT = VecVT.getVectorElementType();
5226   unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
5227 
5228   MVT ContainerVT = VecVT;
5229   if (VecVT.isFixedLengthVector()) {
5230     ContainerVT = getContainerForFixedLengthVector(VecVT);
5231     Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5232   }
5233 
5234   SDValue VL = Op.getOperand(3);
5235   SDValue Mask = Op.getOperand(2);
5236 
5237   MVT M1VT = getLMUL1VT(ContainerVT);
5238   MVT XLenVT = Subtarget.getXLenVT();
5239   MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT;
5240 
5241   SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0),
5242                                         DAG.getConstant(1, DL, XLenVT), M1VT,
5243                                         DL, DAG, Subtarget);
5244   SDValue Reduction =
5245       DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL);
5246   SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
5247                              DAG.getConstant(0, DL, XLenVT));
5248   if (!VecVT.isInteger())
5249     return Elt0;
5250   return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType());
5251 }
5252 
5253 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5254                                                    SelectionDAG &DAG) const {
5255   SDValue Vec = Op.getOperand(0);
5256   SDValue SubVec = Op.getOperand(1);
5257   MVT VecVT = Vec.getSimpleValueType();
5258   MVT SubVecVT = SubVec.getSimpleValueType();
5259 
5260   SDLoc DL(Op);
5261   MVT XLenVT = Subtarget.getXLenVT();
5262   unsigned OrigIdx = Op.getConstantOperandVal(2);
5263   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5264 
5265   // We don't have the ability to slide mask vectors up indexed by their i1
5266   // elements; the smallest we can do is i8. Often we are able to bitcast to
5267   // equivalent i8 vectors. Note that when inserting a fixed-length vector
5268   // into a scalable one, we might not necessarily have enough scalable
5269   // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
5270   if (SubVecVT.getVectorElementType() == MVT::i1 &&
5271       (OrigIdx != 0 || !Vec.isUndef())) {
5272     if (VecVT.getVectorMinNumElements() >= 8 &&
5273         SubVecVT.getVectorMinNumElements() >= 8) {
5274       assert(OrigIdx % 8 == 0 && "Invalid index");
5275       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5276              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5277              "Unexpected mask vector lowering");
5278       OrigIdx /= 8;
5279       SubVecVT =
5280           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5281                            SubVecVT.isScalableVector());
5282       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5283                                VecVT.isScalableVector());
5284       Vec = DAG.getBitcast(VecVT, Vec);
5285       SubVec = DAG.getBitcast(SubVecVT, SubVec);
5286     } else {
5287       // We can't slide this mask vector up indexed by its i1 elements.
5288       // This poses a problem when we wish to insert a scalable vector which
5289       // can't be re-expressed as a larger type. Just choose the slow path and
5290       // extend to a larger type, then truncate back down.
5291       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5292       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5293       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5294       SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
5295       Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
5296                         Op.getOperand(2));
5297       SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
5298       return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
5299     }
5300   }
5301 
5302   // If the subvector vector is a fixed-length type, we cannot use subregister
5303   // manipulation to simplify the codegen; we don't know which register of a
5304   // LMUL group contains the specific subvector as we only know the minimum
5305   // register size. Therefore we must slide the vector group up the full
5306   // amount.
5307   if (SubVecVT.isFixedLengthVector()) {
5308     if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
5309       return Op;
5310     MVT ContainerVT = VecVT;
5311     if (VecVT.isFixedLengthVector()) {
5312       ContainerVT = getContainerForFixedLengthVector(VecVT);
5313       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5314     }
5315     SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
5316                          DAG.getUNDEF(ContainerVT), SubVec,
5317                          DAG.getConstant(0, DL, XLenVT));
5318     if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
5319       SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
5320       return DAG.getBitcast(Op.getValueType(), SubVec);
5321     }
5322     SDValue Mask =
5323         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5324     // Set the vector length to only the number of elements we care about. Note
5325     // that for slideup this includes the offset.
5326     SDValue VL =
5327         DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT);
5328     SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5329     SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec,
5330                                   SubVec, SlideupAmt, Mask, VL);
5331     if (VecVT.isFixedLengthVector())
5332       Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
5333     return DAG.getBitcast(Op.getValueType(), Slideup);
5334   }
5335 
5336   unsigned SubRegIdx, RemIdx;
5337   std::tie(SubRegIdx, RemIdx) =
5338       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5339           VecVT, SubVecVT, OrigIdx, TRI);
5340 
5341   RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
5342   bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
5343                          SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
5344                          SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
5345 
5346   // 1. If the Idx has been completely eliminated and this subvector's size is
5347   // a vector register or a multiple thereof, or the surrounding elements are
5348   // undef, then this is a subvector insert which naturally aligns to a vector
5349   // register. These can easily be handled using subregister manipulation.
5350   // 2. If the subvector is smaller than a vector register, then the insertion
5351   // must preserve the undisturbed elements of the register. We do this by
5352   // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
5353   // (which resolves to a subregister copy), performing a VSLIDEUP to place the
5354   // subvector within the vector register, and an INSERT_SUBVECTOR of that
5355   // LMUL=1 type back into the larger vector (resolving to another subregister
5356   // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
5357   // to avoid allocating a large register group to hold our subvector.
5358   if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
5359     return Op;
5360 
5361   // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
5362   // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
5363   // (in our case undisturbed). This means we can set up a subvector insertion
5364   // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
5365   // size of the subvector.
5366   MVT InterSubVT = VecVT;
5367   SDValue AlignedExtract = Vec;
5368   unsigned AlignedIdx = OrigIdx - RemIdx;
5369   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5370     InterSubVT = getLMUL1VT(VecVT);
5371     // Extract a subvector equal to the nearest full vector register type. This
5372     // should resolve to a EXTRACT_SUBREG instruction.
5373     AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5374                                  DAG.getConstant(AlignedIdx, DL, XLenVT));
5375   }
5376 
5377   SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5378   // For scalable vectors this must be further multiplied by vscale.
5379   SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
5380 
5381   SDValue Mask, VL;
5382   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5383 
5384   // Construct the vector length corresponding to RemIdx + length(SubVecVT).
5385   VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
5386   VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
5387   VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
5388 
5389   SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
5390                        DAG.getUNDEF(InterSubVT), SubVec,
5391                        DAG.getConstant(0, DL, XLenVT));
5392 
5393   SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT,
5394                                 AlignedExtract, SubVec, SlideupAmt, Mask, VL);
5395 
5396   // If required, insert this subvector back into the correct vector register.
5397   // This should resolve to an INSERT_SUBREG instruction.
5398   if (VecVT.bitsGT(InterSubVT))
5399     Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
5400                           DAG.getConstant(AlignedIdx, DL, XLenVT));
5401 
5402   // We might have bitcast from a mask type: cast back to the original type if
5403   // required.
5404   return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
5405 }
5406 
5407 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
5408                                                     SelectionDAG &DAG) const {
5409   SDValue Vec = Op.getOperand(0);
5410   MVT SubVecVT = Op.getSimpleValueType();
5411   MVT VecVT = Vec.getSimpleValueType();
5412 
5413   SDLoc DL(Op);
5414   MVT XLenVT = Subtarget.getXLenVT();
5415   unsigned OrigIdx = Op.getConstantOperandVal(1);
5416   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
5417 
5418   // We don't have the ability to slide mask vectors down indexed by their i1
5419   // elements; the smallest we can do is i8. Often we are able to bitcast to
5420   // equivalent i8 vectors. Note that when extracting a fixed-length vector
5421   // from a scalable one, we might not necessarily have enough scalable
5422   // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
5423   if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
5424     if (VecVT.getVectorMinNumElements() >= 8 &&
5425         SubVecVT.getVectorMinNumElements() >= 8) {
5426       assert(OrigIdx % 8 == 0 && "Invalid index");
5427       assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
5428              SubVecVT.getVectorMinNumElements() % 8 == 0 &&
5429              "Unexpected mask vector lowering");
5430       OrigIdx /= 8;
5431       SubVecVT =
5432           MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
5433                            SubVecVT.isScalableVector());
5434       VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
5435                                VecVT.isScalableVector());
5436       Vec = DAG.getBitcast(VecVT, Vec);
5437     } else {
5438       // We can't slide this mask vector down, indexed by its i1 elements.
5439       // This poses a problem when we wish to extract a scalable vector which
5440       // can't be re-expressed as a larger type. Just choose the slow path and
5441       // extend to a larger type, then truncate back down.
5442       // TODO: We could probably improve this when extracting certain fixed
5443       // from fixed, where we can extract as i8 and shift the correct element
5444       // right to reach the desired subvector?
5445       MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
5446       MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
5447       Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
5448       Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
5449                         Op.getOperand(1));
5450       SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
5451       return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
5452     }
5453   }
5454 
5455   // If the subvector vector is a fixed-length type, we cannot use subregister
5456   // manipulation to simplify the codegen; we don't know which register of a
5457   // LMUL group contains the specific subvector as we only know the minimum
5458   // register size. Therefore we must slide the vector group down the full
5459   // amount.
5460   if (SubVecVT.isFixedLengthVector()) {
5461     // With an index of 0 this is a cast-like subvector, which can be performed
5462     // with subregister operations.
5463     if (OrigIdx == 0)
5464       return Op;
5465     MVT ContainerVT = VecVT;
5466     if (VecVT.isFixedLengthVector()) {
5467       ContainerVT = getContainerForFixedLengthVector(VecVT);
5468       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
5469     }
5470     SDValue Mask =
5471         getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
5472     // Set the vector length to only the number of elements we care about. This
5473     // avoids sliding down elements we're going to discard straight away.
5474     SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT);
5475     SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
5476     SDValue Slidedown =
5477         DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
5478                     DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
5479     // Now we can use a cast-like subvector extract to get the result.
5480     Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5481                             DAG.getConstant(0, DL, XLenVT));
5482     return DAG.getBitcast(Op.getValueType(), Slidedown);
5483   }
5484 
5485   unsigned SubRegIdx, RemIdx;
5486   std::tie(SubRegIdx, RemIdx) =
5487       RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
5488           VecVT, SubVecVT, OrigIdx, TRI);
5489 
5490   // If the Idx has been completely eliminated then this is a subvector extract
5491   // which naturally aligns to a vector register. These can easily be handled
5492   // using subregister manipulation.
5493   if (RemIdx == 0)
5494     return Op;
5495 
5496   // Else we must shift our vector register directly to extract the subvector.
5497   // Do this using VSLIDEDOWN.
5498 
5499   // If the vector type is an LMUL-group type, extract a subvector equal to the
5500   // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
5501   // instruction.
5502   MVT InterSubVT = VecVT;
5503   if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
5504     InterSubVT = getLMUL1VT(VecVT);
5505     Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
5506                       DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
5507   }
5508 
5509   // Slide this vector register down by the desired number of elements in order
5510   // to place the desired subvector starting at element 0.
5511   SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
5512   // For scalable vectors this must be further multiplied by vscale.
5513   SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
5514 
5515   SDValue Mask, VL;
5516   std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
5517   SDValue Slidedown =
5518       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT,
5519                   DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL);
5520 
5521   // Now the vector is in the right position, extract our final subvector. This
5522   // should resolve to a COPY.
5523   Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
5524                           DAG.getConstant(0, DL, XLenVT));
5525 
5526   // We might have bitcast from a mask type: cast back to the original type if
5527   // required.
5528   return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
5529 }
5530 
5531 // Lower step_vector to the vid instruction. Any non-identity step value must
5532 // be accounted for my manual expansion.
5533 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
5534                                               SelectionDAG &DAG) const {
5535   SDLoc DL(Op);
5536   MVT VT = Op.getSimpleValueType();
5537   MVT XLenVT = Subtarget.getXLenVT();
5538   SDValue Mask, VL;
5539   std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
5540   SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
5541   uint64_t StepValImm = Op.getConstantOperandVal(0);
5542   if (StepValImm != 1) {
5543     if (isPowerOf2_64(StepValImm)) {
5544       SDValue StepVal =
5545           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
5546                       DAG.getConstant(Log2_64(StepValImm), DL, XLenVT));
5547       StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
5548     } else {
5549       SDValue StepVal = lowerScalarSplat(
5550           SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
5551           VL, VT, DL, DAG, Subtarget);
5552       StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
5553     }
5554   }
5555   return StepVec;
5556 }
5557 
5558 // Implement vector_reverse using vrgather.vv with indices determined by
5559 // subtracting the id of each element from (VLMAX-1). This will convert
5560 // the indices like so:
5561 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
5562 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
5563 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
5564                                                  SelectionDAG &DAG) const {
5565   SDLoc DL(Op);
5566   MVT VecVT = Op.getSimpleValueType();
5567   unsigned EltSize = VecVT.getScalarSizeInBits();
5568   unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
5569 
5570   unsigned MaxVLMAX = 0;
5571   unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits();
5572   if (VectorBitsMax != 0)
5573     MaxVLMAX = ((VectorBitsMax / EltSize) * MinSize) / RISCV::RVVBitsPerBlock;
5574 
5575   unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
5576   MVT IntVT = VecVT.changeVectorElementTypeToInteger();
5577 
5578   // If this is SEW=8 and VLMAX is unknown or more than 256, we need
5579   // to use vrgatherei16.vv.
5580   // TODO: It's also possible to use vrgatherei16.vv for other types to
5581   // decrease register width for the index calculation.
5582   if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) {
5583     // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
5584     // Reverse each half, then reassemble them in reverse order.
5585     // NOTE: It's also possible that after splitting that VLMAX no longer
5586     // requires vrgatherei16.vv.
5587     if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
5588       SDValue Lo, Hi;
5589       std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
5590       EVT LoVT, HiVT;
5591       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT);
5592       Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
5593       Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
5594       // Reassemble the low and high pieces reversed.
5595       // FIXME: This is a CONCAT_VECTORS.
5596       SDValue Res =
5597           DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
5598                       DAG.getIntPtrConstant(0, DL));
5599       return DAG.getNode(
5600           ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
5601           DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
5602     }
5603 
5604     // Just promote the int type to i16 which will double the LMUL.
5605     IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
5606     GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
5607   }
5608 
5609   MVT XLenVT = Subtarget.getXLenVT();
5610   SDValue Mask, VL;
5611   std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
5612 
5613   // Calculate VLMAX-1 for the desired SEW.
5614   unsigned MinElts = VecVT.getVectorMinNumElements();
5615   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5616                               DAG.getConstant(MinElts, DL, XLenVT));
5617   SDValue VLMinus1 =
5618       DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
5619 
5620   // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
5621   bool IsRV32E64 =
5622       !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
5623   SDValue SplatVL;
5624   if (!IsRV32E64)
5625     SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
5626   else
5627     SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
5628                           VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
5629 
5630   SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
5631   SDValue Indices =
5632       DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL);
5633 
5634   return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL);
5635 }
5636 
5637 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
5638                                                 SelectionDAG &DAG) const {
5639   SDLoc DL(Op);
5640   SDValue V1 = Op.getOperand(0);
5641   SDValue V2 = Op.getOperand(1);
5642   MVT XLenVT = Subtarget.getXLenVT();
5643   MVT VecVT = Op.getSimpleValueType();
5644 
5645   unsigned MinElts = VecVT.getVectorMinNumElements();
5646   SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
5647                               DAG.getConstant(MinElts, DL, XLenVT));
5648 
5649   int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
5650   SDValue DownOffset, UpOffset;
5651   if (ImmValue >= 0) {
5652     // The operand is a TargetConstant, we need to rebuild it as a regular
5653     // constant.
5654     DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
5655     UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
5656   } else {
5657     // The operand is a TargetConstant, we need to rebuild it as a regular
5658     // constant rather than negating the original operand.
5659     UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
5660     DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
5661   }
5662 
5663   MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
5664   SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VLMax);
5665 
5666   SDValue SlideDown =
5667       DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1,
5668                   DownOffset, TrueMask, UpOffset);
5669   return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset,
5670                      TrueMask,
5671                      DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT));
5672 }
5673 
5674 SDValue
5675 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
5676                                                      SelectionDAG &DAG) const {
5677   SDLoc DL(Op);
5678   auto *Load = cast<LoadSDNode>(Op);
5679 
5680   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5681                                         Load->getMemoryVT(),
5682                                         *Load->getMemOperand()) &&
5683          "Expecting a correctly-aligned load");
5684 
5685   MVT VT = Op.getSimpleValueType();
5686   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5687 
5688   SDValue VL =
5689       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5690 
5691   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5692   SDValue NewLoad = DAG.getMemIntrinsicNode(
5693       RISCVISD::VLE_VL, DL, VTs, {Load->getChain(), Load->getBasePtr(), VL},
5694       Load->getMemoryVT(), Load->getMemOperand());
5695 
5696   SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
5697   return DAG.getMergeValues({Result, Load->getChain()}, DL);
5698 }
5699 
5700 SDValue
5701 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
5702                                                       SelectionDAG &DAG) const {
5703   SDLoc DL(Op);
5704   auto *Store = cast<StoreSDNode>(Op);
5705 
5706   assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
5707                                         Store->getMemoryVT(),
5708                                         *Store->getMemOperand()) &&
5709          "Expecting a correctly-aligned store");
5710 
5711   SDValue StoreVal = Store->getValue();
5712   MVT VT = StoreVal.getSimpleValueType();
5713 
5714   // If the size less than a byte, we need to pad with zeros to make a byte.
5715   if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
5716     VT = MVT::v8i1;
5717     StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
5718                            DAG.getConstant(0, DL, VT), StoreVal,
5719                            DAG.getIntPtrConstant(0, DL));
5720   }
5721 
5722   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5723 
5724   SDValue VL =
5725       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5726 
5727   SDValue NewValue =
5728       convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
5729   return DAG.getMemIntrinsicNode(
5730       RISCVISD::VSE_VL, DL, DAG.getVTList(MVT::Other),
5731       {Store->getChain(), NewValue, Store->getBasePtr(), VL},
5732       Store->getMemoryVT(), Store->getMemOperand());
5733 }
5734 
5735 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
5736                                              SelectionDAG &DAG) const {
5737   SDLoc DL(Op);
5738   MVT VT = Op.getSimpleValueType();
5739 
5740   const auto *MemSD = cast<MemSDNode>(Op);
5741   EVT MemVT = MemSD->getMemoryVT();
5742   MachineMemOperand *MMO = MemSD->getMemOperand();
5743   SDValue Chain = MemSD->getChain();
5744   SDValue BasePtr = MemSD->getBasePtr();
5745 
5746   SDValue Mask, PassThru, VL;
5747   if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
5748     Mask = VPLoad->getMask();
5749     PassThru = DAG.getUNDEF(VT);
5750     VL = VPLoad->getVectorLength();
5751   } else {
5752     const auto *MLoad = cast<MaskedLoadSDNode>(Op);
5753     Mask = MLoad->getMask();
5754     PassThru = MLoad->getPassThru();
5755   }
5756 
5757   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5758 
5759   MVT XLenVT = Subtarget.getXLenVT();
5760 
5761   MVT ContainerVT = VT;
5762   if (VT.isFixedLengthVector()) {
5763     ContainerVT = getContainerForFixedLengthVector(VT);
5764     PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
5765     if (!IsUnmasked) {
5766       MVT MaskVT =
5767           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5768       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5769     }
5770   }
5771 
5772   if (!VL)
5773     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5774 
5775   unsigned IntID =
5776       IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
5777   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5778   if (IsUnmasked)
5779     Ops.push_back(DAG.getUNDEF(ContainerVT));
5780   else
5781     Ops.push_back(PassThru);
5782   Ops.push_back(BasePtr);
5783   if (!IsUnmasked)
5784     Ops.push_back(Mask);
5785   Ops.push_back(VL);
5786   if (!IsUnmasked)
5787     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
5788 
5789   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
5790 
5791   SDValue Result =
5792       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
5793   Chain = Result.getValue(1);
5794 
5795   if (VT.isFixedLengthVector())
5796     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
5797 
5798   return DAG.getMergeValues({Result, Chain}, DL);
5799 }
5800 
5801 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
5802                                               SelectionDAG &DAG) const {
5803   SDLoc DL(Op);
5804 
5805   const auto *MemSD = cast<MemSDNode>(Op);
5806   EVT MemVT = MemSD->getMemoryVT();
5807   MachineMemOperand *MMO = MemSD->getMemOperand();
5808   SDValue Chain = MemSD->getChain();
5809   SDValue BasePtr = MemSD->getBasePtr();
5810   SDValue Val, Mask, VL;
5811 
5812   if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
5813     Val = VPStore->getValue();
5814     Mask = VPStore->getMask();
5815     VL = VPStore->getVectorLength();
5816   } else {
5817     const auto *MStore = cast<MaskedStoreSDNode>(Op);
5818     Val = MStore->getValue();
5819     Mask = MStore->getMask();
5820   }
5821 
5822   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
5823 
5824   MVT VT = Val.getSimpleValueType();
5825   MVT XLenVT = Subtarget.getXLenVT();
5826 
5827   MVT ContainerVT = VT;
5828   if (VT.isFixedLengthVector()) {
5829     ContainerVT = getContainerForFixedLengthVector(VT);
5830 
5831     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
5832     if (!IsUnmasked) {
5833       MVT MaskVT =
5834           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5835       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
5836     }
5837   }
5838 
5839   if (!VL)
5840     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
5841 
5842   unsigned IntID =
5843       IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
5844   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
5845   Ops.push_back(Val);
5846   Ops.push_back(BasePtr);
5847   if (!IsUnmasked)
5848     Ops.push_back(Mask);
5849   Ops.push_back(VL);
5850 
5851   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
5852                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
5853 }
5854 
5855 SDValue
5856 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
5857                                                       SelectionDAG &DAG) const {
5858   MVT InVT = Op.getOperand(0).getSimpleValueType();
5859   MVT ContainerVT = getContainerForFixedLengthVector(InVT);
5860 
5861   MVT VT = Op.getSimpleValueType();
5862 
5863   SDValue Op1 =
5864       convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
5865   SDValue Op2 =
5866       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5867 
5868   SDLoc DL(Op);
5869   SDValue VL =
5870       DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT());
5871 
5872   MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5873   SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
5874 
5875   SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2,
5876                             Op.getOperand(2), Mask, VL);
5877 
5878   return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
5879 }
5880 
5881 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
5882     SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
5883   MVT VT = Op.getSimpleValueType();
5884 
5885   if (VT.getVectorElementType() == MVT::i1)
5886     return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false);
5887 
5888   return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true);
5889 }
5890 
5891 SDValue
5892 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
5893                                                       SelectionDAG &DAG) const {
5894   unsigned Opc;
5895   switch (Op.getOpcode()) {
5896   default: llvm_unreachable("Unexpected opcode!");
5897   case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
5898   case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
5899   case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
5900   }
5901 
5902   return lowerToScalableOp(Op, DAG, Opc);
5903 }
5904 
5905 // Lower vector ABS to smax(X, sub(0, X)).
5906 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
5907   SDLoc DL(Op);
5908   MVT VT = Op.getSimpleValueType();
5909   SDValue X = Op.getOperand(0);
5910 
5911   assert(VT.isFixedLengthVector() && "Unexpected type");
5912 
5913   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5914   X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
5915 
5916   SDValue Mask, VL;
5917   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5918 
5919   SDValue SplatZero = DAG.getNode(
5920       RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
5921       DAG.getConstant(0, DL, Subtarget.getXLenVT()));
5922   SDValue NegX =
5923       DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL);
5924   SDValue Max =
5925       DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL);
5926 
5927   return convertFromScalableVector(VT, Max, DAG, Subtarget);
5928 }
5929 
5930 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
5931     SDValue Op, SelectionDAG &DAG) const {
5932   SDLoc DL(Op);
5933   MVT VT = Op.getSimpleValueType();
5934   SDValue Mag = Op.getOperand(0);
5935   SDValue Sign = Op.getOperand(1);
5936   assert(Mag.getValueType() == Sign.getValueType() &&
5937          "Can only handle COPYSIGN with matching types.");
5938 
5939   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5940   Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
5941   Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
5942 
5943   SDValue Mask, VL;
5944   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5945 
5946   SDValue CopySign =
5947       DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL);
5948 
5949   return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
5950 }
5951 
5952 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
5953     SDValue Op, SelectionDAG &DAG) const {
5954   MVT VT = Op.getSimpleValueType();
5955   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5956 
5957   MVT I1ContainerVT =
5958       MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
5959 
5960   SDValue CC =
5961       convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
5962   SDValue Op1 =
5963       convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
5964   SDValue Op2 =
5965       convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
5966 
5967   SDLoc DL(Op);
5968   SDValue Mask, VL;
5969   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
5970 
5971   SDValue Select =
5972       DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
5973 
5974   return convertFromScalableVector(VT, Select, DAG, Subtarget);
5975 }
5976 
5977 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
5978                                                unsigned NewOpc,
5979                                                bool HasMask) const {
5980   MVT VT = Op.getSimpleValueType();
5981   MVT ContainerVT = getContainerForFixedLengthVector(VT);
5982 
5983   // Create list of operands by converting existing ones to scalable types.
5984   SmallVector<SDValue, 6> Ops;
5985   for (const SDValue &V : Op->op_values()) {
5986     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
5987 
5988     // Pass through non-vector operands.
5989     if (!V.getValueType().isVector()) {
5990       Ops.push_back(V);
5991       continue;
5992     }
5993 
5994     // "cast" fixed length vector to a scalable vector.
5995     assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
5996            "Only fixed length vectors are supported!");
5997     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
5998   }
5999 
6000   SDLoc DL(Op);
6001   SDValue Mask, VL;
6002   std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
6003   if (HasMask)
6004     Ops.push_back(Mask);
6005   Ops.push_back(VL);
6006 
6007   SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops);
6008   return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
6009 }
6010 
6011 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
6012 // * Operands of each node are assumed to be in the same order.
6013 // * The EVL operand is promoted from i32 to i64 on RV64.
6014 // * Fixed-length vectors are converted to their scalable-vector container
6015 //   types.
6016 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
6017                                        unsigned RISCVISDOpc) const {
6018   SDLoc DL(Op);
6019   MVT VT = Op.getSimpleValueType();
6020   SmallVector<SDValue, 4> Ops;
6021 
6022   for (const auto &OpIdx : enumerate(Op->ops())) {
6023     SDValue V = OpIdx.value();
6024     assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
6025     // Pass through operands which aren't fixed-length vectors.
6026     if (!V.getValueType().isFixedLengthVector()) {
6027       Ops.push_back(V);
6028       continue;
6029     }
6030     // "cast" fixed length vector to a scalable vector.
6031     MVT OpVT = V.getSimpleValueType();
6032     MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
6033     assert(useRVVForFixedLengthVectorVT(OpVT) &&
6034            "Only fixed length vectors are supported!");
6035     Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
6036   }
6037 
6038   if (!VT.isFixedLengthVector())
6039     return DAG.getNode(RISCVISDOpc, DL, VT, Ops);
6040 
6041   MVT ContainerVT = getContainerForFixedLengthVector(VT);
6042 
6043   SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops);
6044 
6045   return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
6046 }
6047 
6048 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
6049                                             unsigned MaskOpc,
6050                                             unsigned VecOpc) const {
6051   MVT VT = Op.getSimpleValueType();
6052   if (VT.getVectorElementType() != MVT::i1)
6053     return lowerVPOp(Op, DAG, VecOpc);
6054 
6055   // It is safe to drop mask parameter as masked-off elements are undef.
6056   SDValue Op1 = Op->getOperand(0);
6057   SDValue Op2 = Op->getOperand(1);
6058   SDValue VL = Op->getOperand(3);
6059 
6060   MVT ContainerVT = VT;
6061   const bool IsFixed = VT.isFixedLengthVector();
6062   if (IsFixed) {
6063     ContainerVT = getContainerForFixedLengthVector(VT);
6064     Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
6065     Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
6066   }
6067 
6068   SDLoc DL(Op);
6069   SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
6070   if (!IsFixed)
6071     return Val;
6072   return convertFromScalableVector(VT, Val, DAG, Subtarget);
6073 }
6074 
6075 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
6076 // matched to a RVV indexed load. The RVV indexed load instructions only
6077 // support the "unsigned unscaled" addressing mode; indices are implicitly
6078 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6079 // signed or scaled indexing is extended to the XLEN value type and scaled
6080 // accordingly.
6081 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
6082                                                SelectionDAG &DAG) const {
6083   SDLoc DL(Op);
6084   MVT VT = Op.getSimpleValueType();
6085 
6086   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6087   EVT MemVT = MemSD->getMemoryVT();
6088   MachineMemOperand *MMO = MemSD->getMemOperand();
6089   SDValue Chain = MemSD->getChain();
6090   SDValue BasePtr = MemSD->getBasePtr();
6091 
6092   ISD::LoadExtType LoadExtType;
6093   SDValue Index, Mask, PassThru, VL;
6094 
6095   if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
6096     Index = VPGN->getIndex();
6097     Mask = VPGN->getMask();
6098     PassThru = DAG.getUNDEF(VT);
6099     VL = VPGN->getVectorLength();
6100     // VP doesn't support extending loads.
6101     LoadExtType = ISD::NON_EXTLOAD;
6102   } else {
6103     // Else it must be a MGATHER.
6104     auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
6105     Index = MGN->getIndex();
6106     Mask = MGN->getMask();
6107     PassThru = MGN->getPassThru();
6108     LoadExtType = MGN->getExtensionType();
6109   }
6110 
6111   MVT IndexVT = Index.getSimpleValueType();
6112   MVT XLenVT = Subtarget.getXLenVT();
6113 
6114   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6115          "Unexpected VTs!");
6116   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6117   // Targets have to explicitly opt-in for extending vector loads.
6118   assert(LoadExtType == ISD::NON_EXTLOAD &&
6119          "Unexpected extending MGATHER/VP_GATHER");
6120   (void)LoadExtType;
6121 
6122   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6123   // the selection of the masked intrinsics doesn't do this for us.
6124   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6125 
6126   MVT ContainerVT = VT;
6127   if (VT.isFixedLengthVector()) {
6128     // We need to use the larger of the result and index type to determine the
6129     // scalable type to use so we don't increase LMUL for any operand/result.
6130     if (VT.bitsGE(IndexVT)) {
6131       ContainerVT = getContainerForFixedLengthVector(VT);
6132       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6133                                  ContainerVT.getVectorElementCount());
6134     } else {
6135       IndexVT = getContainerForFixedLengthVector(IndexVT);
6136       ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(),
6137                                      IndexVT.getVectorElementCount());
6138     }
6139 
6140     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6141 
6142     if (!IsUnmasked) {
6143       MVT MaskVT =
6144           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6145       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6146       PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
6147     }
6148   }
6149 
6150   if (!VL)
6151     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6152 
6153   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6154     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6155     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6156                                    VL);
6157     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6158                         TrueMask, VL);
6159   }
6160 
6161   unsigned IntID =
6162       IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
6163   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6164   if (IsUnmasked)
6165     Ops.push_back(DAG.getUNDEF(ContainerVT));
6166   else
6167     Ops.push_back(PassThru);
6168   Ops.push_back(BasePtr);
6169   Ops.push_back(Index);
6170   if (!IsUnmasked)
6171     Ops.push_back(Mask);
6172   Ops.push_back(VL);
6173   if (!IsUnmasked)
6174     Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
6175 
6176   SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
6177   SDValue Result =
6178       DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
6179   Chain = Result.getValue(1);
6180 
6181   if (VT.isFixedLengthVector())
6182     Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
6183 
6184   return DAG.getMergeValues({Result, Chain}, DL);
6185 }
6186 
6187 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
6188 // matched to a RVV indexed store. The RVV indexed store instructions only
6189 // support the "unsigned unscaled" addressing mode; indices are implicitly
6190 // zero-extended or truncated to XLEN and are treated as byte offsets. Any
6191 // signed or scaled indexing is extended to the XLEN value type and scaled
6192 // accordingly.
6193 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
6194                                                 SelectionDAG &DAG) const {
6195   SDLoc DL(Op);
6196   const auto *MemSD = cast<MemSDNode>(Op.getNode());
6197   EVT MemVT = MemSD->getMemoryVT();
6198   MachineMemOperand *MMO = MemSD->getMemOperand();
6199   SDValue Chain = MemSD->getChain();
6200   SDValue BasePtr = MemSD->getBasePtr();
6201 
6202   bool IsTruncatingStore = false;
6203   SDValue Index, Mask, Val, VL;
6204 
6205   if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
6206     Index = VPSN->getIndex();
6207     Mask = VPSN->getMask();
6208     Val = VPSN->getValue();
6209     VL = VPSN->getVectorLength();
6210     // VP doesn't support truncating stores.
6211     IsTruncatingStore = false;
6212   } else {
6213     // Else it must be a MSCATTER.
6214     auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
6215     Index = MSN->getIndex();
6216     Mask = MSN->getMask();
6217     Val = MSN->getValue();
6218     IsTruncatingStore = MSN->isTruncatingStore();
6219   }
6220 
6221   MVT VT = Val.getSimpleValueType();
6222   MVT IndexVT = Index.getSimpleValueType();
6223   MVT XLenVT = Subtarget.getXLenVT();
6224 
6225   assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
6226          "Unexpected VTs!");
6227   assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
6228   // Targets have to explicitly opt-in for extending vector loads and
6229   // truncating vector stores.
6230   assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
6231   (void)IsTruncatingStore;
6232 
6233   // If the mask is known to be all ones, optimize to an unmasked intrinsic;
6234   // the selection of the masked intrinsics doesn't do this for us.
6235   bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
6236 
6237   MVT ContainerVT = VT;
6238   if (VT.isFixedLengthVector()) {
6239     // We need to use the larger of the value and index type to determine the
6240     // scalable type to use so we don't increase LMUL for any operand/result.
6241     if (VT.bitsGE(IndexVT)) {
6242       ContainerVT = getContainerForFixedLengthVector(VT);
6243       IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
6244                                  ContainerVT.getVectorElementCount());
6245     } else {
6246       IndexVT = getContainerForFixedLengthVector(IndexVT);
6247       ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
6248                                      IndexVT.getVectorElementCount());
6249     }
6250 
6251     Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
6252     Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
6253 
6254     if (!IsUnmasked) {
6255       MVT MaskVT =
6256           MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6257       Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
6258     }
6259   }
6260 
6261   if (!VL)
6262     VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
6263 
6264   if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
6265     IndexVT = IndexVT.changeVectorElementType(XLenVT);
6266     SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
6267                                    VL);
6268     Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
6269                         TrueMask, VL);
6270   }
6271 
6272   unsigned IntID =
6273       IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
6274   SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
6275   Ops.push_back(Val);
6276   Ops.push_back(BasePtr);
6277   Ops.push_back(Index);
6278   if (!IsUnmasked)
6279     Ops.push_back(Mask);
6280   Ops.push_back(VL);
6281 
6282   return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
6283                                  DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
6284 }
6285 
6286 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
6287                                                SelectionDAG &DAG) const {
6288   const MVT XLenVT = Subtarget.getXLenVT();
6289   SDLoc DL(Op);
6290   SDValue Chain = Op->getOperand(0);
6291   SDValue SysRegNo = DAG.getTargetConstant(
6292       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6293   SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
6294   SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
6295 
6296   // Encoding used for rounding mode in RISCV differs from that used in
6297   // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
6298   // table, which consists of a sequence of 4-bit fields, each representing
6299   // corresponding FLT_ROUNDS mode.
6300   static const int Table =
6301       (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
6302       (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
6303       (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
6304       (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
6305       (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
6306 
6307   SDValue Shift =
6308       DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
6309   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6310                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6311   SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6312                                DAG.getConstant(7, DL, XLenVT));
6313 
6314   return DAG.getMergeValues({Masked, Chain}, DL);
6315 }
6316 
6317 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
6318                                                SelectionDAG &DAG) const {
6319   const MVT XLenVT = Subtarget.getXLenVT();
6320   SDLoc DL(Op);
6321   SDValue Chain = Op->getOperand(0);
6322   SDValue RMValue = Op->getOperand(1);
6323   SDValue SysRegNo = DAG.getTargetConstant(
6324       RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
6325 
6326   // Encoding used for rounding mode in RISCV differs from that used in
6327   // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
6328   // a table, which consists of a sequence of 4-bit fields, each representing
6329   // corresponding RISCV mode.
6330   static const unsigned Table =
6331       (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
6332       (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
6333       (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
6334       (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
6335       (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
6336 
6337   SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
6338                               DAG.getConstant(2, DL, XLenVT));
6339   SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
6340                                 DAG.getConstant(Table, DL, XLenVT), Shift);
6341   RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
6342                         DAG.getConstant(0x7, DL, XLenVT));
6343   return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
6344                      RMValue);
6345 }
6346 
6347 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) {
6348   switch (IntNo) {
6349   default:
6350     llvm_unreachable("Unexpected Intrinsic");
6351   case Intrinsic::riscv_grev:
6352     return RISCVISD::GREVW;
6353   case Intrinsic::riscv_gorc:
6354     return RISCVISD::GORCW;
6355   case Intrinsic::riscv_bcompress:
6356     return RISCVISD::BCOMPRESSW;
6357   case Intrinsic::riscv_bdecompress:
6358     return RISCVISD::BDECOMPRESSW;
6359   case Intrinsic::riscv_bfp:
6360     return RISCVISD::BFPW;
6361   case Intrinsic::riscv_fsl:
6362     return RISCVISD::FSLW;
6363   case Intrinsic::riscv_fsr:
6364     return RISCVISD::FSRW;
6365   }
6366 }
6367 
6368 // Converts the given intrinsic to a i64 operation with any extension.
6369 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG,
6370                                          unsigned IntNo) {
6371   SDLoc DL(N);
6372   RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo);
6373   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6374   SDValue NewOp2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6375   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp1, NewOp2);
6376   // ReplaceNodeResults requires we maintain the same type for the return value.
6377   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6378 }
6379 
6380 // Returns the opcode of the target-specific SDNode that implements the 32-bit
6381 // form of the given Opcode.
6382 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
6383   switch (Opcode) {
6384   default:
6385     llvm_unreachable("Unexpected opcode");
6386   case ISD::SHL:
6387     return RISCVISD::SLLW;
6388   case ISD::SRA:
6389     return RISCVISD::SRAW;
6390   case ISD::SRL:
6391     return RISCVISD::SRLW;
6392   case ISD::SDIV:
6393     return RISCVISD::DIVW;
6394   case ISD::UDIV:
6395     return RISCVISD::DIVUW;
6396   case ISD::UREM:
6397     return RISCVISD::REMUW;
6398   case ISD::ROTL:
6399     return RISCVISD::ROLW;
6400   case ISD::ROTR:
6401     return RISCVISD::RORW;
6402   case RISCVISD::GREV:
6403     return RISCVISD::GREVW;
6404   case RISCVISD::GORC:
6405     return RISCVISD::GORCW;
6406   }
6407 }
6408 
6409 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
6410 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
6411 // otherwise be promoted to i64, making it difficult to select the
6412 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
6413 // type i8/i16/i32 is lost.
6414 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
6415                                    unsigned ExtOpc = ISD::ANY_EXTEND) {
6416   SDLoc DL(N);
6417   RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6418   SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
6419   SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
6420   SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6421   // ReplaceNodeResults requires we maintain the same type for the return value.
6422   return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
6423 }
6424 
6425 // Converts the given 32-bit operation to a i64 operation with signed extension
6426 // semantic to reduce the signed extension instructions.
6427 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
6428   SDLoc DL(N);
6429   SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6430   SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6431   SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
6432   SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6433                                DAG.getValueType(MVT::i32));
6434   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
6435 }
6436 
6437 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
6438                                              SmallVectorImpl<SDValue> &Results,
6439                                              SelectionDAG &DAG) const {
6440   SDLoc DL(N);
6441   switch (N->getOpcode()) {
6442   default:
6443     llvm_unreachable("Don't know how to custom type legalize this operation!");
6444   case ISD::STRICT_FP_TO_SINT:
6445   case ISD::STRICT_FP_TO_UINT:
6446   case ISD::FP_TO_SINT:
6447   case ISD::FP_TO_UINT: {
6448     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6449            "Unexpected custom legalisation");
6450     bool IsStrict = N->isStrictFPOpcode();
6451     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
6452                     N->getOpcode() == ISD::STRICT_FP_TO_SINT;
6453     SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
6454     if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
6455         TargetLowering::TypeSoftenFloat) {
6456       if (!isTypeLegal(Op0.getValueType()))
6457         return;
6458       if (IsStrict) {
6459         unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
6460                                 : RISCVISD::STRICT_FCVT_WU_RV64;
6461         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
6462         SDValue Res = DAG.getNode(
6463             Opc, DL, VTs, N->getOperand(0), Op0,
6464             DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6465         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6466         Results.push_back(Res.getValue(1));
6467         return;
6468       }
6469       unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
6470       SDValue Res =
6471           DAG.getNode(Opc, DL, MVT::i64, Op0,
6472                       DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
6473       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6474       return;
6475     }
6476     // If the FP type needs to be softened, emit a library call using the 'si'
6477     // version. If we left it to default legalization we'd end up with 'di'. If
6478     // the FP type doesn't need to be softened just let generic type
6479     // legalization promote the result type.
6480     RTLIB::Libcall LC;
6481     if (IsSigned)
6482       LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
6483     else
6484       LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
6485     MakeLibCallOptions CallOptions;
6486     EVT OpVT = Op0.getValueType();
6487     CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
6488     SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
6489     SDValue Result;
6490     std::tie(Result, Chain) =
6491         makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
6492     Results.push_back(Result);
6493     if (IsStrict)
6494       Results.push_back(Chain);
6495     break;
6496   }
6497   case ISD::READCYCLECOUNTER: {
6498     assert(!Subtarget.is64Bit() &&
6499            "READCYCLECOUNTER only has custom type legalization on riscv32");
6500 
6501     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6502     SDValue RCW =
6503         DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
6504 
6505     Results.push_back(
6506         DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
6507     Results.push_back(RCW.getValue(2));
6508     break;
6509   }
6510   case ISD::MUL: {
6511     unsigned Size = N->getSimpleValueType(0).getSizeInBits();
6512     unsigned XLen = Subtarget.getXLen();
6513     // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
6514     if (Size > XLen) {
6515       assert(Size == (XLen * 2) && "Unexpected custom legalisation");
6516       SDValue LHS = N->getOperand(0);
6517       SDValue RHS = N->getOperand(1);
6518       APInt HighMask = APInt::getHighBitsSet(Size, XLen);
6519 
6520       bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
6521       bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
6522       // We need exactly one side to be unsigned.
6523       if (LHSIsU == RHSIsU)
6524         return;
6525 
6526       auto MakeMULPair = [&](SDValue S, SDValue U) {
6527         MVT XLenVT = Subtarget.getXLenVT();
6528         S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
6529         U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
6530         SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
6531         SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
6532         return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
6533       };
6534 
6535       bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
6536       bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
6537 
6538       // The other operand should be signed, but still prefer MULH when
6539       // possible.
6540       if (RHSIsU && LHSIsS && !RHSIsS)
6541         Results.push_back(MakeMULPair(LHS, RHS));
6542       else if (LHSIsU && RHSIsS && !LHSIsS)
6543         Results.push_back(MakeMULPair(RHS, LHS));
6544 
6545       return;
6546     }
6547     LLVM_FALLTHROUGH;
6548   }
6549   case ISD::ADD:
6550   case ISD::SUB:
6551     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6552            "Unexpected custom legalisation");
6553     Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
6554     break;
6555   case ISD::SHL:
6556   case ISD::SRA:
6557   case ISD::SRL:
6558     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6559            "Unexpected custom legalisation");
6560     if (N->getOperand(1).getOpcode() != ISD::Constant) {
6561       Results.push_back(customLegalizeToWOp(N, DAG));
6562       break;
6563     }
6564 
6565     // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
6566     // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
6567     // shift amount.
6568     if (N->getOpcode() == ISD::SHL) {
6569       SDLoc DL(N);
6570       SDValue NewOp0 =
6571           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6572       SDValue NewOp1 =
6573           DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
6574       SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
6575       SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
6576                                    DAG.getValueType(MVT::i32));
6577       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6578     }
6579 
6580     break;
6581   case ISD::ROTL:
6582   case ISD::ROTR:
6583     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6584            "Unexpected custom legalisation");
6585     Results.push_back(customLegalizeToWOp(N, DAG));
6586     break;
6587   case ISD::CTTZ:
6588   case ISD::CTTZ_ZERO_UNDEF:
6589   case ISD::CTLZ:
6590   case ISD::CTLZ_ZERO_UNDEF: {
6591     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6592            "Unexpected custom legalisation");
6593 
6594     SDValue NewOp0 =
6595         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6596     bool IsCTZ =
6597         N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
6598     unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
6599     SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
6600     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6601     return;
6602   }
6603   case ISD::SDIV:
6604   case ISD::UDIV:
6605   case ISD::UREM: {
6606     MVT VT = N->getSimpleValueType(0);
6607     assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
6608            Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
6609            "Unexpected custom legalisation");
6610     // Don't promote division/remainder by constant since we should expand those
6611     // to multiply by magic constant.
6612     // FIXME: What if the expansion is disabled for minsize.
6613     if (N->getOperand(1).getOpcode() == ISD::Constant)
6614       return;
6615 
6616     // If the input is i32, use ANY_EXTEND since the W instructions don't read
6617     // the upper 32 bits. For other types we need to sign or zero extend
6618     // based on the opcode.
6619     unsigned ExtOpc = ISD::ANY_EXTEND;
6620     if (VT != MVT::i32)
6621       ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
6622                                            : ISD::ZERO_EXTEND;
6623 
6624     Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
6625     break;
6626   }
6627   case ISD::UADDO:
6628   case ISD::USUBO: {
6629     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6630            "Unexpected custom legalisation");
6631     bool IsAdd = N->getOpcode() == ISD::UADDO;
6632     // Create an ADDW or SUBW.
6633     SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6634     SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6635     SDValue Res =
6636         DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
6637     Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
6638                       DAG.getValueType(MVT::i32));
6639 
6640     // Sign extend the LHS and perform an unsigned compare with the ADDW result.
6641     // Since the inputs are sign extended from i32, this is equivalent to
6642     // comparing the lower 32 bits.
6643     LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6644     SDValue Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
6645                                     IsAdd ? ISD::SETULT : ISD::SETUGT);
6646 
6647     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6648     Results.push_back(Overflow);
6649     return;
6650   }
6651   case ISD::UADDSAT:
6652   case ISD::USUBSAT: {
6653     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6654            "Unexpected custom legalisation");
6655     if (Subtarget.hasStdExtZbb()) {
6656       // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
6657       // sign extend allows overflow of the lower 32 bits to be detected on
6658       // the promoted size.
6659       SDValue LHS =
6660           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6661       SDValue RHS =
6662           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
6663       SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
6664       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6665       return;
6666     }
6667 
6668     // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
6669     // promotion for UADDO/USUBO.
6670     Results.push_back(expandAddSubSat(N, DAG));
6671     return;
6672   }
6673   case ISD::ABS: {
6674     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6675            "Unexpected custom legalisation");
6676           DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
6677 
6678     // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
6679 
6680     SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6681 
6682     // Freeze the source so we can increase it's use count.
6683     Src = DAG.getFreeze(Src);
6684 
6685     // Copy sign bit to all bits using the sraiw pattern.
6686     SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
6687                                    DAG.getValueType(MVT::i32));
6688     SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
6689                            DAG.getConstant(31, DL, MVT::i64));
6690 
6691     SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
6692     NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
6693 
6694     // NOTE: The result is only required to be anyextended, but sext is
6695     // consistent with type legalization of sub.
6696     NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
6697                          DAG.getValueType(MVT::i32));
6698     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6699     return;
6700   }
6701   case ISD::BITCAST: {
6702     EVT VT = N->getValueType(0);
6703     assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
6704     SDValue Op0 = N->getOperand(0);
6705     EVT Op0VT = Op0.getValueType();
6706     MVT XLenVT = Subtarget.getXLenVT();
6707     if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) {
6708       SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
6709       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
6710     } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
6711                Subtarget.hasStdExtF()) {
6712       SDValue FPConv =
6713           DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
6714       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
6715     } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
6716                isTypeLegal(Op0VT)) {
6717       // Custom-legalize bitcasts from fixed-length vector types to illegal
6718       // scalar types in order to improve codegen. Bitcast the vector to a
6719       // one-element vector type whose element type is the same as the result
6720       // type, and extract the first element.
6721       EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
6722       if (isTypeLegal(BVT)) {
6723         SDValue BVec = DAG.getBitcast(BVT, Op0);
6724         Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
6725                                       DAG.getConstant(0, DL, XLenVT)));
6726       }
6727     }
6728     break;
6729   }
6730   case RISCVISD::GREV:
6731   case RISCVISD::GORC: {
6732     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6733            "Unexpected custom legalisation");
6734     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6735     // This is similar to customLegalizeToWOp, except that we pass the second
6736     // operand (a TargetConstant) straight through: it is already of type
6737     // XLenVT.
6738     RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
6739     SDValue NewOp0 =
6740         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6741     SDValue NewOp1 =
6742         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6743     SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
6744     // ReplaceNodeResults requires we maintain the same type for the return
6745     // value.
6746     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6747     break;
6748   }
6749   case RISCVISD::SHFL: {
6750     // There is no SHFLIW instruction, but we can just promote the operation.
6751     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6752            "Unexpected custom legalisation");
6753     assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant");
6754     SDValue NewOp0 =
6755         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6756     SDValue NewOp1 =
6757         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6758     SDValue NewRes = DAG.getNode(RISCVISD::SHFL, DL, MVT::i64, NewOp0, NewOp1);
6759     // ReplaceNodeResults requires we maintain the same type for the return
6760     // value.
6761     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
6762     break;
6763   }
6764   case ISD::BSWAP:
6765   case ISD::BITREVERSE: {
6766     MVT VT = N->getSimpleValueType(0);
6767     MVT XLenVT = Subtarget.getXLenVT();
6768     assert((VT == MVT::i8 || VT == MVT::i16 ||
6769             (VT == MVT::i32 && Subtarget.is64Bit())) &&
6770            Subtarget.hasStdExtZbp() && "Unexpected custom legalisation");
6771     SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
6772     unsigned Imm = VT.getSizeInBits() - 1;
6773     // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits.
6774     if (N->getOpcode() == ISD::BSWAP)
6775       Imm &= ~0x7U;
6776     unsigned Opc = Subtarget.is64Bit() ? RISCVISD::GREVW : RISCVISD::GREV;
6777     SDValue GREVI =
6778         DAG.getNode(Opc, DL, XLenVT, NewOp0, DAG.getConstant(Imm, DL, XLenVT));
6779     // ReplaceNodeResults requires we maintain the same type for the return
6780     // value.
6781     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI));
6782     break;
6783   }
6784   case ISD::FSHL:
6785   case ISD::FSHR: {
6786     assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6787            Subtarget.hasStdExtZbt() && "Unexpected custom legalisation");
6788     SDValue NewOp0 =
6789         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
6790     SDValue NewOp1 =
6791         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6792     SDValue NewShAmt =
6793         DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6794     // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits.
6795     // Mask the shift amount to 5 bits to prevent accidentally setting bit 5.
6796     NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt,
6797                            DAG.getConstant(0x1f, DL, MVT::i64));
6798     // fshl and fshr concatenate their operands in the same order. fsrw and fslw
6799     // instruction use different orders. fshl will return its first operand for
6800     // shift of zero, fshr will return its second operand. fsl and fsr both
6801     // return rs1 so the ISD nodes need to have different operand orders.
6802     // Shift amount is in rs2.
6803     unsigned Opc = RISCVISD::FSLW;
6804     if (N->getOpcode() == ISD::FSHR) {
6805       std::swap(NewOp0, NewOp1);
6806       Opc = RISCVISD::FSRW;
6807     }
6808     SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt);
6809     Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp));
6810     break;
6811   }
6812   case ISD::EXTRACT_VECTOR_ELT: {
6813     // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
6814     // type is illegal (currently only vXi64 RV32).
6815     // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
6816     // transferred to the destination register. We issue two of these from the
6817     // upper- and lower- halves of the SEW-bit vector element, slid down to the
6818     // first element.
6819     SDValue Vec = N->getOperand(0);
6820     SDValue Idx = N->getOperand(1);
6821 
6822     // The vector type hasn't been legalized yet so we can't issue target
6823     // specific nodes if it needs legalization.
6824     // FIXME: We would manually legalize if it's important.
6825     if (!isTypeLegal(Vec.getValueType()))
6826       return;
6827 
6828     MVT VecVT = Vec.getSimpleValueType();
6829 
6830     assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
6831            VecVT.getVectorElementType() == MVT::i64 &&
6832            "Unexpected EXTRACT_VECTOR_ELT legalization");
6833 
6834     // If this is a fixed vector, we need to convert it to a scalable vector.
6835     MVT ContainerVT = VecVT;
6836     if (VecVT.isFixedLengthVector()) {
6837       ContainerVT = getContainerForFixedLengthVector(VecVT);
6838       Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
6839     }
6840 
6841     MVT XLenVT = Subtarget.getXLenVT();
6842 
6843     // Use a VL of 1 to avoid processing more elements than we need.
6844     MVT MaskVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
6845     SDValue VL = DAG.getConstant(1, DL, XLenVT);
6846     SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6847 
6848     // Unless the index is known to be 0, we must slide the vector down to get
6849     // the desired element into index 0.
6850     if (!isNullConstant(Idx)) {
6851       Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT,
6852                         DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
6853     }
6854 
6855     // Extract the lower XLEN bits of the correct vector element.
6856     SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6857 
6858     // To extract the upper XLEN bits of the vector element, shift the first
6859     // element right by 32 bits and re-extract the lower XLEN bits.
6860     SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
6861                                      DAG.getUNDEF(ContainerVT),
6862                                      DAG.getConstant(32, DL, XLenVT), VL);
6863     SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec,
6864                                  ThirtyTwoV, Mask, VL);
6865 
6866     SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6867 
6868     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6869     break;
6870   }
6871   case ISD::INTRINSIC_WO_CHAIN: {
6872     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6873     switch (IntNo) {
6874     default:
6875       llvm_unreachable(
6876           "Don't know how to custom type legalize this intrinsic!");
6877     case Intrinsic::riscv_grev:
6878     case Intrinsic::riscv_gorc:
6879     case Intrinsic::riscv_bcompress:
6880     case Intrinsic::riscv_bdecompress:
6881     case Intrinsic::riscv_bfp: {
6882       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6883              "Unexpected custom legalisation");
6884       Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo));
6885       break;
6886     }
6887     case Intrinsic::riscv_fsl:
6888     case Intrinsic::riscv_fsr: {
6889       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6890              "Unexpected custom legalisation");
6891       SDValue NewOp1 =
6892           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6893       SDValue NewOp2 =
6894           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6895       SDValue NewOp3 =
6896           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(3));
6897       unsigned Opc = getRISCVWOpcodeByIntr(IntNo);
6898       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2, NewOp3);
6899       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6900       break;
6901     }
6902     case Intrinsic::riscv_orc_b: {
6903       // Lower to the GORCI encoding for orc.b with the operand extended.
6904       SDValue NewOp =
6905           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6906       // If Zbp is enabled, use GORCIW which will sign extend the result.
6907       unsigned Opc =
6908           Subtarget.hasStdExtZbp() ? RISCVISD::GORCW : RISCVISD::GORC;
6909       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp,
6910                                 DAG.getConstant(7, DL, MVT::i64));
6911       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6912       return;
6913     }
6914     case Intrinsic::riscv_shfl:
6915     case Intrinsic::riscv_unshfl: {
6916       assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
6917              "Unexpected custom legalisation");
6918       SDValue NewOp1 =
6919           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
6920       SDValue NewOp2 =
6921           DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2));
6922       unsigned Opc =
6923           IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW;
6924       // There is no (UN)SHFLIW. If the control word is a constant, we can use
6925       // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half
6926       // will be shuffled the same way as the lower 32 bit half, but the two
6927       // halves won't cross.
6928       if (isa<ConstantSDNode>(NewOp2)) {
6929         NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2,
6930                              DAG.getConstant(0xf, DL, MVT::i64));
6931         Opc =
6932             IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL;
6933       }
6934       SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2);
6935       Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
6936       break;
6937     }
6938     case Intrinsic::riscv_vmv_x_s: {
6939       EVT VT = N->getValueType(0);
6940       MVT XLenVT = Subtarget.getXLenVT();
6941       if (VT.bitsLT(XLenVT)) {
6942         // Simple case just extract using vmv.x.s and truncate.
6943         SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
6944                                       Subtarget.getXLenVT(), N->getOperand(1));
6945         Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
6946         return;
6947       }
6948 
6949       assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
6950              "Unexpected custom legalization");
6951 
6952       // We need to do the move in two steps.
6953       SDValue Vec = N->getOperand(1);
6954       MVT VecVT = Vec.getSimpleValueType();
6955 
6956       // First extract the lower XLEN bits of the element.
6957       SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
6958 
6959       // To extract the upper XLEN bits of the vector element, shift the first
6960       // element right by 32 bits and re-extract the lower XLEN bits.
6961       SDValue VL = DAG.getConstant(1, DL, XLenVT);
6962       MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
6963       SDValue Mask = DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
6964       SDValue ThirtyTwoV =
6965           DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
6966                       DAG.getConstant(32, DL, XLenVT), VL);
6967       SDValue LShr32 =
6968           DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL);
6969       SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
6970 
6971       Results.push_back(
6972           DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
6973       break;
6974     }
6975     }
6976     break;
6977   }
6978   case ISD::VECREDUCE_ADD:
6979   case ISD::VECREDUCE_AND:
6980   case ISD::VECREDUCE_OR:
6981   case ISD::VECREDUCE_XOR:
6982   case ISD::VECREDUCE_SMAX:
6983   case ISD::VECREDUCE_UMAX:
6984   case ISD::VECREDUCE_SMIN:
6985   case ISD::VECREDUCE_UMIN:
6986     if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
6987       Results.push_back(V);
6988     break;
6989   case ISD::VP_REDUCE_ADD:
6990   case ISD::VP_REDUCE_AND:
6991   case ISD::VP_REDUCE_OR:
6992   case ISD::VP_REDUCE_XOR:
6993   case ISD::VP_REDUCE_SMAX:
6994   case ISD::VP_REDUCE_UMAX:
6995   case ISD::VP_REDUCE_SMIN:
6996   case ISD::VP_REDUCE_UMIN:
6997     if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
6998       Results.push_back(V);
6999     break;
7000   case ISD::FLT_ROUNDS_: {
7001     SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
7002     SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0));
7003     Results.push_back(Res.getValue(0));
7004     Results.push_back(Res.getValue(1));
7005     break;
7006   }
7007   }
7008 }
7009 
7010 // A structure to hold one of the bit-manipulation patterns below. Together, a
7011 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source:
7012 //   (or (and (shl x, 1), 0xAAAAAAAA),
7013 //       (and (srl x, 1), 0x55555555))
7014 struct RISCVBitmanipPat {
7015   SDValue Op;
7016   unsigned ShAmt;
7017   bool IsSHL;
7018 
7019   bool formsPairWith(const RISCVBitmanipPat &Other) const {
7020     return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL;
7021   }
7022 };
7023 
7024 // Matches patterns of the form
7025 //   (and (shl x, C2), (C1 << C2))
7026 //   (and (srl x, C2), C1)
7027 //   (shl (and x, C1), C2)
7028 //   (srl (and x, (C1 << C2)), C2)
7029 // Where C2 is a power of 2 and C1 has at least that many leading zeroes.
7030 // The expected masks for each shift amount are specified in BitmanipMasks where
7031 // BitmanipMasks[log2(C2)] specifies the expected C1 value.
7032 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether
7033 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible
7034 // XLen is 64.
7035 static Optional<RISCVBitmanipPat>
7036 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) {
7037   assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) &&
7038          "Unexpected number of masks");
7039   Optional<uint64_t> Mask;
7040   // Optionally consume a mask around the shift operation.
7041   if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) {
7042     Mask = Op.getConstantOperandVal(1);
7043     Op = Op.getOperand(0);
7044   }
7045   if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL)
7046     return None;
7047   bool IsSHL = Op.getOpcode() == ISD::SHL;
7048 
7049   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7050     return None;
7051   uint64_t ShAmt = Op.getConstantOperandVal(1);
7052 
7053   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7054   if (ShAmt >= Width || !isPowerOf2_64(ShAmt))
7055     return None;
7056   // If we don't have enough masks for 64 bit, then we must be trying to
7057   // match SHFL so we're only allowed to shift 1/4 of the width.
7058   if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2))
7059     return None;
7060 
7061   SDValue Src = Op.getOperand(0);
7062 
7063   // The expected mask is shifted left when the AND is found around SHL
7064   // patterns.
7065   //   ((x >> 1) & 0x55555555)
7066   //   ((x << 1) & 0xAAAAAAAA)
7067   bool SHLExpMask = IsSHL;
7068 
7069   if (!Mask) {
7070     // Sometimes LLVM keeps the mask as an operand of the shift, typically when
7071     // the mask is all ones: consume that now.
7072     if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) {
7073       Mask = Src.getConstantOperandVal(1);
7074       Src = Src.getOperand(0);
7075       // The expected mask is now in fact shifted left for SRL, so reverse the
7076       // decision.
7077       //   ((x & 0xAAAAAAAA) >> 1)
7078       //   ((x & 0x55555555) << 1)
7079       SHLExpMask = !SHLExpMask;
7080     } else {
7081       // Use a default shifted mask of all-ones if there's no AND, truncated
7082       // down to the expected width. This simplifies the logic later on.
7083       Mask = maskTrailingOnes<uint64_t>(Width);
7084       *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt);
7085     }
7086   }
7087 
7088   unsigned MaskIdx = Log2_32(ShAmt);
7089   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7090 
7091   if (SHLExpMask)
7092     ExpMask <<= ShAmt;
7093 
7094   if (Mask != ExpMask)
7095     return None;
7096 
7097   return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL};
7098 }
7099 
7100 // Matches any of the following bit-manipulation patterns:
7101 //   (and (shl x, 1), (0x55555555 << 1))
7102 //   (and (srl x, 1), 0x55555555)
7103 //   (shl (and x, 0x55555555), 1)
7104 //   (srl (and x, (0x55555555 << 1)), 1)
7105 // where the shift amount and mask may vary thus:
7106 //   [1]  = 0x55555555 / 0xAAAAAAAA
7107 //   [2]  = 0x33333333 / 0xCCCCCCCC
7108 //   [4]  = 0x0F0F0F0F / 0xF0F0F0F0
7109 //   [8]  = 0x00FF00FF / 0xFF00FF00
7110 //   [16] = 0x0000FFFF / 0xFFFFFFFF
7111 //   [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64)
7112 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) {
7113   // These are the unshifted masks which we use to match bit-manipulation
7114   // patterns. They may be shifted left in certain circumstances.
7115   static const uint64_t BitmanipMasks[] = {
7116       0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
7117       0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
7118 
7119   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7120 }
7121 
7122 // Match the following pattern as a GREVI(W) operation
7123 //   (or (BITMANIP_SHL x), (BITMANIP_SRL x))
7124 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG,
7125                                const RISCVSubtarget &Subtarget) {
7126   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7127   EVT VT = Op.getValueType();
7128 
7129   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7130     auto LHS = matchGREVIPat(Op.getOperand(0));
7131     auto RHS = matchGREVIPat(Op.getOperand(1));
7132     if (LHS && RHS && LHS->formsPairWith(*RHS)) {
7133       SDLoc DL(Op);
7134       return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op,
7135                          DAG.getConstant(LHS->ShAmt, DL, VT));
7136     }
7137   }
7138   return SDValue();
7139 }
7140 
7141 // Matches any the following pattern as a GORCI(W) operation
7142 // 1.  (or (GREVI x, shamt), x) if shamt is a power of 2
7143 // 2.  (or x, (GREVI x, shamt)) if shamt is a power of 2
7144 // 3.  (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x))
7145 // Note that with the variant of 3.,
7146 //     (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x)
7147 // the inner pattern will first be matched as GREVI and then the outer
7148 // pattern will be matched to GORC via the first rule above.
7149 // 4.  (or (rotl/rotr x, bitwidth/2), x)
7150 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG,
7151                                const RISCVSubtarget &Subtarget) {
7152   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7153   EVT VT = Op.getValueType();
7154 
7155   if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) {
7156     SDLoc DL(Op);
7157     SDValue Op0 = Op.getOperand(0);
7158     SDValue Op1 = Op.getOperand(1);
7159 
7160     auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) {
7161       if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X &&
7162           isa<ConstantSDNode>(Reverse.getOperand(1)) &&
7163           isPowerOf2_32(Reverse.getConstantOperandVal(1)))
7164         return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1));
7165       // We can also form GORCI from ROTL/ROTR by half the bitwidth.
7166       if ((Reverse.getOpcode() == ISD::ROTL ||
7167            Reverse.getOpcode() == ISD::ROTR) &&
7168           Reverse.getOperand(0) == X &&
7169           isa<ConstantSDNode>(Reverse.getOperand(1))) {
7170         uint64_t RotAmt = Reverse.getConstantOperandVal(1);
7171         if (RotAmt == (VT.getSizeInBits() / 2))
7172           return DAG.getNode(RISCVISD::GORC, DL, VT, X,
7173                              DAG.getConstant(RotAmt, DL, VT));
7174       }
7175       return SDValue();
7176     };
7177 
7178     // Check for either commutable permutation of (or (GREVI x, shamt), x)
7179     if (SDValue V = MatchOROfReverse(Op0, Op1))
7180       return V;
7181     if (SDValue V = MatchOROfReverse(Op1, Op0))
7182       return V;
7183 
7184     // OR is commutable so canonicalize its OR operand to the left
7185     if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR)
7186       std::swap(Op0, Op1);
7187     if (Op0.getOpcode() != ISD::OR)
7188       return SDValue();
7189     SDValue OrOp0 = Op0.getOperand(0);
7190     SDValue OrOp1 = Op0.getOperand(1);
7191     auto LHS = matchGREVIPat(OrOp0);
7192     // OR is commutable so swap the operands and try again: x might have been
7193     // on the left
7194     if (!LHS) {
7195       std::swap(OrOp0, OrOp1);
7196       LHS = matchGREVIPat(OrOp0);
7197     }
7198     auto RHS = matchGREVIPat(Op1);
7199     if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) {
7200       return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op,
7201                          DAG.getConstant(LHS->ShAmt, DL, VT));
7202     }
7203   }
7204   return SDValue();
7205 }
7206 
7207 // Matches any of the following bit-manipulation patterns:
7208 //   (and (shl x, 1), (0x22222222 << 1))
7209 //   (and (srl x, 1), 0x22222222)
7210 //   (shl (and x, 0x22222222), 1)
7211 //   (srl (and x, (0x22222222 << 1)), 1)
7212 // where the shift amount and mask may vary thus:
7213 //   [1]  = 0x22222222 / 0x44444444
7214 //   [2]  = 0x0C0C0C0C / 0x3C3C3C3C
7215 //   [4]  = 0x00F000F0 / 0x0F000F00
7216 //   [8]  = 0x0000FF00 / 0x00FF0000
7217 //   [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64)
7218 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) {
7219   // These are the unshifted masks which we use to match bit-manipulation
7220   // patterns. They may be shifted left in certain circumstances.
7221   static const uint64_t BitmanipMasks[] = {
7222       0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL,
7223       0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL};
7224 
7225   return matchRISCVBitmanipPat(Op, BitmanipMasks);
7226 }
7227 
7228 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x)
7229 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG,
7230                                const RISCVSubtarget &Subtarget) {
7231   assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson");
7232   EVT VT = Op.getValueType();
7233 
7234   if (VT != MVT::i32 && VT != Subtarget.getXLenVT())
7235     return SDValue();
7236 
7237   SDValue Op0 = Op.getOperand(0);
7238   SDValue Op1 = Op.getOperand(1);
7239 
7240   // Or is commutable so canonicalize the second OR to the LHS.
7241   if (Op0.getOpcode() != ISD::OR)
7242     std::swap(Op0, Op1);
7243   if (Op0.getOpcode() != ISD::OR)
7244     return SDValue();
7245 
7246   // We found an inner OR, so our operands are the operands of the inner OR
7247   // and the other operand of the outer OR.
7248   SDValue A = Op0.getOperand(0);
7249   SDValue B = Op0.getOperand(1);
7250   SDValue C = Op1;
7251 
7252   auto Match1 = matchSHFLPat(A);
7253   auto Match2 = matchSHFLPat(B);
7254 
7255   // If neither matched, we failed.
7256   if (!Match1 && !Match2)
7257     return SDValue();
7258 
7259   // We had at least one match. if one failed, try the remaining C operand.
7260   if (!Match1) {
7261     std::swap(A, C);
7262     Match1 = matchSHFLPat(A);
7263     if (!Match1)
7264       return SDValue();
7265   } else if (!Match2) {
7266     std::swap(B, C);
7267     Match2 = matchSHFLPat(B);
7268     if (!Match2)
7269       return SDValue();
7270   }
7271   assert(Match1 && Match2);
7272 
7273   // Make sure our matches pair up.
7274   if (!Match1->formsPairWith(*Match2))
7275     return SDValue();
7276 
7277   // All the remains is to make sure C is an AND with the same input, that masks
7278   // out the bits that are being shuffled.
7279   if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) ||
7280       C.getOperand(0) != Match1->Op)
7281     return SDValue();
7282 
7283   uint64_t Mask = C.getConstantOperandVal(1);
7284 
7285   static const uint64_t BitmanipMasks[] = {
7286       0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL,
7287       0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL,
7288   };
7289 
7290   unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32;
7291   unsigned MaskIdx = Log2_32(Match1->ShAmt);
7292   uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width);
7293 
7294   if (Mask != ExpMask)
7295     return SDValue();
7296 
7297   SDLoc DL(Op);
7298   return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op,
7299                      DAG.getConstant(Match1->ShAmt, DL, VT));
7300 }
7301 
7302 // Optimize (add (shl x, c0), (shl y, c1)) ->
7303 //          (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
7304 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
7305                                   const RISCVSubtarget &Subtarget) {
7306   // Perform this optimization only in the zba extension.
7307   if (!Subtarget.hasStdExtZba())
7308     return SDValue();
7309 
7310   // Skip for vector types and larger types.
7311   EVT VT = N->getValueType(0);
7312   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7313     return SDValue();
7314 
7315   // The two operand nodes must be SHL and have no other use.
7316   SDValue N0 = N->getOperand(0);
7317   SDValue N1 = N->getOperand(1);
7318   if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
7319       !N0->hasOneUse() || !N1->hasOneUse())
7320     return SDValue();
7321 
7322   // Check c0 and c1.
7323   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7324   auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
7325   if (!N0C || !N1C)
7326     return SDValue();
7327   int64_t C0 = N0C->getSExtValue();
7328   int64_t C1 = N1C->getSExtValue();
7329   if (C0 <= 0 || C1 <= 0)
7330     return SDValue();
7331 
7332   // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
7333   int64_t Bits = std::min(C0, C1);
7334   int64_t Diff = std::abs(C0 - C1);
7335   if (Diff != 1 && Diff != 2 && Diff != 3)
7336     return SDValue();
7337 
7338   // Build nodes.
7339   SDLoc DL(N);
7340   SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
7341   SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
7342   SDValue NA0 =
7343       DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
7344   SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
7345   return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
7346 }
7347 
7348 // Combine
7349 // ROTR ((GREV x, 24), 16) -> (GREVI x, 8) for RV32
7350 // ROTL ((GREV x, 24), 16) -> (GREVI x, 8) for RV32
7351 // ROTR ((GREV x, 56), 32) -> (GREVI x, 24) for RV64
7352 // ROTL ((GREV x, 56), 32) -> (GREVI x, 24) for RV64
7353 // RORW ((GREVW x, 24), 16) -> (GREVIW x, 8) for RV64
7354 // ROLW ((GREVW x, 24), 16) -> (GREVIW x, 8) for RV64
7355 // The grev patterns represents BSWAP.
7356 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB
7357 // off the grev.
7358 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG,
7359                                           const RISCVSubtarget &Subtarget) {
7360   bool IsWInstruction =
7361       N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW;
7362   assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL ||
7363           IsWInstruction) &&
7364          "Unexpected opcode!");
7365   SDValue Src = N->getOperand(0);
7366   EVT VT = N->getValueType(0);
7367   SDLoc DL(N);
7368 
7369   if (!Subtarget.hasStdExtZbp())
7370     return SDValue();
7371 
7372   unsigned GrevOpc = IsWInstruction ? RISCVISD::GREVW : RISCVISD::GREV;
7373   if (Src.getOpcode() != GrevOpc)
7374     return SDValue();
7375 
7376   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7377       !isa<ConstantSDNode>(Src.getOperand(1)))
7378     return SDValue();
7379 
7380   unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits();
7381   assert(isPowerOf2_32(BitWidth) && "Expected a power of 2");
7382 
7383   // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for
7384   // RORW/ROLW. And the grev should be the encoding for bswap for this width.
7385   unsigned ShAmt1 = N->getConstantOperandVal(1);
7386   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7387   if (BitWidth < 16 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8))
7388     return SDValue();
7389 
7390   Src = Src.getOperand(0);
7391 
7392   // Toggle bit the MSB of the shift.
7393   unsigned CombinedShAmt = ShAmt1 ^ ShAmt2;
7394   if (CombinedShAmt == 0)
7395     return Src;
7396 
7397   return DAG.getNode(
7398       GrevOpc, DL, VT, Src,
7399       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7400 }
7401 
7402 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is
7403 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself.
7404 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does
7405 // not undo itself, but they are redundant.
7406 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) {
7407   SDValue Src = N->getOperand(0);
7408 
7409   if (Src.getOpcode() != N->getOpcode())
7410     return SDValue();
7411 
7412   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
7413       !isa<ConstantSDNode>(Src.getOperand(1)))
7414     return SDValue();
7415 
7416   unsigned ShAmt1 = N->getConstantOperandVal(1);
7417   unsigned ShAmt2 = Src.getConstantOperandVal(1);
7418   Src = Src.getOperand(0);
7419 
7420   unsigned CombinedShAmt;
7421   if (N->getOpcode() == RISCVISD::GORC || N->getOpcode() == RISCVISD::GORCW)
7422     CombinedShAmt = ShAmt1 | ShAmt2;
7423   else
7424     CombinedShAmt = ShAmt1 ^ ShAmt2;
7425 
7426   if (CombinedShAmt == 0)
7427     return Src;
7428 
7429   SDLoc DL(N);
7430   return DAG.getNode(
7431       N->getOpcode(), DL, N->getValueType(0), Src,
7432       DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType()));
7433 }
7434 
7435 // Combine a constant select operand into its use:
7436 //
7437 // (and (select cond, -1, c), x)
7438 //   -> (select cond, x, (and x, c))  [AllOnes=1]
7439 // (or  (select cond, 0, c), x)
7440 //   -> (select cond, x, (or x, c))  [AllOnes=0]
7441 // (xor (select cond, 0, c), x)
7442 //   -> (select cond, x, (xor x, c))  [AllOnes=0]
7443 // (add (select cond, 0, c), x)
7444 //   -> (select cond, x, (add x, c))  [AllOnes=0]
7445 // (sub x, (select cond, 0, c))
7446 //   -> (select cond, x, (sub x, c))  [AllOnes=0]
7447 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7448                                    SelectionDAG &DAG, bool AllOnes) {
7449   EVT VT = N->getValueType(0);
7450 
7451   // Skip vectors.
7452   if (VT.isVector())
7453     return SDValue();
7454 
7455   if ((Slct.getOpcode() != ISD::SELECT &&
7456        Slct.getOpcode() != RISCVISD::SELECT_CC) ||
7457       !Slct.hasOneUse())
7458     return SDValue();
7459 
7460   auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
7461     return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
7462   };
7463 
7464   bool SwapSelectOps;
7465   unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
7466   SDValue TrueVal = Slct.getOperand(1 + OpOffset);
7467   SDValue FalseVal = Slct.getOperand(2 + OpOffset);
7468   SDValue NonConstantVal;
7469   if (isZeroOrAllOnes(TrueVal, AllOnes)) {
7470     SwapSelectOps = false;
7471     NonConstantVal = FalseVal;
7472   } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
7473     SwapSelectOps = true;
7474     NonConstantVal = TrueVal;
7475   } else
7476     return SDValue();
7477 
7478   // Slct is now know to be the desired identity constant when CC is true.
7479   TrueVal = OtherOp;
7480   FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
7481   // Unless SwapSelectOps says the condition should be false.
7482   if (SwapSelectOps)
7483     std::swap(TrueVal, FalseVal);
7484 
7485   if (Slct.getOpcode() == RISCVISD::SELECT_CC)
7486     return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
7487                        {Slct.getOperand(0), Slct.getOperand(1),
7488                         Slct.getOperand(2), TrueVal, FalseVal});
7489 
7490   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7491                      {Slct.getOperand(0), TrueVal, FalseVal});
7492 }
7493 
7494 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7495 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
7496                                               bool AllOnes) {
7497   SDValue N0 = N->getOperand(0);
7498   SDValue N1 = N->getOperand(1);
7499   if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes))
7500     return Result;
7501   if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes))
7502     return Result;
7503   return SDValue();
7504 }
7505 
7506 // Transform (add (mul x, c0), c1) ->
7507 //           (add (mul (add x, c1/c0), c0), c1%c0).
7508 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
7509 // that should be excluded is when c0*(c1/c0) is simm12, which will lead
7510 // to an infinite loop in DAGCombine if transformed.
7511 // Or transform (add (mul x, c0), c1) ->
7512 //              (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
7513 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
7514 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
7515 // lead to an infinite loop in DAGCombine if transformed.
7516 // Or transform (add (mul x, c0), c1) ->
7517 //              (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
7518 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
7519 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
7520 // lead to an infinite loop in DAGCombine if transformed.
7521 // Or transform (add (mul x, c0), c1) ->
7522 //              (mul (add x, c1/c0), c0).
7523 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
7524 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
7525                                      const RISCVSubtarget &Subtarget) {
7526   // Skip for vector types and larger types.
7527   EVT VT = N->getValueType(0);
7528   if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
7529     return SDValue();
7530   // The first operand node must be a MUL and has no other use.
7531   SDValue N0 = N->getOperand(0);
7532   if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
7533     return SDValue();
7534   // Check if c0 and c1 match above conditions.
7535   auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7536   auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7537   if (!N0C || !N1C)
7538     return SDValue();
7539   // If N0C has multiple uses it's possible one of the cases in
7540   // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
7541   // in an infinite loop.
7542   if (!N0C->hasOneUse())
7543     return SDValue();
7544   int64_t C0 = N0C->getSExtValue();
7545   int64_t C1 = N1C->getSExtValue();
7546   int64_t CA, CB;
7547   if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
7548     return SDValue();
7549   // Search for proper CA (non-zero) and CB that both are simm12.
7550   if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
7551       !isInt<12>(C0 * (C1 / C0))) {
7552     CA = C1 / C0;
7553     CB = C1 % C0;
7554   } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
7555              isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
7556     CA = C1 / C0 + 1;
7557     CB = C1 % C0 - C0;
7558   } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
7559              isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
7560     CA = C1 / C0 - 1;
7561     CB = C1 % C0 + C0;
7562   } else
7563     return SDValue();
7564   // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
7565   SDLoc DL(N);
7566   SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
7567                              DAG.getConstant(CA, DL, VT));
7568   SDValue New1 =
7569       DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
7570   return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
7571 }
7572 
7573 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
7574                                  const RISCVSubtarget &Subtarget) {
7575   if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
7576     return V;
7577   if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
7578     return V;
7579   // fold (add (select lhs, rhs, cc, 0, y), x) ->
7580   //      (select lhs, rhs, cc, x, (add x, y))
7581   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7582 }
7583 
7584 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) {
7585   // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
7586   //      (select lhs, rhs, cc, x, (sub x, y))
7587   SDValue N0 = N->getOperand(0);
7588   SDValue N1 = N->getOperand(1);
7589   return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false);
7590 }
7591 
7592 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) {
7593   // fold (and (select lhs, rhs, cc, -1, y), x) ->
7594   //      (select lhs, rhs, cc, x, (and x, y))
7595   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true);
7596 }
7597 
7598 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
7599                                 const RISCVSubtarget &Subtarget) {
7600   if (Subtarget.hasStdExtZbp()) {
7601     if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget))
7602       return GREV;
7603     if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget))
7604       return GORC;
7605     if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget))
7606       return SHFL;
7607   }
7608 
7609   // fold (or (select cond, 0, y), x) ->
7610   //      (select cond, x, (or x, y))
7611   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7612 }
7613 
7614 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) {
7615   // fold (xor (select cond, 0, y), x) ->
7616   //      (select cond, x, (xor x, y))
7617   return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false);
7618 }
7619 
7620 static SDValue
7621 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
7622                                 const RISCVSubtarget &Subtarget) {
7623   SDValue Src = N->getOperand(0);
7624   EVT VT = N->getValueType(0);
7625 
7626   // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
7627   if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
7628       cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
7629     return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
7630                        Src.getOperand(0));
7631 
7632   // Fold (i64 (sext_inreg (abs X), i32)) ->
7633   // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits.
7634   // The (sext_inreg (neg X), i32) will be selected to negw by isel. This
7635   // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user
7636   // of the (i32 (abs X)) is a sext or setcc or something else that causes type
7637   // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have
7638   // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg
7639   // may get combined into an earlier operation so we need to use
7640   // ComputeNumSignBits.
7641   // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for
7642   // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so
7643   // we can't assume that X has 33 sign bits. We must check.
7644   if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() &&
7645       Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 &&
7646       cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 &&
7647       DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) {
7648     SDLoc DL(N);
7649     SDValue Freeze = DAG.getFreeze(Src.getOperand(0));
7650     SDValue Neg =
7651         DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze);
7652     Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg,
7653                       DAG.getValueType(MVT::i32));
7654     return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg);
7655   }
7656 
7657   return SDValue();
7658 }
7659 
7660 // Attempt to turn ANY_EXTEND into SIGN_EXTEND if the input to the ANY_EXTEND
7661 // has users that require SIGN_EXTEND and the SIGN_EXTEND can be done for free
7662 // by an instruction like ADDW/SUBW/MULW. Without this the ANY_EXTEND would be
7663 // removed during type legalization leaving an ADD/SUB/MUL use that won't use
7664 // ADDW/SUBW/MULW.
7665 static SDValue performANY_EXTENDCombine(SDNode *N,
7666                                         TargetLowering::DAGCombinerInfo &DCI,
7667                                         const RISCVSubtarget &Subtarget) {
7668   if (!Subtarget.is64Bit())
7669     return SDValue();
7670 
7671   SelectionDAG &DAG = DCI.DAG;
7672 
7673   SDValue Src = N->getOperand(0);
7674   EVT VT = N->getValueType(0);
7675   if (VT != MVT::i64 || Src.getValueType() != MVT::i32)
7676     return SDValue();
7677 
7678   // The opcode must be one that can implicitly sign_extend.
7679   // FIXME: Additional opcodes.
7680   switch (Src.getOpcode()) {
7681   default:
7682     return SDValue();
7683   case ISD::MUL:
7684     if (!Subtarget.hasStdExtM())
7685       return SDValue();
7686     LLVM_FALLTHROUGH;
7687   case ISD::ADD:
7688   case ISD::SUB:
7689     break;
7690   }
7691 
7692   // Only handle cases where the result is used by a CopyToReg. That likely
7693   // means the value is a liveout of the basic block. This helps prevent
7694   // infinite combine loops like PR51206.
7695   if (none_of(N->uses(),
7696               [](SDNode *User) { return User->getOpcode() == ISD::CopyToReg; }))
7697     return SDValue();
7698 
7699   SmallVector<SDNode *, 4> SetCCs;
7700   for (SDNode::use_iterator UI = Src.getNode()->use_begin(),
7701                             UE = Src.getNode()->use_end();
7702        UI != UE; ++UI) {
7703     SDNode *User = *UI;
7704     if (User == N)
7705       continue;
7706     if (UI.getUse().getResNo() != Src.getResNo())
7707       continue;
7708     // All i32 setccs are legalized by sign extending operands.
7709     if (User->getOpcode() == ISD::SETCC) {
7710       SetCCs.push_back(User);
7711       continue;
7712     }
7713     // We don't know if we can extend this user.
7714     break;
7715   }
7716 
7717   // If we don't have any SetCCs, this isn't worthwhile.
7718   if (SetCCs.empty())
7719     return SDValue();
7720 
7721   SDLoc DL(N);
7722   SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Src);
7723   DCI.CombineTo(N, SExt);
7724 
7725   // Promote all the setccs.
7726   for (SDNode *SetCC : SetCCs) {
7727     SmallVector<SDValue, 4> Ops;
7728 
7729     for (unsigned j = 0; j != 2; ++j) {
7730       SDValue SOp = SetCC->getOperand(j);
7731       if (SOp == Src)
7732         Ops.push_back(SExt);
7733       else
7734         Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, SOp));
7735     }
7736 
7737     Ops.push_back(SetCC->getOperand(2));
7738     DCI.CombineTo(SetCC,
7739                   DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
7740   }
7741   return SDValue(N, 0);
7742 }
7743 
7744 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to
7745 // vwadd(u).vv/vx or vwsub(u).vv/vx.
7746 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG,
7747                                              bool Commute = false) {
7748   assert((N->getOpcode() == RISCVISD::ADD_VL ||
7749           N->getOpcode() == RISCVISD::SUB_VL) &&
7750          "Unexpected opcode");
7751   bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL;
7752   SDValue Op0 = N->getOperand(0);
7753   SDValue Op1 = N->getOperand(1);
7754   if (Commute)
7755     std::swap(Op0, Op1);
7756 
7757   MVT VT = N->getSimpleValueType(0);
7758 
7759   // Determine the narrow size for a widening add/sub.
7760   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7761   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7762                                   VT.getVectorElementCount());
7763 
7764   SDValue Mask = N->getOperand(2);
7765   SDValue VL = N->getOperand(3);
7766 
7767   SDLoc DL(N);
7768 
7769   // If the RHS is a sext or zext, we can form a widening op.
7770   if ((Op1.getOpcode() == RISCVISD::VZEXT_VL ||
7771        Op1.getOpcode() == RISCVISD::VSEXT_VL) &&
7772       Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) {
7773     unsigned ExtOpc = Op1.getOpcode();
7774     Op1 = Op1.getOperand(0);
7775     // Re-introduce narrower extends if needed.
7776     if (Op1.getValueType() != NarrowVT)
7777       Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7778 
7779     unsigned WOpc;
7780     if (ExtOpc == RISCVISD::VSEXT_VL)
7781       WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL;
7782     else
7783       WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL;
7784 
7785     return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL);
7786   }
7787 
7788   // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
7789   // sext/zext?
7790 
7791   return SDValue();
7792 }
7793 
7794 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or
7795 // vwsub(u).vv/vx.
7796 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) {
7797   SDValue Op0 = N->getOperand(0);
7798   SDValue Op1 = N->getOperand(1);
7799   SDValue Mask = N->getOperand(2);
7800   SDValue VL = N->getOperand(3);
7801 
7802   MVT VT = N->getSimpleValueType(0);
7803   MVT NarrowVT = Op1.getSimpleValueType();
7804   unsigned NarrowSize = NarrowVT.getScalarSizeInBits();
7805 
7806   unsigned VOpc;
7807   switch (N->getOpcode()) {
7808   default: llvm_unreachable("Unexpected opcode");
7809   case RISCVISD::VWADD_W_VL:  VOpc = RISCVISD::VWADD_VL;  break;
7810   case RISCVISD::VWSUB_W_VL:  VOpc = RISCVISD::VWSUB_VL;  break;
7811   case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break;
7812   case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break;
7813   }
7814 
7815   bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7816                   N->getOpcode() == RISCVISD::VWSUB_W_VL;
7817 
7818   SDLoc DL(N);
7819 
7820   // If the LHS is a sext or zext, we can narrow this op to the same size as
7821   // the RHS.
7822   if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) ||
7823        (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) &&
7824       Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) {
7825     unsigned ExtOpc = Op0.getOpcode();
7826     Op0 = Op0.getOperand(0);
7827     // Re-introduce narrower extends if needed.
7828     if (Op0.getValueType() != NarrowVT)
7829       Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7830     return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL);
7831   }
7832 
7833   bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL ||
7834                N->getOpcode() == RISCVISD::VWADDU_W_VL;
7835 
7836   // Look for splats on the left hand side of a vwadd(u).wv. We might be able
7837   // to commute and use a vwadd(u).vx instead.
7838   if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL &&
7839       Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) {
7840     Op0 = Op0.getOperand(1);
7841 
7842     // See if have enough sign bits or zero bits in the scalar to use a
7843     // widening add/sub by splatting to smaller element size.
7844     unsigned EltBits = VT.getScalarSizeInBits();
7845     unsigned ScalarBits = Op0.getValueSizeInBits();
7846     // Make sure we're getting all element bits from the scalar register.
7847     // FIXME: Support implicit sign extension of vmv.v.x?
7848     if (ScalarBits < EltBits)
7849       return SDValue();
7850 
7851     if (IsSigned) {
7852       if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize))
7853         return SDValue();
7854     } else {
7855       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7856       if (!DAG.MaskedValueIsZero(Op0, Mask))
7857         return SDValue();
7858     }
7859 
7860     Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
7861                       DAG.getUNDEF(NarrowVT), Op0, VL);
7862     return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL);
7863   }
7864 
7865   return SDValue();
7866 }
7867 
7868 // Try to form VWMUL, VWMULU or VWMULSU.
7869 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op.
7870 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG,
7871                                        bool Commute) {
7872   assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode");
7873   SDValue Op0 = N->getOperand(0);
7874   SDValue Op1 = N->getOperand(1);
7875   if (Commute)
7876     std::swap(Op0, Op1);
7877 
7878   bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL;
7879   bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL;
7880   bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL;
7881   if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse())
7882     return SDValue();
7883 
7884   SDValue Mask = N->getOperand(2);
7885   SDValue VL = N->getOperand(3);
7886 
7887   // Make sure the mask and VL match.
7888   if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL)
7889     return SDValue();
7890 
7891   MVT VT = N->getSimpleValueType(0);
7892 
7893   // Determine the narrow size for a widening multiply.
7894   unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
7895   MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
7896                                   VT.getVectorElementCount());
7897 
7898   SDLoc DL(N);
7899 
7900   // See if the other operand is the same opcode.
7901   if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) {
7902     if (!Op1.hasOneUse())
7903       return SDValue();
7904 
7905     // Make sure the mask and VL match.
7906     if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL)
7907       return SDValue();
7908 
7909     Op1 = Op1.getOperand(0);
7910   } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) {
7911     // The operand is a splat of a scalar.
7912 
7913     // The pasthru must be undef for tail agnostic
7914     if (!Op1.getOperand(0).isUndef())
7915       return SDValue();
7916     // The VL must be the same.
7917     if (Op1.getOperand(2) != VL)
7918       return SDValue();
7919 
7920     // Get the scalar value.
7921     Op1 = Op1.getOperand(1);
7922 
7923     // See if have enough sign bits or zero bits in the scalar to use a
7924     // widening multiply by splatting to smaller element size.
7925     unsigned EltBits = VT.getScalarSizeInBits();
7926     unsigned ScalarBits = Op1.getValueSizeInBits();
7927     // Make sure we're getting all element bits from the scalar register.
7928     // FIXME: Support implicit sign extension of vmv.v.x?
7929     if (ScalarBits < EltBits)
7930       return SDValue();
7931 
7932     // If the LHS is a sign extend, try to use vwmul.
7933     if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) {
7934       // Can use vwmul.
7935     } else {
7936       // Otherwise try to use vwmulu or vwmulsu.
7937       APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize);
7938       if (DAG.MaskedValueIsZero(Op1, Mask))
7939         IsVWMULSU = IsSignExt;
7940       else
7941         return SDValue();
7942     }
7943 
7944     Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
7945                       DAG.getUNDEF(NarrowVT), Op1, VL);
7946   } else
7947     return SDValue();
7948 
7949   Op0 = Op0.getOperand(0);
7950 
7951   // Re-introduce narrower extends if needed.
7952   unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
7953   if (Op0.getValueType() != NarrowVT)
7954     Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL);
7955   // vwmulsu requires second operand to be zero extended.
7956   ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc;
7957   if (Op1.getValueType() != NarrowVT)
7958     Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL);
7959 
7960   unsigned WMulOpc = RISCVISD::VWMULSU_VL;
7961   if (!IsVWMULSU)
7962     WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
7963   return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL);
7964 }
7965 
7966 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) {
7967   switch (Op.getOpcode()) {
7968   case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE;
7969   case ISD::FTRUNC:     return RISCVFPRndMode::RTZ;
7970   case ISD::FFLOOR:     return RISCVFPRndMode::RDN;
7971   case ISD::FCEIL:      return RISCVFPRndMode::RUP;
7972   case ISD::FROUND:     return RISCVFPRndMode::RMM;
7973   }
7974 
7975   return RISCVFPRndMode::Invalid;
7976 }
7977 
7978 // Fold
7979 //   (fp_to_int (froundeven X)) -> fcvt X, rne
7980 //   (fp_to_int (ftrunc X))     -> fcvt X, rtz
7981 //   (fp_to_int (ffloor X))     -> fcvt X, rdn
7982 //   (fp_to_int (fceil X))      -> fcvt X, rup
7983 //   (fp_to_int (fround X))     -> fcvt X, rmm
7984 static SDValue performFP_TO_INTCombine(SDNode *N,
7985                                        TargetLowering::DAGCombinerInfo &DCI,
7986                                        const RISCVSubtarget &Subtarget) {
7987   SelectionDAG &DAG = DCI.DAG;
7988   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7989   MVT XLenVT = Subtarget.getXLenVT();
7990 
7991   // Only handle XLen or i32 types. Other types narrower than XLen will
7992   // eventually be legalized to XLenVT.
7993   EVT VT = N->getValueType(0);
7994   if (VT != MVT::i32 && VT != XLenVT)
7995     return SDValue();
7996 
7997   SDValue Src = N->getOperand(0);
7998 
7999   // Ensure the FP type is also legal.
8000   if (!TLI.isTypeLegal(Src.getValueType()))
8001     return SDValue();
8002 
8003   // Don't do this for f16 with Zfhmin and not Zfh.
8004   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8005     return SDValue();
8006 
8007   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8008   if (FRM == RISCVFPRndMode::Invalid)
8009     return SDValue();
8010 
8011   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8012 
8013   unsigned Opc;
8014   if (VT == XLenVT)
8015     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8016   else
8017     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8018 
8019   SDLoc DL(N);
8020   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
8021                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8022   return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
8023 }
8024 
8025 // Fold
8026 //   (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
8027 //   (fp_to_int_sat (ftrunc X))     -> (select X == nan, 0, (fcvt X, rtz))
8028 //   (fp_to_int_sat (ffloor X))     -> (select X == nan, 0, (fcvt X, rdn))
8029 //   (fp_to_int_sat (fceil X))      -> (select X == nan, 0, (fcvt X, rup))
8030 //   (fp_to_int_sat (fround X))     -> (select X == nan, 0, (fcvt X, rmm))
8031 static SDValue performFP_TO_INT_SATCombine(SDNode *N,
8032                                        TargetLowering::DAGCombinerInfo &DCI,
8033                                        const RISCVSubtarget &Subtarget) {
8034   SelectionDAG &DAG = DCI.DAG;
8035   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8036   MVT XLenVT = Subtarget.getXLenVT();
8037 
8038   // Only handle XLen types. Other types narrower than XLen will eventually be
8039   // legalized to XLenVT.
8040   EVT DstVT = N->getValueType(0);
8041   if (DstVT != XLenVT)
8042     return SDValue();
8043 
8044   SDValue Src = N->getOperand(0);
8045 
8046   // Ensure the FP type is also legal.
8047   if (!TLI.isTypeLegal(Src.getValueType()))
8048     return SDValue();
8049 
8050   // Don't do this for f16 with Zfhmin and not Zfh.
8051   if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
8052     return SDValue();
8053 
8054   EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8055 
8056   RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src);
8057   if (FRM == RISCVFPRndMode::Invalid)
8058     return SDValue();
8059 
8060   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
8061 
8062   unsigned Opc;
8063   if (SatVT == DstVT)
8064     Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
8065   else if (DstVT == MVT::i64 && SatVT == MVT::i32)
8066     Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
8067   else
8068     return SDValue();
8069   // FIXME: Support other SatVTs by clamping before or after the conversion.
8070 
8071   Src = Src.getOperand(0);
8072 
8073   SDLoc DL(N);
8074   SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
8075                                 DAG.getTargetConstant(FRM, DL, XLenVT));
8076 
8077   // RISCV FP-to-int conversions saturate to the destination register size, but
8078   // don't produce 0 for nan.
8079   SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
8080   return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
8081 }
8082 
8083 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
8084                                                DAGCombinerInfo &DCI) const {
8085   SelectionDAG &DAG = DCI.DAG;
8086 
8087   // Helper to call SimplifyDemandedBits on an operand of N where only some low
8088   // bits are demanded. N will be added to the Worklist if it was not deleted.
8089   // Caller should return SDValue(N, 0) if this returns true.
8090   auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
8091     SDValue Op = N->getOperand(OpNo);
8092     APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
8093     if (!SimplifyDemandedBits(Op, Mask, DCI))
8094       return false;
8095 
8096     if (N->getOpcode() != ISD::DELETED_NODE)
8097       DCI.AddToWorklist(N);
8098     return true;
8099   };
8100 
8101   switch (N->getOpcode()) {
8102   default:
8103     break;
8104   case RISCVISD::SplitF64: {
8105     SDValue Op0 = N->getOperand(0);
8106     // If the input to SplitF64 is just BuildPairF64 then the operation is
8107     // redundant. Instead, use BuildPairF64's operands directly.
8108     if (Op0->getOpcode() == RISCVISD::BuildPairF64)
8109       return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
8110 
8111     if (Op0->isUndef()) {
8112       SDValue Lo = DAG.getUNDEF(MVT::i32);
8113       SDValue Hi = DAG.getUNDEF(MVT::i32);
8114       return DCI.CombineTo(N, Lo, Hi);
8115     }
8116 
8117     SDLoc DL(N);
8118 
8119     // It's cheaper to materialise two 32-bit integers than to load a double
8120     // from the constant pool and transfer it to integer registers through the
8121     // stack.
8122     if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
8123       APInt V = C->getValueAPF().bitcastToAPInt();
8124       SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
8125       SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
8126       return DCI.CombineTo(N, Lo, Hi);
8127     }
8128 
8129     // This is a target-specific version of a DAGCombine performed in
8130     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8131     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8132     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8133     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8134         !Op0.getNode()->hasOneUse())
8135       break;
8136     SDValue NewSplitF64 =
8137         DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
8138                     Op0.getOperand(0));
8139     SDValue Lo = NewSplitF64.getValue(0);
8140     SDValue Hi = NewSplitF64.getValue(1);
8141     APInt SignBit = APInt::getSignMask(32);
8142     if (Op0.getOpcode() == ISD::FNEG) {
8143       SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
8144                                   DAG.getConstant(SignBit, DL, MVT::i32));
8145       return DCI.CombineTo(N, Lo, NewHi);
8146     }
8147     assert(Op0.getOpcode() == ISD::FABS);
8148     SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
8149                                 DAG.getConstant(~SignBit, DL, MVT::i32));
8150     return DCI.CombineTo(N, Lo, NewHi);
8151   }
8152   case RISCVISD::SLLW:
8153   case RISCVISD::SRAW:
8154   case RISCVISD::SRLW: {
8155     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8156     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8157         SimplifyDemandedLowBitsHelper(1, 5))
8158       return SDValue(N, 0);
8159 
8160     break;
8161   }
8162   case ISD::ROTR:
8163   case ISD::ROTL:
8164   case RISCVISD::RORW:
8165   case RISCVISD::ROLW: {
8166     if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) {
8167       // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8168       if (SimplifyDemandedLowBitsHelper(0, 32) ||
8169           SimplifyDemandedLowBitsHelper(1, 5))
8170         return SDValue(N, 0);
8171     }
8172 
8173     return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget);
8174   }
8175   case RISCVISD::CLZW:
8176   case RISCVISD::CTZW: {
8177     // Only the lower 32 bits of the first operand are read
8178     if (SimplifyDemandedLowBitsHelper(0, 32))
8179       return SDValue(N, 0);
8180     break;
8181   }
8182   case RISCVISD::GREV:
8183   case RISCVISD::GORC: {
8184     // Only the lower log2(Bitwidth) bits of the the shift amount are read.
8185     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8186     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8187     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth)))
8188       return SDValue(N, 0);
8189 
8190     return combineGREVI_GORCI(N, DAG);
8191   }
8192   case RISCVISD::GREVW:
8193   case RISCVISD::GORCW: {
8194     // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
8195     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8196         SimplifyDemandedLowBitsHelper(1, 5))
8197       return SDValue(N, 0);
8198 
8199     return combineGREVI_GORCI(N, DAG);
8200   }
8201   case RISCVISD::SHFL:
8202   case RISCVISD::UNSHFL: {
8203     // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read.
8204     unsigned BitWidth = N->getOperand(1).getValueSizeInBits();
8205     assert(isPowerOf2_32(BitWidth) && "Unexpected bit width");
8206     if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1))
8207       return SDValue(N, 0);
8208 
8209     break;
8210   }
8211   case RISCVISD::SHFLW:
8212   case RISCVISD::UNSHFLW: {
8213     // Only the lower 32 bits of LHS and lower 4 bits of RHS are read.
8214     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8215         SimplifyDemandedLowBitsHelper(1, 4))
8216       return SDValue(N, 0);
8217 
8218     break;
8219   }
8220   case RISCVISD::BCOMPRESSW:
8221   case RISCVISD::BDECOMPRESSW: {
8222     // Only the lower 32 bits of LHS and RHS are read.
8223     if (SimplifyDemandedLowBitsHelper(0, 32) ||
8224         SimplifyDemandedLowBitsHelper(1, 32))
8225       return SDValue(N, 0);
8226 
8227     break;
8228   }
8229   case RISCVISD::FMV_X_ANYEXTH:
8230   case RISCVISD::FMV_X_ANYEXTW_RV64: {
8231     SDLoc DL(N);
8232     SDValue Op0 = N->getOperand(0);
8233     MVT VT = N->getSimpleValueType(0);
8234     // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
8235     // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
8236     // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
8237     if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
8238          Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
8239         (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
8240          Op0->getOpcode() == RISCVISD::FMV_H_X)) {
8241       assert(Op0.getOperand(0).getValueType() == VT &&
8242              "Unexpected value type!");
8243       return Op0.getOperand(0);
8244     }
8245 
8246     // This is a target-specific version of a DAGCombine performed in
8247     // DAGCombiner::visitBITCAST. It performs the equivalent of:
8248     // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
8249     // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
8250     if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
8251         !Op0.getNode()->hasOneUse())
8252       break;
8253     SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
8254     unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
8255     APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits());
8256     if (Op0.getOpcode() == ISD::FNEG)
8257       return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
8258                          DAG.getConstant(SignBit, DL, VT));
8259 
8260     assert(Op0.getOpcode() == ISD::FABS);
8261     return DAG.getNode(ISD::AND, DL, VT, NewFMV,
8262                        DAG.getConstant(~SignBit, DL, VT));
8263   }
8264   case ISD::ADD:
8265     return performADDCombine(N, DAG, Subtarget);
8266   case ISD::SUB:
8267     return performSUBCombine(N, DAG);
8268   case ISD::AND:
8269     return performANDCombine(N, DAG);
8270   case ISD::OR:
8271     return performORCombine(N, DAG, Subtarget);
8272   case ISD::XOR:
8273     return performXORCombine(N, DAG);
8274   case ISD::SIGN_EXTEND_INREG:
8275     return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
8276   case ISD::ANY_EXTEND:
8277     return performANY_EXTENDCombine(N, DCI, Subtarget);
8278   case ISD::ZERO_EXTEND:
8279     // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
8280     // type legalization. This is safe because fp_to_uint produces poison if
8281     // it overflows.
8282     if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
8283       SDValue Src = N->getOperand(0);
8284       if (Src.getOpcode() == ISD::FP_TO_UINT &&
8285           isTypeLegal(Src.getOperand(0).getValueType()))
8286         return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
8287                            Src.getOperand(0));
8288       if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
8289           isTypeLegal(Src.getOperand(1).getValueType())) {
8290         SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
8291         SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
8292                                   Src.getOperand(0), Src.getOperand(1));
8293         DCI.CombineTo(N, Res);
8294         DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
8295         DCI.recursivelyDeleteUnusedNodes(Src.getNode());
8296         return SDValue(N, 0); // Return N so it doesn't get rechecked.
8297       }
8298     }
8299     return SDValue();
8300   case RISCVISD::SELECT_CC: {
8301     // Transform
8302     SDValue LHS = N->getOperand(0);
8303     SDValue RHS = N->getOperand(1);
8304     SDValue TrueV = N->getOperand(3);
8305     SDValue FalseV = N->getOperand(4);
8306 
8307     // If the True and False values are the same, we don't need a select_cc.
8308     if (TrueV == FalseV)
8309       return TrueV;
8310 
8311     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get();
8312     if (!ISD::isIntEqualitySetCC(CCVal))
8313       break;
8314 
8315     // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) ->
8316     //      (select_cc X, Y, lt, trueV, falseV)
8317     // Sometimes the setcc is introduced after select_cc has been formed.
8318     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8319         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8320       // If we're looking for eq 0 instead of ne 0, we need to invert the
8321       // condition.
8322       bool Invert = CCVal == ISD::SETEQ;
8323       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8324       if (Invert)
8325         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8326 
8327       SDLoc DL(N);
8328       RHS = LHS.getOperand(1);
8329       LHS = LHS.getOperand(0);
8330       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8331 
8332       SDValue TargetCC = DAG.getCondCode(CCVal);
8333       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8334                          {LHS, RHS, TargetCC, TrueV, FalseV});
8335     }
8336 
8337     // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) ->
8338     //      (select_cc X, Y, eq/ne, trueV, falseV)
8339     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8340       return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0),
8341                          {LHS.getOperand(0), LHS.getOperand(1),
8342                           N->getOperand(2), TrueV, FalseV});
8343     // (select_cc X, 1, setne, trueV, falseV) ->
8344     // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1.
8345     // This can occur when legalizing some floating point comparisons.
8346     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8347     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8348       SDLoc DL(N);
8349       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8350       SDValue TargetCC = DAG.getCondCode(CCVal);
8351       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8352       return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
8353                          {LHS, RHS, TargetCC, TrueV, FalseV});
8354     }
8355 
8356     break;
8357   }
8358   case RISCVISD::BR_CC: {
8359     SDValue LHS = N->getOperand(1);
8360     SDValue RHS = N->getOperand(2);
8361     ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get();
8362     if (!ISD::isIntEqualitySetCC(CCVal))
8363       break;
8364 
8365     // Fold (br_cc (setlt X, Y), 0, ne, dest) ->
8366     //      (br_cc X, Y, lt, dest)
8367     // Sometimes the setcc is introduced after br_cc has been formed.
8368     if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
8369         LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
8370       // If we're looking for eq 0 instead of ne 0, we need to invert the
8371       // condition.
8372       bool Invert = CCVal == ISD::SETEQ;
8373       CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8374       if (Invert)
8375         CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8376 
8377       SDLoc DL(N);
8378       RHS = LHS.getOperand(1);
8379       LHS = LHS.getOperand(0);
8380       translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
8381 
8382       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8383                          N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal),
8384                          N->getOperand(4));
8385     }
8386 
8387     // Fold (br_cc (xor X, Y), 0, eq/ne, dest) ->
8388     //      (br_cc X, Y, eq/ne, trueV, falseV)
8389     if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS))
8390       return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0),
8391                          N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1),
8392                          N->getOperand(3), N->getOperand(4));
8393 
8394     // (br_cc X, 1, setne, br_cc) ->
8395     // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1.
8396     // This can occur when legalizing some floating point comparisons.
8397     APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
8398     if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
8399       SDLoc DL(N);
8400       CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
8401       SDValue TargetCC = DAG.getCondCode(CCVal);
8402       RHS = DAG.getConstant(0, DL, LHS.getValueType());
8403       return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
8404                          N->getOperand(0), LHS, RHS, TargetCC,
8405                          N->getOperand(4));
8406     }
8407     break;
8408   }
8409   case ISD::FP_TO_SINT:
8410   case ISD::FP_TO_UINT:
8411     return performFP_TO_INTCombine(N, DCI, Subtarget);
8412   case ISD::FP_TO_SINT_SAT:
8413   case ISD::FP_TO_UINT_SAT:
8414     return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
8415   case ISD::FCOPYSIGN: {
8416     EVT VT = N->getValueType(0);
8417     if (!VT.isVector())
8418       break;
8419     // There is a form of VFSGNJ which injects the negated sign of its second
8420     // operand. Try and bubble any FNEG up after the extend/round to produce
8421     // this optimized pattern. Avoid modifying cases where FP_ROUND and
8422     // TRUNC=1.
8423     SDValue In2 = N->getOperand(1);
8424     // Avoid cases where the extend/round has multiple uses, as duplicating
8425     // those is typically more expensive than removing a fneg.
8426     if (!In2.hasOneUse())
8427       break;
8428     if (In2.getOpcode() != ISD::FP_EXTEND &&
8429         (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
8430       break;
8431     In2 = In2.getOperand(0);
8432     if (In2.getOpcode() != ISD::FNEG)
8433       break;
8434     SDLoc DL(N);
8435     SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
8436     return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
8437                        DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
8438   }
8439   case ISD::MGATHER:
8440   case ISD::MSCATTER:
8441   case ISD::VP_GATHER:
8442   case ISD::VP_SCATTER: {
8443     if (!DCI.isBeforeLegalize())
8444       break;
8445     SDValue Index, ScaleOp;
8446     bool IsIndexScaled = false;
8447     bool IsIndexSigned = false;
8448     if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
8449       Index = VPGSN->getIndex();
8450       ScaleOp = VPGSN->getScale();
8451       IsIndexScaled = VPGSN->isIndexScaled();
8452       IsIndexSigned = VPGSN->isIndexSigned();
8453     } else {
8454       const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
8455       Index = MGSN->getIndex();
8456       ScaleOp = MGSN->getScale();
8457       IsIndexScaled = MGSN->isIndexScaled();
8458       IsIndexSigned = MGSN->isIndexSigned();
8459     }
8460     EVT IndexVT = Index.getValueType();
8461     MVT XLenVT = Subtarget.getXLenVT();
8462     // RISCV indexed loads only support the "unsigned unscaled" addressing
8463     // mode, so anything else must be manually legalized.
8464     bool NeedsIdxLegalization =
8465         IsIndexScaled ||
8466         (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
8467     if (!NeedsIdxLegalization)
8468       break;
8469 
8470     SDLoc DL(N);
8471 
8472     // Any index legalization should first promote to XLenVT, so we don't lose
8473     // bits when scaling. This may create an illegal index type so we let
8474     // LLVM's legalization take care of the splitting.
8475     // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
8476     if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
8477       IndexVT = IndexVT.changeVectorElementType(XLenVT);
8478       Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8479                           DL, IndexVT, Index);
8480     }
8481 
8482     unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue();
8483     if (IsIndexScaled && Scale != 1) {
8484       // Manually scale the indices by the element size.
8485       // TODO: Sanitize the scale operand here?
8486       // TODO: For VP nodes, should we use VP_SHL here?
8487       assert(isPowerOf2_32(Scale) && "Expecting power-of-two types");
8488       SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT);
8489       Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale);
8490     }
8491 
8492     ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED;
8493     if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
8494       return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
8495                              {VPGN->getChain(), VPGN->getBasePtr(), Index,
8496                               VPGN->getScale(), VPGN->getMask(),
8497                               VPGN->getVectorLength()},
8498                              VPGN->getMemOperand(), NewIndexTy);
8499     if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
8500       return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
8501                               {VPSN->getChain(), VPSN->getValue(),
8502                                VPSN->getBasePtr(), Index, VPSN->getScale(),
8503                                VPSN->getMask(), VPSN->getVectorLength()},
8504                               VPSN->getMemOperand(), NewIndexTy);
8505     if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
8506       return DAG.getMaskedGather(
8507           N->getVTList(), MGN->getMemoryVT(), DL,
8508           {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
8509            MGN->getBasePtr(), Index, MGN->getScale()},
8510           MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
8511     const auto *MSN = cast<MaskedScatterSDNode>(N);
8512     return DAG.getMaskedScatter(
8513         N->getVTList(), MSN->getMemoryVT(), DL,
8514         {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
8515          Index, MSN->getScale()},
8516         MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
8517   }
8518   case RISCVISD::SRA_VL:
8519   case RISCVISD::SRL_VL:
8520   case RISCVISD::SHL_VL: {
8521     SDValue ShAmt = N->getOperand(1);
8522     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8523       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8524       SDLoc DL(N);
8525       SDValue VL = N->getOperand(3);
8526       EVT VT = N->getValueType(0);
8527       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8528                           ShAmt.getOperand(1), VL);
8529       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
8530                          N->getOperand(2), N->getOperand(3));
8531     }
8532     break;
8533   }
8534   case ISD::SRA:
8535   case ISD::SRL:
8536   case ISD::SHL: {
8537     SDValue ShAmt = N->getOperand(1);
8538     if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
8539       // We don't need the upper 32 bits of a 64-bit element for a shift amount.
8540       SDLoc DL(N);
8541       EVT VT = N->getValueType(0);
8542       ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
8543                           ShAmt.getOperand(1),
8544                           DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
8545       return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
8546     }
8547     break;
8548   }
8549   case RISCVISD::ADD_VL:
8550     if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false))
8551       return V;
8552     return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true);
8553   case RISCVISD::SUB_VL:
8554     return combineADDSUB_VLToVWADDSUB_VL(N, DAG);
8555   case RISCVISD::VWADD_W_VL:
8556   case RISCVISD::VWADDU_W_VL:
8557   case RISCVISD::VWSUB_W_VL:
8558   case RISCVISD::VWSUBU_W_VL:
8559     return combineVWADD_W_VL_VWSUB_W_VL(N, DAG);
8560   case RISCVISD::MUL_VL:
8561     if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false))
8562       return V;
8563     // Mul is commutative.
8564     return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true);
8565   case ISD::STORE: {
8566     auto *Store = cast<StoreSDNode>(N);
8567     SDValue Val = Store->getValue();
8568     // Combine store of vmv.x.s to vse with VL of 1.
8569     // FIXME: Support FP.
8570     if (Val.getOpcode() == RISCVISD::VMV_X_S) {
8571       SDValue Src = Val.getOperand(0);
8572       EVT VecVT = Src.getValueType();
8573       EVT MemVT = Store->getMemoryVT();
8574       // The memory VT and the element type must match.
8575       if (VecVT.getVectorElementType() == MemVT) {
8576         SDLoc DL(N);
8577         MVT MaskVT = MVT::getVectorVT(MVT::i1, VecVT.getVectorElementCount());
8578         return DAG.getStoreVP(
8579             Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
8580             DAG.getConstant(1, DL, MaskVT),
8581             DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
8582             Store->getMemOperand(), Store->getAddressingMode(),
8583             Store->isTruncatingStore(), /*IsCompress*/ false);
8584       }
8585     }
8586 
8587     break;
8588   }
8589   case ISD::SPLAT_VECTOR: {
8590     EVT VT = N->getValueType(0);
8591     // Only perform this combine on legal MVT types.
8592     if (!isTypeLegal(VT))
8593       break;
8594     if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
8595                                          DAG, Subtarget))
8596       return Gather;
8597     break;
8598   }
8599   case RISCVISD::VMV_V_X_VL: {
8600     // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
8601     // scalar input.
8602     unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
8603     unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
8604     if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
8605       if (SimplifyDemandedLowBitsHelper(1, EltWidth))
8606         return SDValue(N, 0);
8607 
8608     break;
8609   }
8610   case ISD::INTRINSIC_WO_CHAIN: {
8611     unsigned IntNo = N->getConstantOperandVal(0);
8612     switch (IntNo) {
8613       // By default we do not combine any intrinsic.
8614     default:
8615       return SDValue();
8616     case Intrinsic::riscv_vcpop:
8617     case Intrinsic::riscv_vcpop_mask:
8618     case Intrinsic::riscv_vfirst:
8619     case Intrinsic::riscv_vfirst_mask: {
8620       SDValue VL = N->getOperand(2);
8621       if (IntNo == Intrinsic::riscv_vcpop_mask ||
8622           IntNo == Intrinsic::riscv_vfirst_mask)
8623         VL = N->getOperand(3);
8624       if (!isNullConstant(VL))
8625         return SDValue();
8626       // If VL is 0, vcpop -> li 0, vfirst -> li -1.
8627       SDLoc DL(N);
8628       EVT VT = N->getValueType(0);
8629       if (IntNo == Intrinsic::riscv_vfirst ||
8630           IntNo == Intrinsic::riscv_vfirst_mask)
8631         return DAG.getConstant(-1, DL, VT);
8632       return DAG.getConstant(0, DL, VT);
8633     }
8634     }
8635   }
8636   }
8637 
8638   return SDValue();
8639 }
8640 
8641 bool RISCVTargetLowering::isDesirableToCommuteWithShift(
8642     const SDNode *N, CombineLevel Level) const {
8643   // The following folds are only desirable if `(OP _, c1 << c2)` can be
8644   // materialised in fewer instructions than `(OP _, c1)`:
8645   //
8646   //   (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
8647   //   (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
8648   SDValue N0 = N->getOperand(0);
8649   EVT Ty = N0.getValueType();
8650   if (Ty.isScalarInteger() &&
8651       (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
8652     auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
8653     auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
8654     if (C1 && C2) {
8655       const APInt &C1Int = C1->getAPIntValue();
8656       APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
8657 
8658       // We can materialise `c1 << c2` into an add immediate, so it's "free",
8659       // and the combine should happen, to potentially allow further combines
8660       // later.
8661       if (ShiftedC1Int.getMinSignedBits() <= 64 &&
8662           isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
8663         return true;
8664 
8665       // We can materialise `c1` in an add immediate, so it's "free", and the
8666       // combine should be prevented.
8667       if (C1Int.getMinSignedBits() <= 64 &&
8668           isLegalAddImmediate(C1Int.getSExtValue()))
8669         return false;
8670 
8671       // Neither constant will fit into an immediate, so find materialisation
8672       // costs.
8673       int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
8674                                               Subtarget.getFeatureBits(),
8675                                               /*CompressionCost*/true);
8676       int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
8677           ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
8678           /*CompressionCost*/true);
8679 
8680       // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
8681       // combine should be prevented.
8682       if (C1Cost < ShiftedC1Cost)
8683         return false;
8684     }
8685   }
8686   return true;
8687 }
8688 
8689 bool RISCVTargetLowering::targetShrinkDemandedConstant(
8690     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
8691     TargetLoweringOpt &TLO) const {
8692   // Delay this optimization as late as possible.
8693   if (!TLO.LegalOps)
8694     return false;
8695 
8696   EVT VT = Op.getValueType();
8697   if (VT.isVector())
8698     return false;
8699 
8700   // Only handle AND for now.
8701   if (Op.getOpcode() != ISD::AND)
8702     return false;
8703 
8704   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8705   if (!C)
8706     return false;
8707 
8708   const APInt &Mask = C->getAPIntValue();
8709 
8710   // Clear all non-demanded bits initially.
8711   APInt ShrunkMask = Mask & DemandedBits;
8712 
8713   // Try to make a smaller immediate by setting undemanded bits.
8714 
8715   APInt ExpandedMask = Mask | ~DemandedBits;
8716 
8717   auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
8718     return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
8719   };
8720   auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool {
8721     if (NewMask == Mask)
8722       return true;
8723     SDLoc DL(Op);
8724     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
8725     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
8726     return TLO.CombineTo(Op, NewOp);
8727   };
8728 
8729   // If the shrunk mask fits in sign extended 12 bits, let the target
8730   // independent code apply it.
8731   if (ShrunkMask.isSignedIntN(12))
8732     return false;
8733 
8734   // Preserve (and X, 0xffff) when zext.h is supported.
8735   if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) {
8736     APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
8737     if (IsLegalMask(NewMask))
8738       return UseMask(NewMask);
8739   }
8740 
8741   // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
8742   if (VT == MVT::i64) {
8743     APInt NewMask = APInt(64, 0xffffffff);
8744     if (IsLegalMask(NewMask))
8745       return UseMask(NewMask);
8746   }
8747 
8748   // For the remaining optimizations, we need to be able to make a negative
8749   // number through a combination of mask and undemanded bits.
8750   if (!ExpandedMask.isNegative())
8751     return false;
8752 
8753   // What is the fewest number of bits we need to represent the negative number.
8754   unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
8755 
8756   // Try to make a 12 bit negative immediate. If that fails try to make a 32
8757   // bit negative immediate unless the shrunk immediate already fits in 32 bits.
8758   APInt NewMask = ShrunkMask;
8759   if (MinSignedBits <= 12)
8760     NewMask.setBitsFrom(11);
8761   else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
8762     NewMask.setBitsFrom(31);
8763   else
8764     return false;
8765 
8766   // Check that our new mask is a subset of the demanded mask.
8767   assert(IsLegalMask(NewMask));
8768   return UseMask(NewMask);
8769 }
8770 
8771 static void computeGREV(APInt &Src, unsigned ShAmt) {
8772   ShAmt &= Src.getBitWidth() - 1;
8773   uint64_t x = Src.getZExtValue();
8774   if (ShAmt & 1)
8775     x = ((x & 0x5555555555555555LL) << 1) | ((x & 0xAAAAAAAAAAAAAAAALL) >> 1);
8776   if (ShAmt & 2)
8777     x = ((x & 0x3333333333333333LL) << 2) | ((x & 0xCCCCCCCCCCCCCCCCLL) >> 2);
8778   if (ShAmt & 4)
8779     x = ((x & 0x0F0F0F0F0F0F0F0FLL) << 4) | ((x & 0xF0F0F0F0F0F0F0F0LL) >> 4);
8780   if (ShAmt & 8)
8781     x = ((x & 0x00FF00FF00FF00FFLL) << 8) | ((x & 0xFF00FF00FF00FF00LL) >> 8);
8782   if (ShAmt & 16)
8783     x = ((x & 0x0000FFFF0000FFFFLL) << 16) | ((x & 0xFFFF0000FFFF0000LL) >> 16);
8784   if (ShAmt & 32)
8785     x = ((x & 0x00000000FFFFFFFFLL) << 32) | ((x & 0xFFFFFFFF00000000LL) >> 32);
8786   Src = x;
8787 }
8788 
8789 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8790                                                         KnownBits &Known,
8791                                                         const APInt &DemandedElts,
8792                                                         const SelectionDAG &DAG,
8793                                                         unsigned Depth) const {
8794   unsigned BitWidth = Known.getBitWidth();
8795   unsigned Opc = Op.getOpcode();
8796   assert((Opc >= ISD::BUILTIN_OP_END ||
8797           Opc == ISD::INTRINSIC_WO_CHAIN ||
8798           Opc == ISD::INTRINSIC_W_CHAIN ||
8799           Opc == ISD::INTRINSIC_VOID) &&
8800          "Should use MaskedValueIsZero if you don't know whether Op"
8801          " is a target node!");
8802 
8803   Known.resetAll();
8804   switch (Opc) {
8805   default: break;
8806   case RISCVISD::SELECT_CC: {
8807     Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
8808     // If we don't know any bits, early out.
8809     if (Known.isUnknown())
8810       break;
8811     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
8812 
8813     // Only known if known in both the LHS and RHS.
8814     Known = KnownBits::commonBits(Known, Known2);
8815     break;
8816   }
8817   case RISCVISD::REMUW: {
8818     KnownBits Known2;
8819     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8820     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8821     // We only care about the lower 32 bits.
8822     Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
8823     // Restore the original width by sign extending.
8824     Known = Known.sext(BitWidth);
8825     break;
8826   }
8827   case RISCVISD::DIVUW: {
8828     KnownBits Known2;
8829     Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
8830     Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
8831     // We only care about the lower 32 bits.
8832     Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
8833     // Restore the original width by sign extending.
8834     Known = Known.sext(BitWidth);
8835     break;
8836   }
8837   case RISCVISD::CTZW: {
8838     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8839     unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
8840     unsigned LowBits = Log2_32(PossibleTZ) + 1;
8841     Known.Zero.setBitsFrom(LowBits);
8842     break;
8843   }
8844   case RISCVISD::CLZW: {
8845     KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8846     unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
8847     unsigned LowBits = Log2_32(PossibleLZ) + 1;
8848     Known.Zero.setBitsFrom(LowBits);
8849     break;
8850   }
8851   case RISCVISD::GREV:
8852   case RISCVISD::GREVW: {
8853     if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8854       Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
8855       if (Opc == RISCVISD::GREVW)
8856         Known = Known.trunc(32);
8857       unsigned ShAmt = C->getZExtValue();
8858       computeGREV(Known.Zero, ShAmt);
8859       computeGREV(Known.One, ShAmt);
8860       if (Opc == RISCVISD::GREVW)
8861         Known = Known.sext(BitWidth);
8862     }
8863     break;
8864   }
8865   case RISCVISD::READ_VLENB: {
8866     // If we know the minimum VLen from Zvl extensions, we can use that to
8867     // determine the trailing zeros of VLENB.
8868     // FIXME: Limit to 128 bit vectors until we have more testing.
8869     unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8;
8870     if (MinVLenB > 0)
8871       Known.Zero.setLowBits(Log2_32(MinVLenB));
8872     // We assume VLENB is no more than 65536 / 8 bytes.
8873     Known.Zero.setBitsFrom(14);
8874     break;
8875   }
8876   case ISD::INTRINSIC_W_CHAIN:
8877   case ISD::INTRINSIC_WO_CHAIN: {
8878     unsigned IntNo =
8879         Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
8880     switch (IntNo) {
8881     default:
8882       // We can't do anything for most intrinsics.
8883       break;
8884     case Intrinsic::riscv_vsetvli:
8885     case Intrinsic::riscv_vsetvlimax:
8886     case Intrinsic::riscv_vsetvli_opt:
8887     case Intrinsic::riscv_vsetvlimax_opt:
8888       // Assume that VL output is positive and would fit in an int32_t.
8889       // TODO: VLEN might be capped at 16 bits in a future V spec update.
8890       if (BitWidth >= 32)
8891         Known.Zero.setBitsFrom(31);
8892       break;
8893     }
8894     break;
8895   }
8896   }
8897 }
8898 
8899 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
8900     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
8901     unsigned Depth) const {
8902   switch (Op.getOpcode()) {
8903   default:
8904     break;
8905   case RISCVISD::SELECT_CC: {
8906     unsigned Tmp =
8907         DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
8908     if (Tmp == 1) return 1;  // Early out.
8909     unsigned Tmp2 =
8910         DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
8911     return std::min(Tmp, Tmp2);
8912   }
8913   case RISCVISD::SLLW:
8914   case RISCVISD::SRAW:
8915   case RISCVISD::SRLW:
8916   case RISCVISD::DIVW:
8917   case RISCVISD::DIVUW:
8918   case RISCVISD::REMUW:
8919   case RISCVISD::ROLW:
8920   case RISCVISD::RORW:
8921   case RISCVISD::GREVW:
8922   case RISCVISD::GORCW:
8923   case RISCVISD::FSLW:
8924   case RISCVISD::FSRW:
8925   case RISCVISD::SHFLW:
8926   case RISCVISD::UNSHFLW:
8927   case RISCVISD::BCOMPRESSW:
8928   case RISCVISD::BDECOMPRESSW:
8929   case RISCVISD::BFPW:
8930   case RISCVISD::FCVT_W_RV64:
8931   case RISCVISD::FCVT_WU_RV64:
8932   case RISCVISD::STRICT_FCVT_W_RV64:
8933   case RISCVISD::STRICT_FCVT_WU_RV64:
8934     // TODO: As the result is sign-extended, this is conservatively correct. A
8935     // more precise answer could be calculated for SRAW depending on known
8936     // bits in the shift amount.
8937     return 33;
8938   case RISCVISD::SHFL:
8939   case RISCVISD::UNSHFL: {
8940     // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word
8941     // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but
8942     // will stay within the upper 32 bits. If there were more than 32 sign bits
8943     // before there will be at least 33 sign bits after.
8944     if (Op.getValueType() == MVT::i64 &&
8945         isa<ConstantSDNode>(Op.getOperand(1)) &&
8946         (Op.getConstantOperandVal(1) & 0x10) == 0) {
8947       unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1);
8948       if (Tmp > 32)
8949         return 33;
8950     }
8951     break;
8952   }
8953   case RISCVISD::VMV_X_S: {
8954     // The number of sign bits of the scalar result is computed by obtaining the
8955     // element type of the input vector operand, subtracting its width from the
8956     // XLEN, and then adding one (sign bit within the element type). If the
8957     // element type is wider than XLen, the least-significant XLEN bits are
8958     // taken.
8959     unsigned XLen = Subtarget.getXLen();
8960     unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
8961     if (EltBits <= XLen)
8962       return XLen - EltBits + 1;
8963     break;
8964   }
8965   }
8966 
8967   return 1;
8968 }
8969 
8970 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
8971                                                   MachineBasicBlock *BB) {
8972   assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
8973 
8974   // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
8975   // Should the count have wrapped while it was being read, we need to try
8976   // again.
8977   // ...
8978   // read:
8979   // rdcycleh x3 # load high word of cycle
8980   // rdcycle  x2 # load low word of cycle
8981   // rdcycleh x4 # load high word of cycle
8982   // bne x3, x4, read # check if high word reads match, otherwise try again
8983   // ...
8984 
8985   MachineFunction &MF = *BB->getParent();
8986   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8987   MachineFunction::iterator It = ++BB->getIterator();
8988 
8989   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8990   MF.insert(It, LoopMBB);
8991 
8992   MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
8993   MF.insert(It, DoneMBB);
8994 
8995   // Transfer the remainder of BB and its successor edges to DoneMBB.
8996   DoneMBB->splice(DoneMBB->begin(), BB,
8997                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8998   DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
8999 
9000   BB->addSuccessor(LoopMBB);
9001 
9002   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9003   Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9004   Register LoReg = MI.getOperand(0).getReg();
9005   Register HiReg = MI.getOperand(1).getReg();
9006   DebugLoc DL = MI.getDebugLoc();
9007 
9008   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
9009   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
9010       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9011       .addReg(RISCV::X0);
9012   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
9013       .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
9014       .addReg(RISCV::X0);
9015   BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
9016       .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
9017       .addReg(RISCV::X0);
9018 
9019   BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
9020       .addReg(HiReg)
9021       .addReg(ReadAgainReg)
9022       .addMBB(LoopMBB);
9023 
9024   LoopMBB->addSuccessor(LoopMBB);
9025   LoopMBB->addSuccessor(DoneMBB);
9026 
9027   MI.eraseFromParent();
9028 
9029   return DoneMBB;
9030 }
9031 
9032 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
9033                                              MachineBasicBlock *BB) {
9034   assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
9035 
9036   MachineFunction &MF = *BB->getParent();
9037   DebugLoc DL = MI.getDebugLoc();
9038   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9039   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9040   Register LoReg = MI.getOperand(0).getReg();
9041   Register HiReg = MI.getOperand(1).getReg();
9042   Register SrcReg = MI.getOperand(2).getReg();
9043   const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
9044   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9045 
9046   TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
9047                           RI);
9048   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9049   MachineMemOperand *MMOLo =
9050       MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
9051   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9052       MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
9053   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
9054       .addFrameIndex(FI)
9055       .addImm(0)
9056       .addMemOperand(MMOLo);
9057   BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
9058       .addFrameIndex(FI)
9059       .addImm(4)
9060       .addMemOperand(MMOHi);
9061   MI.eraseFromParent(); // The pseudo instruction is gone now.
9062   return BB;
9063 }
9064 
9065 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
9066                                                  MachineBasicBlock *BB) {
9067   assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
9068          "Unexpected instruction");
9069 
9070   MachineFunction &MF = *BB->getParent();
9071   DebugLoc DL = MI.getDebugLoc();
9072   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
9073   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
9074   Register DstReg = MI.getOperand(0).getReg();
9075   Register LoReg = MI.getOperand(1).getReg();
9076   Register HiReg = MI.getOperand(2).getReg();
9077   const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
9078   int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
9079 
9080   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
9081   MachineMemOperand *MMOLo =
9082       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
9083   MachineMemOperand *MMOHi = MF.getMachineMemOperand(
9084       MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
9085   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9086       .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
9087       .addFrameIndex(FI)
9088       .addImm(0)
9089       .addMemOperand(MMOLo);
9090   BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
9091       .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
9092       .addFrameIndex(FI)
9093       .addImm(4)
9094       .addMemOperand(MMOHi);
9095   TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI);
9096   MI.eraseFromParent(); // The pseudo instruction is gone now.
9097   return BB;
9098 }
9099 
9100 static bool isSelectPseudo(MachineInstr &MI) {
9101   switch (MI.getOpcode()) {
9102   default:
9103     return false;
9104   case RISCV::Select_GPR_Using_CC_GPR:
9105   case RISCV::Select_FPR16_Using_CC_GPR:
9106   case RISCV::Select_FPR32_Using_CC_GPR:
9107   case RISCV::Select_FPR64_Using_CC_GPR:
9108     return true;
9109   }
9110 }
9111 
9112 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
9113                                         unsigned RelOpcode, unsigned EqOpcode,
9114                                         const RISCVSubtarget &Subtarget) {
9115   DebugLoc DL = MI.getDebugLoc();
9116   Register DstReg = MI.getOperand(0).getReg();
9117   Register Src1Reg = MI.getOperand(1).getReg();
9118   Register Src2Reg = MI.getOperand(2).getReg();
9119   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
9120   Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
9121   const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
9122 
9123   // Save the current FFLAGS.
9124   BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
9125 
9126   auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
9127                  .addReg(Src1Reg)
9128                  .addReg(Src2Reg);
9129   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9130     MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
9131 
9132   // Restore the FFLAGS.
9133   BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
9134       .addReg(SavedFFlags, RegState::Kill);
9135 
9136   // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
9137   auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
9138                   .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
9139                   .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
9140   if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
9141     MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
9142 
9143   // Erase the pseudoinstruction.
9144   MI.eraseFromParent();
9145   return BB;
9146 }
9147 
9148 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
9149                                            MachineBasicBlock *BB,
9150                                            const RISCVSubtarget &Subtarget) {
9151   // To "insert" Select_* instructions, we actually have to insert the triangle
9152   // control-flow pattern.  The incoming instructions know the destination vreg
9153   // to set, the condition code register to branch on, the true/false values to
9154   // select between, and the condcode to use to select the appropriate branch.
9155   //
9156   // We produce the following control flow:
9157   //     HeadMBB
9158   //     |  \
9159   //     |  IfFalseMBB
9160   //     | /
9161   //    TailMBB
9162   //
9163   // When we find a sequence of selects we attempt to optimize their emission
9164   // by sharing the control flow. Currently we only handle cases where we have
9165   // multiple selects with the exact same condition (same LHS, RHS and CC).
9166   // The selects may be interleaved with other instructions if the other
9167   // instructions meet some requirements we deem safe:
9168   // - They are debug instructions. Otherwise,
9169   // - They do not have side-effects, do not access memory and their inputs do
9170   //   not depend on the results of the select pseudo-instructions.
9171   // The TrueV/FalseV operands of the selects cannot depend on the result of
9172   // previous selects in the sequence.
9173   // These conditions could be further relaxed. See the X86 target for a
9174   // related approach and more information.
9175   Register LHS = MI.getOperand(1).getReg();
9176   Register RHS = MI.getOperand(2).getReg();
9177   auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
9178 
9179   SmallVector<MachineInstr *, 4> SelectDebugValues;
9180   SmallSet<Register, 4> SelectDests;
9181   SelectDests.insert(MI.getOperand(0).getReg());
9182 
9183   MachineInstr *LastSelectPseudo = &MI;
9184 
9185   for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
9186        SequenceMBBI != E; ++SequenceMBBI) {
9187     if (SequenceMBBI->isDebugInstr())
9188       continue;
9189     else if (isSelectPseudo(*SequenceMBBI)) {
9190       if (SequenceMBBI->getOperand(1).getReg() != LHS ||
9191           SequenceMBBI->getOperand(2).getReg() != RHS ||
9192           SequenceMBBI->getOperand(3).getImm() != CC ||
9193           SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
9194           SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
9195         break;
9196       LastSelectPseudo = &*SequenceMBBI;
9197       SequenceMBBI->collectDebugValues(SelectDebugValues);
9198       SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
9199     } else {
9200       if (SequenceMBBI->hasUnmodeledSideEffects() ||
9201           SequenceMBBI->mayLoadOrStore())
9202         break;
9203       if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
9204             return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
9205           }))
9206         break;
9207     }
9208   }
9209 
9210   const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
9211   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9212   DebugLoc DL = MI.getDebugLoc();
9213   MachineFunction::iterator I = ++BB->getIterator();
9214 
9215   MachineBasicBlock *HeadMBB = BB;
9216   MachineFunction *F = BB->getParent();
9217   MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
9218   MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
9219 
9220   F->insert(I, IfFalseMBB);
9221   F->insert(I, TailMBB);
9222 
9223   // Transfer debug instructions associated with the selects to TailMBB.
9224   for (MachineInstr *DebugInstr : SelectDebugValues) {
9225     TailMBB->push_back(DebugInstr->removeFromParent());
9226   }
9227 
9228   // Move all instructions after the sequence to TailMBB.
9229   TailMBB->splice(TailMBB->end(), HeadMBB,
9230                   std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
9231   // Update machine-CFG edges by transferring all successors of the current
9232   // block to the new block which will contain the Phi nodes for the selects.
9233   TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
9234   // Set the successors for HeadMBB.
9235   HeadMBB->addSuccessor(IfFalseMBB);
9236   HeadMBB->addSuccessor(TailMBB);
9237 
9238   // Insert appropriate branch.
9239   BuildMI(HeadMBB, DL, TII.getBrCond(CC))
9240     .addReg(LHS)
9241     .addReg(RHS)
9242     .addMBB(TailMBB);
9243 
9244   // IfFalseMBB just falls through to TailMBB.
9245   IfFalseMBB->addSuccessor(TailMBB);
9246 
9247   // Create PHIs for all of the select pseudo-instructions.
9248   auto SelectMBBI = MI.getIterator();
9249   auto SelectEnd = std::next(LastSelectPseudo->getIterator());
9250   auto InsertionPoint = TailMBB->begin();
9251   while (SelectMBBI != SelectEnd) {
9252     auto Next = std::next(SelectMBBI);
9253     if (isSelectPseudo(*SelectMBBI)) {
9254       // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
9255       BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
9256               TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
9257           .addReg(SelectMBBI->getOperand(4).getReg())
9258           .addMBB(HeadMBB)
9259           .addReg(SelectMBBI->getOperand(5).getReg())
9260           .addMBB(IfFalseMBB);
9261       SelectMBBI->eraseFromParent();
9262     }
9263     SelectMBBI = Next;
9264   }
9265 
9266   F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
9267   return TailMBB;
9268 }
9269 
9270 MachineBasicBlock *
9271 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9272                                                  MachineBasicBlock *BB) const {
9273   switch (MI.getOpcode()) {
9274   default:
9275     llvm_unreachable("Unexpected instr type to insert");
9276   case RISCV::ReadCycleWide:
9277     assert(!Subtarget.is64Bit() &&
9278            "ReadCycleWrite is only to be used on riscv32");
9279     return emitReadCycleWidePseudo(MI, BB);
9280   case RISCV::Select_GPR_Using_CC_GPR:
9281   case RISCV::Select_FPR16_Using_CC_GPR:
9282   case RISCV::Select_FPR32_Using_CC_GPR:
9283   case RISCV::Select_FPR64_Using_CC_GPR:
9284     return emitSelectPseudo(MI, BB, Subtarget);
9285   case RISCV::BuildPairF64Pseudo:
9286     return emitBuildPairF64Pseudo(MI, BB);
9287   case RISCV::SplitF64Pseudo:
9288     return emitSplitF64Pseudo(MI, BB);
9289   case RISCV::PseudoQuietFLE_H:
9290     return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
9291   case RISCV::PseudoQuietFLT_H:
9292     return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
9293   case RISCV::PseudoQuietFLE_S:
9294     return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
9295   case RISCV::PseudoQuietFLT_S:
9296     return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
9297   case RISCV::PseudoQuietFLE_D:
9298     return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
9299   case RISCV::PseudoQuietFLT_D:
9300     return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
9301   }
9302 }
9303 
9304 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9305                                                         SDNode *Node) const {
9306   // Add FRM dependency to any instructions with dynamic rounding mode.
9307   unsigned Opc = MI.getOpcode();
9308   auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
9309   if (Idx < 0)
9310     return;
9311   if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
9312     return;
9313   // If the instruction already reads FRM, don't add another read.
9314   if (MI.readsRegister(RISCV::FRM))
9315     return;
9316   MI.addOperand(
9317       MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
9318 }
9319 
9320 // Calling Convention Implementation.
9321 // The expectations for frontend ABI lowering vary from target to target.
9322 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
9323 // details, but this is a longer term goal. For now, we simply try to keep the
9324 // role of the frontend as simple and well-defined as possible. The rules can
9325 // be summarised as:
9326 // * Never split up large scalar arguments. We handle them here.
9327 // * If a hardfloat calling convention is being used, and the struct may be
9328 // passed in a pair of registers (fp+fp, int+fp), and both registers are
9329 // available, then pass as two separate arguments. If either the GPRs or FPRs
9330 // are exhausted, then pass according to the rule below.
9331 // * If a struct could never be passed in registers or directly in a stack
9332 // slot (as it is larger than 2*XLEN and the floating point rules don't
9333 // apply), then pass it using a pointer with the byval attribute.
9334 // * If a struct is less than 2*XLEN, then coerce to either a two-element
9335 // word-sized array or a 2*XLEN scalar (depending on alignment).
9336 // * The frontend can determine whether a struct is returned by reference or
9337 // not based on its size and fields. If it will be returned by reference, the
9338 // frontend must modify the prototype so a pointer with the sret annotation is
9339 // passed as the first argument. This is not necessary for large scalar
9340 // returns.
9341 // * Struct return values and varargs should be coerced to structs containing
9342 // register-size fields in the same situations they would be for fixed
9343 // arguments.
9344 
9345 static const MCPhysReg ArgGPRs[] = {
9346   RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
9347   RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
9348 };
9349 static const MCPhysReg ArgFPR16s[] = {
9350   RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
9351   RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
9352 };
9353 static const MCPhysReg ArgFPR32s[] = {
9354   RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
9355   RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
9356 };
9357 static const MCPhysReg ArgFPR64s[] = {
9358   RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
9359   RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
9360 };
9361 // This is an interim calling convention and it may be changed in the future.
9362 static const MCPhysReg ArgVRs[] = {
9363     RISCV::V8,  RISCV::V9,  RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
9364     RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
9365     RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
9366 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2,  RISCV::V10M2, RISCV::V12M2,
9367                                      RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
9368                                      RISCV::V20M2, RISCV::V22M2};
9369 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
9370                                      RISCV::V20M4};
9371 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
9372 
9373 // Pass a 2*XLEN argument that has been split into two XLEN values through
9374 // registers or the stack as necessary.
9375 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
9376                                 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
9377                                 MVT ValVT2, MVT LocVT2,
9378                                 ISD::ArgFlagsTy ArgFlags2) {
9379   unsigned XLenInBytes = XLen / 8;
9380   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9381     // At least one half can be passed via register.
9382     State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
9383                                      VA1.getLocVT(), CCValAssign::Full));
9384   } else {
9385     // Both halves must be passed on the stack, with proper alignment.
9386     Align StackAlign =
9387         std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
9388     State.addLoc(
9389         CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
9390                             State.AllocateStack(XLenInBytes, StackAlign),
9391                             VA1.getLocVT(), CCValAssign::Full));
9392     State.addLoc(CCValAssign::getMem(
9393         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9394         LocVT2, CCValAssign::Full));
9395     return false;
9396   }
9397 
9398   if (Register Reg = State.AllocateReg(ArgGPRs)) {
9399     // The second half can also be passed via register.
9400     State.addLoc(
9401         CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
9402   } else {
9403     // The second half is passed via the stack, without additional alignment.
9404     State.addLoc(CCValAssign::getMem(
9405         ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
9406         LocVT2, CCValAssign::Full));
9407   }
9408 
9409   return false;
9410 }
9411 
9412 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
9413                                Optional<unsigned> FirstMaskArgument,
9414                                CCState &State, const RISCVTargetLowering &TLI) {
9415   const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
9416   if (RC == &RISCV::VRRegClass) {
9417     // Assign the first mask argument to V0.
9418     // This is an interim calling convention and it may be changed in the
9419     // future.
9420     if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue())
9421       return State.AllocateReg(RISCV::V0);
9422     return State.AllocateReg(ArgVRs);
9423   }
9424   if (RC == &RISCV::VRM2RegClass)
9425     return State.AllocateReg(ArgVRM2s);
9426   if (RC == &RISCV::VRM4RegClass)
9427     return State.AllocateReg(ArgVRM4s);
9428   if (RC == &RISCV::VRM8RegClass)
9429     return State.AllocateReg(ArgVRM8s);
9430   llvm_unreachable("Unhandled register class for ValueType");
9431 }
9432 
9433 // Implements the RISC-V calling convention. Returns true upon failure.
9434 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
9435                      MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
9436                      ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
9437                      bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
9438                      Optional<unsigned> FirstMaskArgument) {
9439   unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
9440   assert(XLen == 32 || XLen == 64);
9441   MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
9442 
9443   // Any return value split in to more than two values can't be returned
9444   // directly. Vectors are returned via the available vector registers.
9445   if (!LocVT.isVector() && IsRet && ValNo > 1)
9446     return true;
9447 
9448   // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
9449   // variadic argument, or if no F16/F32 argument registers are available.
9450   bool UseGPRForF16_F32 = true;
9451   // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
9452   // variadic argument, or if no F64 argument registers are available.
9453   bool UseGPRForF64 = true;
9454 
9455   switch (ABI) {
9456   default:
9457     llvm_unreachable("Unexpected ABI");
9458   case RISCVABI::ABI_ILP32:
9459   case RISCVABI::ABI_LP64:
9460     break;
9461   case RISCVABI::ABI_ILP32F:
9462   case RISCVABI::ABI_LP64F:
9463     UseGPRForF16_F32 = !IsFixed;
9464     break;
9465   case RISCVABI::ABI_ILP32D:
9466   case RISCVABI::ABI_LP64D:
9467     UseGPRForF16_F32 = !IsFixed;
9468     UseGPRForF64 = !IsFixed;
9469     break;
9470   }
9471 
9472   // FPR16, FPR32, and FPR64 alias each other.
9473   if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) {
9474     UseGPRForF16_F32 = true;
9475     UseGPRForF64 = true;
9476   }
9477 
9478   // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
9479   // similar local variables rather than directly checking against the target
9480   // ABI.
9481 
9482   if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
9483     LocVT = XLenVT;
9484     LocInfo = CCValAssign::BCvt;
9485   } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
9486     LocVT = MVT::i64;
9487     LocInfo = CCValAssign::BCvt;
9488   }
9489 
9490   // If this is a variadic argument, the RISC-V calling convention requires
9491   // that it is assigned an 'even' or 'aligned' register if it has 8-byte
9492   // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
9493   // be used regardless of whether the original argument was split during
9494   // legalisation or not. The argument will not be passed by registers if the
9495   // original type is larger than 2*XLEN, so the register alignment rule does
9496   // not apply.
9497   unsigned TwoXLenInBytes = (2 * XLen) / 8;
9498   if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
9499       DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
9500     unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
9501     // Skip 'odd' register if necessary.
9502     if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1)
9503       State.AllocateReg(ArgGPRs);
9504   }
9505 
9506   SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
9507   SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
9508       State.getPendingArgFlags();
9509 
9510   assert(PendingLocs.size() == PendingArgFlags.size() &&
9511          "PendingLocs and PendingArgFlags out of sync");
9512 
9513   // Handle passing f64 on RV32D with a soft float ABI or when floating point
9514   // registers are exhausted.
9515   if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
9516     assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
9517            "Can't lower f64 if it is split");
9518     // Depending on available argument GPRS, f64 may be passed in a pair of
9519     // GPRs, split between a GPR and the stack, or passed completely on the
9520     // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
9521     // cases.
9522     Register Reg = State.AllocateReg(ArgGPRs);
9523     LocVT = MVT::i32;
9524     if (!Reg) {
9525       unsigned StackOffset = State.AllocateStack(8, Align(8));
9526       State.addLoc(
9527           CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9528       return false;
9529     }
9530     if (!State.AllocateReg(ArgGPRs))
9531       State.AllocateStack(4, Align(4));
9532     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9533     return false;
9534   }
9535 
9536   // Fixed-length vectors are located in the corresponding scalable-vector
9537   // container types.
9538   if (ValVT.isFixedLengthVector())
9539     LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9540 
9541   // Split arguments might be passed indirectly, so keep track of the pending
9542   // values. Split vectors are passed via a mix of registers and indirectly, so
9543   // treat them as we would any other argument.
9544   if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
9545     LocVT = XLenVT;
9546     LocInfo = CCValAssign::Indirect;
9547     PendingLocs.push_back(
9548         CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
9549     PendingArgFlags.push_back(ArgFlags);
9550     if (!ArgFlags.isSplitEnd()) {
9551       return false;
9552     }
9553   }
9554 
9555   // If the split argument only had two elements, it should be passed directly
9556   // in registers or on the stack.
9557   if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
9558       PendingLocs.size() <= 2) {
9559     assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
9560     // Apply the normal calling convention rules to the first half of the
9561     // split argument.
9562     CCValAssign VA = PendingLocs[0];
9563     ISD::ArgFlagsTy AF = PendingArgFlags[0];
9564     PendingLocs.clear();
9565     PendingArgFlags.clear();
9566     return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
9567                                ArgFlags);
9568   }
9569 
9570   // Allocate to a register if possible, or else a stack slot.
9571   Register Reg;
9572   unsigned StoreSizeBytes = XLen / 8;
9573   Align StackAlign = Align(XLen / 8);
9574 
9575   if (ValVT == MVT::f16 && !UseGPRForF16_F32)
9576     Reg = State.AllocateReg(ArgFPR16s);
9577   else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
9578     Reg = State.AllocateReg(ArgFPR32s);
9579   else if (ValVT == MVT::f64 && !UseGPRForF64)
9580     Reg = State.AllocateReg(ArgFPR64s);
9581   else if (ValVT.isVector()) {
9582     Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
9583     if (!Reg) {
9584       // For return values, the vector must be passed fully via registers or
9585       // via the stack.
9586       // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
9587       // but we're using all of them.
9588       if (IsRet)
9589         return true;
9590       // Try using a GPR to pass the address
9591       if ((Reg = State.AllocateReg(ArgGPRs))) {
9592         LocVT = XLenVT;
9593         LocInfo = CCValAssign::Indirect;
9594       } else if (ValVT.isScalableVector()) {
9595         LocVT = XLenVT;
9596         LocInfo = CCValAssign::Indirect;
9597       } else {
9598         // Pass fixed-length vectors on the stack.
9599         LocVT = ValVT;
9600         StoreSizeBytes = ValVT.getStoreSize();
9601         // Align vectors to their element sizes, being careful for vXi1
9602         // vectors.
9603         StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9604       }
9605     }
9606   } else {
9607     Reg = State.AllocateReg(ArgGPRs);
9608   }
9609 
9610   unsigned StackOffset =
9611       Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
9612 
9613   // If we reach this point and PendingLocs is non-empty, we must be at the
9614   // end of a split argument that must be passed indirectly.
9615   if (!PendingLocs.empty()) {
9616     assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
9617     assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
9618 
9619     for (auto &It : PendingLocs) {
9620       if (Reg)
9621         It.convertToReg(Reg);
9622       else
9623         It.convertToMem(StackOffset);
9624       State.addLoc(It);
9625     }
9626     PendingLocs.clear();
9627     PendingArgFlags.clear();
9628     return false;
9629   }
9630 
9631   assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
9632           (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
9633          "Expected an XLenVT or vector types at this stage");
9634 
9635   if (Reg) {
9636     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9637     return false;
9638   }
9639 
9640   // When a floating-point value is passed on the stack, no bit-conversion is
9641   // needed.
9642   if (ValVT.isFloatingPoint()) {
9643     LocVT = ValVT;
9644     LocInfo = CCValAssign::Full;
9645   }
9646   State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9647   return false;
9648 }
9649 
9650 template <typename ArgTy>
9651 static Optional<unsigned> preAssignMask(const ArgTy &Args) {
9652   for (const auto &ArgIdx : enumerate(Args)) {
9653     MVT ArgVT = ArgIdx.value().VT;
9654     if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
9655       return ArgIdx.index();
9656   }
9657   return None;
9658 }
9659 
9660 void RISCVTargetLowering::analyzeInputArgs(
9661     MachineFunction &MF, CCState &CCInfo,
9662     const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
9663     RISCVCCAssignFn Fn) const {
9664   unsigned NumArgs = Ins.size();
9665   FunctionType *FType = MF.getFunction().getFunctionType();
9666 
9667   Optional<unsigned> FirstMaskArgument;
9668   if (Subtarget.hasVInstructions())
9669     FirstMaskArgument = preAssignMask(Ins);
9670 
9671   for (unsigned i = 0; i != NumArgs; ++i) {
9672     MVT ArgVT = Ins[i].VT;
9673     ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
9674 
9675     Type *ArgTy = nullptr;
9676     if (IsRet)
9677       ArgTy = FType->getReturnType();
9678     else if (Ins[i].isOrigArg())
9679       ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
9680 
9681     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9682     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9683            ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
9684            FirstMaskArgument)) {
9685       LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
9686                         << EVT(ArgVT).getEVTString() << '\n');
9687       llvm_unreachable(nullptr);
9688     }
9689   }
9690 }
9691 
9692 void RISCVTargetLowering::analyzeOutputArgs(
9693     MachineFunction &MF, CCState &CCInfo,
9694     const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
9695     CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
9696   unsigned NumArgs = Outs.size();
9697 
9698   Optional<unsigned> FirstMaskArgument;
9699   if (Subtarget.hasVInstructions())
9700     FirstMaskArgument = preAssignMask(Outs);
9701 
9702   for (unsigned i = 0; i != NumArgs; i++) {
9703     MVT ArgVT = Outs[i].VT;
9704     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
9705     Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
9706 
9707     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
9708     if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
9709            ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
9710            FirstMaskArgument)) {
9711       LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
9712                         << EVT(ArgVT).getEVTString() << "\n");
9713       llvm_unreachable(nullptr);
9714     }
9715   }
9716 }
9717 
9718 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
9719 // values.
9720 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
9721                                    const CCValAssign &VA, const SDLoc &DL,
9722                                    const RISCVSubtarget &Subtarget) {
9723   switch (VA.getLocInfo()) {
9724   default:
9725     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9726   case CCValAssign::Full:
9727     if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
9728       Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
9729     break;
9730   case CCValAssign::BCvt:
9731     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9732       Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
9733     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9734       Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
9735     else
9736       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
9737     break;
9738   }
9739   return Val;
9740 }
9741 
9742 // The caller is responsible for loading the full value if the argument is
9743 // passed with CCValAssign::Indirect.
9744 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
9745                                 const CCValAssign &VA, const SDLoc &DL,
9746                                 const RISCVTargetLowering &TLI) {
9747   MachineFunction &MF = DAG.getMachineFunction();
9748   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9749   EVT LocVT = VA.getLocVT();
9750   SDValue Val;
9751   const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
9752   Register VReg = RegInfo.createVirtualRegister(RC);
9753   RegInfo.addLiveIn(VA.getLocReg(), VReg);
9754   Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
9755 
9756   if (VA.getLocInfo() == CCValAssign::Indirect)
9757     return Val;
9758 
9759   return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
9760 }
9761 
9762 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
9763                                    const CCValAssign &VA, const SDLoc &DL,
9764                                    const RISCVSubtarget &Subtarget) {
9765   EVT LocVT = VA.getLocVT();
9766 
9767   switch (VA.getLocInfo()) {
9768   default:
9769     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9770   case CCValAssign::Full:
9771     if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
9772       Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
9773     break;
9774   case CCValAssign::BCvt:
9775     if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
9776       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
9777     else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
9778       Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
9779     else
9780       Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
9781     break;
9782   }
9783   return Val;
9784 }
9785 
9786 // The caller is responsible for loading the full value if the argument is
9787 // passed with CCValAssign::Indirect.
9788 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
9789                                 const CCValAssign &VA, const SDLoc &DL) {
9790   MachineFunction &MF = DAG.getMachineFunction();
9791   MachineFrameInfo &MFI = MF.getFrameInfo();
9792   EVT LocVT = VA.getLocVT();
9793   EVT ValVT = VA.getValVT();
9794   EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
9795   if (ValVT.isScalableVector()) {
9796     // When the value is a scalable vector, we save the pointer which points to
9797     // the scalable vector value in the stack. The ValVT will be the pointer
9798     // type, instead of the scalable vector type.
9799     ValVT = LocVT;
9800   }
9801   int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
9802                                  /*IsImmutable=*/true);
9803   SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
9804   SDValue Val;
9805 
9806   ISD::LoadExtType ExtType;
9807   switch (VA.getLocInfo()) {
9808   default:
9809     llvm_unreachable("Unexpected CCValAssign::LocInfo");
9810   case CCValAssign::Full:
9811   case CCValAssign::Indirect:
9812   case CCValAssign::BCvt:
9813     ExtType = ISD::NON_EXTLOAD;
9814     break;
9815   }
9816   Val = DAG.getExtLoad(
9817       ExtType, DL, LocVT, Chain, FIN,
9818       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
9819   return Val;
9820 }
9821 
9822 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
9823                                        const CCValAssign &VA, const SDLoc &DL) {
9824   assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
9825          "Unexpected VA");
9826   MachineFunction &MF = DAG.getMachineFunction();
9827   MachineFrameInfo &MFI = MF.getFrameInfo();
9828   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9829 
9830   if (VA.isMemLoc()) {
9831     // f64 is passed on the stack.
9832     int FI =
9833         MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
9834     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9835     return DAG.getLoad(MVT::f64, DL, Chain, FIN,
9836                        MachinePointerInfo::getFixedStack(MF, FI));
9837   }
9838 
9839   assert(VA.isRegLoc() && "Expected register VA assignment");
9840 
9841   Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9842   RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
9843   SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
9844   SDValue Hi;
9845   if (VA.getLocReg() == RISCV::X17) {
9846     // Second half of f64 is passed on the stack.
9847     int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
9848     SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
9849     Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
9850                      MachinePointerInfo::getFixedStack(MF, FI));
9851   } else {
9852     // Second half of f64 is passed in another GPR.
9853     Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
9854     RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
9855     Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
9856   }
9857   return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
9858 }
9859 
9860 // FastCC has less than 1% performance improvement for some particular
9861 // benchmark. But theoretically, it may has benenfit for some cases.
9862 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
9863                             unsigned ValNo, MVT ValVT, MVT LocVT,
9864                             CCValAssign::LocInfo LocInfo,
9865                             ISD::ArgFlagsTy ArgFlags, CCState &State,
9866                             bool IsFixed, bool IsRet, Type *OrigTy,
9867                             const RISCVTargetLowering &TLI,
9868                             Optional<unsigned> FirstMaskArgument) {
9869 
9870   // X5 and X6 might be used for save-restore libcall.
9871   static const MCPhysReg GPRList[] = {
9872       RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
9873       RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7,  RISCV::X28,
9874       RISCV::X29, RISCV::X30, RISCV::X31};
9875 
9876   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9877     if (unsigned Reg = State.AllocateReg(GPRList)) {
9878       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9879       return false;
9880     }
9881   }
9882 
9883   if (LocVT == MVT::f16) {
9884     static const MCPhysReg FPR16List[] = {
9885         RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
9886         RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H,  RISCV::F1_H,
9887         RISCV::F2_H,  RISCV::F3_H,  RISCV::F4_H,  RISCV::F5_H,  RISCV::F6_H,
9888         RISCV::F7_H,  RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
9889     if (unsigned Reg = State.AllocateReg(FPR16List)) {
9890       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9891       return false;
9892     }
9893   }
9894 
9895   if (LocVT == MVT::f32) {
9896     static const MCPhysReg FPR32List[] = {
9897         RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
9898         RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F,  RISCV::F1_F,
9899         RISCV::F2_F,  RISCV::F3_F,  RISCV::F4_F,  RISCV::F5_F,  RISCV::F6_F,
9900         RISCV::F7_F,  RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
9901     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9902       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9903       return false;
9904     }
9905   }
9906 
9907   if (LocVT == MVT::f64) {
9908     static const MCPhysReg FPR64List[] = {
9909         RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
9910         RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D,  RISCV::F1_D,
9911         RISCV::F2_D,  RISCV::F3_D,  RISCV::F4_D,  RISCV::F5_D,  RISCV::F6_D,
9912         RISCV::F7_D,  RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
9913     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9914       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9915       return false;
9916     }
9917   }
9918 
9919   if (LocVT == MVT::i32 || LocVT == MVT::f32) {
9920     unsigned Offset4 = State.AllocateStack(4, Align(4));
9921     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
9922     return false;
9923   }
9924 
9925   if (LocVT == MVT::i64 || LocVT == MVT::f64) {
9926     unsigned Offset5 = State.AllocateStack(8, Align(8));
9927     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
9928     return false;
9929   }
9930 
9931   if (LocVT.isVector()) {
9932     if (unsigned Reg =
9933             allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
9934       // Fixed-length vectors are located in the corresponding scalable-vector
9935       // container types.
9936       if (ValVT.isFixedLengthVector())
9937         LocVT = TLI.getContainerForFixedLengthVector(LocVT);
9938       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9939     } else {
9940       // Try and pass the address via a "fast" GPR.
9941       if (unsigned GPRReg = State.AllocateReg(GPRList)) {
9942         LocInfo = CCValAssign::Indirect;
9943         LocVT = TLI.getSubtarget().getXLenVT();
9944         State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
9945       } else if (ValVT.isFixedLengthVector()) {
9946         auto StackAlign =
9947             MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
9948         unsigned StackOffset =
9949             State.AllocateStack(ValVT.getStoreSize(), StackAlign);
9950         State.addLoc(
9951             CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
9952       } else {
9953         // Can't pass scalable vectors on the stack.
9954         return true;
9955       }
9956     }
9957 
9958     return false;
9959   }
9960 
9961   return true; // CC didn't match.
9962 }
9963 
9964 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
9965                          CCValAssign::LocInfo LocInfo,
9966                          ISD::ArgFlagsTy ArgFlags, CCState &State) {
9967 
9968   if (LocVT == MVT::i32 || LocVT == MVT::i64) {
9969     // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
9970     //                        s1    s2  s3  s4  s5  s6  s7  s8  s9  s10 s11
9971     static const MCPhysReg GPRList[] = {
9972         RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
9973         RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
9974     if (unsigned Reg = State.AllocateReg(GPRList)) {
9975       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9976       return false;
9977     }
9978   }
9979 
9980   if (LocVT == MVT::f32) {
9981     // Pass in STG registers: F1, ..., F6
9982     //                        fs0 ... fs5
9983     static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
9984                                           RISCV::F18_F, RISCV::F19_F,
9985                                           RISCV::F20_F, RISCV::F21_F};
9986     if (unsigned Reg = State.AllocateReg(FPR32List)) {
9987       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
9988       return false;
9989     }
9990   }
9991 
9992   if (LocVT == MVT::f64) {
9993     // Pass in STG registers: D1, ..., D6
9994     //                        fs6 ... fs11
9995     static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
9996                                           RISCV::F24_D, RISCV::F25_D,
9997                                           RISCV::F26_D, RISCV::F27_D};
9998     if (unsigned Reg = State.AllocateReg(FPR64List)) {
9999       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
10000       return false;
10001     }
10002   }
10003 
10004   report_fatal_error("No registers left in GHC calling convention");
10005   return true;
10006 }
10007 
10008 // Transform physical registers into virtual registers.
10009 SDValue RISCVTargetLowering::LowerFormalArguments(
10010     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
10011     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
10012     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
10013 
10014   MachineFunction &MF = DAG.getMachineFunction();
10015 
10016   switch (CallConv) {
10017   default:
10018     report_fatal_error("Unsupported calling convention");
10019   case CallingConv::C:
10020   case CallingConv::Fast:
10021     break;
10022   case CallingConv::GHC:
10023     if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
10024         !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
10025       report_fatal_error(
10026         "GHC calling convention requires the F and D instruction set extensions");
10027   }
10028 
10029   const Function &Func = MF.getFunction();
10030   if (Func.hasFnAttribute("interrupt")) {
10031     if (!Func.arg_empty())
10032       report_fatal_error(
10033         "Functions with the interrupt attribute cannot have arguments!");
10034 
10035     StringRef Kind =
10036       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10037 
10038     if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
10039       report_fatal_error(
10040         "Function interrupt attribute argument not supported!");
10041   }
10042 
10043   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10044   MVT XLenVT = Subtarget.getXLenVT();
10045   unsigned XLenInBytes = Subtarget.getXLen() / 8;
10046   // Used with vargs to acumulate store chains.
10047   std::vector<SDValue> OutChains;
10048 
10049   // Assign locations to all of the incoming arguments.
10050   SmallVector<CCValAssign, 16> ArgLocs;
10051   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10052 
10053   if (CallConv == CallingConv::GHC)
10054     CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
10055   else
10056     analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
10057                      CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10058                                                    : CC_RISCV);
10059 
10060   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
10061     CCValAssign &VA = ArgLocs[i];
10062     SDValue ArgValue;
10063     // Passing f64 on RV32D with a soft float ABI must be handled as a special
10064     // case.
10065     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
10066       ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
10067     else if (VA.isRegLoc())
10068       ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this);
10069     else
10070       ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
10071 
10072     if (VA.getLocInfo() == CCValAssign::Indirect) {
10073       // If the original argument was split and passed by reference (e.g. i128
10074       // on RV32), we need to load all parts of it here (using the same
10075       // address). Vectors may be partly split to registers and partly to the
10076       // stack, in which case the base address is partly offset and subsequent
10077       // stores are relative to that.
10078       InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
10079                                    MachinePointerInfo()));
10080       unsigned ArgIndex = Ins[i].OrigArgIndex;
10081       unsigned ArgPartOffset = Ins[i].PartOffset;
10082       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10083       while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
10084         CCValAssign &PartVA = ArgLocs[i + 1];
10085         unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
10086         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10087         if (PartVA.getValVT().isScalableVector())
10088           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10089         SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
10090         InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
10091                                      MachinePointerInfo()));
10092         ++i;
10093       }
10094       continue;
10095     }
10096     InVals.push_back(ArgValue);
10097   }
10098 
10099   if (IsVarArg) {
10100     ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs);
10101     unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
10102     const TargetRegisterClass *RC = &RISCV::GPRRegClass;
10103     MachineFrameInfo &MFI = MF.getFrameInfo();
10104     MachineRegisterInfo &RegInfo = MF.getRegInfo();
10105     RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
10106 
10107     // Offset of the first variable argument from stack pointer, and size of
10108     // the vararg save area. For now, the varargs save area is either zero or
10109     // large enough to hold a0-a7.
10110     int VaArgOffset, VarArgsSaveSize;
10111 
10112     // If all registers are allocated, then all varargs must be passed on the
10113     // stack and we don't need to save any argregs.
10114     if (ArgRegs.size() == Idx) {
10115       VaArgOffset = CCInfo.getNextStackOffset();
10116       VarArgsSaveSize = 0;
10117     } else {
10118       VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
10119       VaArgOffset = -VarArgsSaveSize;
10120     }
10121 
10122     // Record the frame index of the first variable argument
10123     // which is a value necessary to VASTART.
10124     int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10125     RVFI->setVarArgsFrameIndex(FI);
10126 
10127     // If saving an odd number of registers then create an extra stack slot to
10128     // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
10129     // offsets to even-numbered registered remain 2*XLEN-aligned.
10130     if (Idx % 2) {
10131       MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
10132       VarArgsSaveSize += XLenInBytes;
10133     }
10134 
10135     // Copy the integer registers that may have been used for passing varargs
10136     // to the vararg save area.
10137     for (unsigned I = Idx; I < ArgRegs.size();
10138          ++I, VaArgOffset += XLenInBytes) {
10139       const Register Reg = RegInfo.createVirtualRegister(RC);
10140       RegInfo.addLiveIn(ArgRegs[I], Reg);
10141       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
10142       FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
10143       SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10144       SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
10145                                    MachinePointerInfo::getFixedStack(MF, FI));
10146       cast<StoreSDNode>(Store.getNode())
10147           ->getMemOperand()
10148           ->setValue((Value *)nullptr);
10149       OutChains.push_back(Store);
10150     }
10151     RVFI->setVarArgsSaveSize(VarArgsSaveSize);
10152   }
10153 
10154   // All stores are grouped in one node to allow the matching between
10155   // the size of Ins and InVals. This only happens for vararg functions.
10156   if (!OutChains.empty()) {
10157     OutChains.push_back(Chain);
10158     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
10159   }
10160 
10161   return Chain;
10162 }
10163 
10164 /// isEligibleForTailCallOptimization - Check whether the call is eligible
10165 /// for tail call optimization.
10166 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
10167 bool RISCVTargetLowering::isEligibleForTailCallOptimization(
10168     CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
10169     const SmallVector<CCValAssign, 16> &ArgLocs) const {
10170 
10171   auto &Callee = CLI.Callee;
10172   auto CalleeCC = CLI.CallConv;
10173   auto &Outs = CLI.Outs;
10174   auto &Caller = MF.getFunction();
10175   auto CallerCC = Caller.getCallingConv();
10176 
10177   // Exception-handling functions need a special set of instructions to
10178   // indicate a return to the hardware. Tail-calling another function would
10179   // probably break this.
10180   // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
10181   // should be expanded as new function attributes are introduced.
10182   if (Caller.hasFnAttribute("interrupt"))
10183     return false;
10184 
10185   // Do not tail call opt if the stack is used to pass parameters.
10186   if (CCInfo.getNextStackOffset() != 0)
10187     return false;
10188 
10189   // Do not tail call opt if any parameters need to be passed indirectly.
10190   // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
10191   // passed indirectly. So the address of the value will be passed in a
10192   // register, or if not available, then the address is put on the stack. In
10193   // order to pass indirectly, space on the stack often needs to be allocated
10194   // in order to store the value. In this case the CCInfo.getNextStackOffset()
10195   // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
10196   // are passed CCValAssign::Indirect.
10197   for (auto &VA : ArgLocs)
10198     if (VA.getLocInfo() == CCValAssign::Indirect)
10199       return false;
10200 
10201   // Do not tail call opt if either caller or callee uses struct return
10202   // semantics.
10203   auto IsCallerStructRet = Caller.hasStructRetAttr();
10204   auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
10205   if (IsCallerStructRet || IsCalleeStructRet)
10206     return false;
10207 
10208   // Externally-defined functions with weak linkage should not be
10209   // tail-called. The behaviour of branch instructions in this situation (as
10210   // used for tail calls) is implementation-defined, so we cannot rely on the
10211   // linker replacing the tail call with a return.
10212   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
10213     const GlobalValue *GV = G->getGlobal();
10214     if (GV->hasExternalWeakLinkage())
10215       return false;
10216   }
10217 
10218   // The callee has to preserve all registers the caller needs to preserve.
10219   const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
10220   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
10221   if (CalleeCC != CallerCC) {
10222     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
10223     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
10224       return false;
10225   }
10226 
10227   // Byval parameters hand the function a pointer directly into the stack area
10228   // we want to reuse during a tail call. Working around this *is* possible
10229   // but less efficient and uglier in LowerCall.
10230   for (auto &Arg : Outs)
10231     if (Arg.Flags.isByVal())
10232       return false;
10233 
10234   return true;
10235 }
10236 
10237 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
10238   return DAG.getDataLayout().getPrefTypeAlign(
10239       VT.getTypeForEVT(*DAG.getContext()));
10240 }
10241 
10242 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
10243 // and output parameter nodes.
10244 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
10245                                        SmallVectorImpl<SDValue> &InVals) const {
10246   SelectionDAG &DAG = CLI.DAG;
10247   SDLoc &DL = CLI.DL;
10248   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
10249   SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
10250   SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
10251   SDValue Chain = CLI.Chain;
10252   SDValue Callee = CLI.Callee;
10253   bool &IsTailCall = CLI.IsTailCall;
10254   CallingConv::ID CallConv = CLI.CallConv;
10255   bool IsVarArg = CLI.IsVarArg;
10256   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10257   MVT XLenVT = Subtarget.getXLenVT();
10258 
10259   MachineFunction &MF = DAG.getMachineFunction();
10260 
10261   // Analyze the operands of the call, assigning locations to each operand.
10262   SmallVector<CCValAssign, 16> ArgLocs;
10263   CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
10264 
10265   if (CallConv == CallingConv::GHC)
10266     ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
10267   else
10268     analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
10269                       CallConv == CallingConv::Fast ? CC_RISCV_FastCC
10270                                                     : CC_RISCV);
10271 
10272   // Check if it's really possible to do a tail call.
10273   if (IsTailCall)
10274     IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
10275 
10276   if (IsTailCall)
10277     ++NumTailCalls;
10278   else if (CLI.CB && CLI.CB->isMustTailCall())
10279     report_fatal_error("failed to perform tail call elimination on a call "
10280                        "site marked musttail");
10281 
10282   // Get a count of how many bytes are to be pushed on the stack.
10283   unsigned NumBytes = ArgCCInfo.getNextStackOffset();
10284 
10285   // Create local copies for byval args
10286   SmallVector<SDValue, 8> ByValArgs;
10287   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10288     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10289     if (!Flags.isByVal())
10290       continue;
10291 
10292     SDValue Arg = OutVals[i];
10293     unsigned Size = Flags.getByValSize();
10294     Align Alignment = Flags.getNonZeroByValAlign();
10295 
10296     int FI =
10297         MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
10298     SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
10299     SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
10300 
10301     Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
10302                           /*IsVolatile=*/false,
10303                           /*AlwaysInline=*/false, IsTailCall,
10304                           MachinePointerInfo(), MachinePointerInfo());
10305     ByValArgs.push_back(FIPtr);
10306   }
10307 
10308   if (!IsTailCall)
10309     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
10310 
10311   // Copy argument values to their designated locations.
10312   SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
10313   SmallVector<SDValue, 8> MemOpChains;
10314   SDValue StackPtr;
10315   for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
10316     CCValAssign &VA = ArgLocs[i];
10317     SDValue ArgValue = OutVals[i];
10318     ISD::ArgFlagsTy Flags = Outs[i].Flags;
10319 
10320     // Handle passing f64 on RV32D with a soft float ABI as a special case.
10321     bool IsF64OnRV32DSoftABI =
10322         VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
10323     if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
10324       SDValue SplitF64 = DAG.getNode(
10325           RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
10326       SDValue Lo = SplitF64.getValue(0);
10327       SDValue Hi = SplitF64.getValue(1);
10328 
10329       Register RegLo = VA.getLocReg();
10330       RegsToPass.push_back(std::make_pair(RegLo, Lo));
10331 
10332       if (RegLo == RISCV::X17) {
10333         // Second half of f64 is passed on the stack.
10334         // Work out the address of the stack slot.
10335         if (!StackPtr.getNode())
10336           StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10337         // Emit the store.
10338         MemOpChains.push_back(
10339             DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
10340       } else {
10341         // Second half of f64 is passed in another GPR.
10342         assert(RegLo < RISCV::X31 && "Invalid register pair");
10343         Register RegHigh = RegLo + 1;
10344         RegsToPass.push_back(std::make_pair(RegHigh, Hi));
10345       }
10346       continue;
10347     }
10348 
10349     // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
10350     // as any other MemLoc.
10351 
10352     // Promote the value if needed.
10353     // For now, only handle fully promoted and indirect arguments.
10354     if (VA.getLocInfo() == CCValAssign::Indirect) {
10355       // Store the argument in a stack slot and pass its address.
10356       Align StackAlign =
10357           std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
10358                    getPrefTypeAlign(ArgValue.getValueType(), DAG));
10359       TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
10360       // If the original argument was split (e.g. i128), we need
10361       // to store the required parts of it here (and pass just one address).
10362       // Vectors may be partly split to registers and partly to the stack, in
10363       // which case the base address is partly offset and subsequent stores are
10364       // relative to that.
10365       unsigned ArgIndex = Outs[i].OrigArgIndex;
10366       unsigned ArgPartOffset = Outs[i].PartOffset;
10367       assert(VA.getValVT().isVector() || ArgPartOffset == 0);
10368       // Calculate the total size to store. We don't have access to what we're
10369       // actually storing other than performing the loop and collecting the
10370       // info.
10371       SmallVector<std::pair<SDValue, SDValue>> Parts;
10372       while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
10373         SDValue PartValue = OutVals[i + 1];
10374         unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
10375         SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
10376         EVT PartVT = PartValue.getValueType();
10377         if (PartVT.isScalableVector())
10378           Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
10379         StoredSize += PartVT.getStoreSize();
10380         StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
10381         Parts.push_back(std::make_pair(PartValue, Offset));
10382         ++i;
10383       }
10384       SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
10385       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
10386       MemOpChains.push_back(
10387           DAG.getStore(Chain, DL, ArgValue, SpillSlot,
10388                        MachinePointerInfo::getFixedStack(MF, FI)));
10389       for (const auto &Part : Parts) {
10390         SDValue PartValue = Part.first;
10391         SDValue PartOffset = Part.second;
10392         SDValue Address =
10393             DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
10394         MemOpChains.push_back(
10395             DAG.getStore(Chain, DL, PartValue, Address,
10396                          MachinePointerInfo::getFixedStack(MF, FI)));
10397       }
10398       ArgValue = SpillSlot;
10399     } else {
10400       ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
10401     }
10402 
10403     // Use local copy if it is a byval arg.
10404     if (Flags.isByVal())
10405       ArgValue = ByValArgs[j++];
10406 
10407     if (VA.isRegLoc()) {
10408       // Queue up the argument copies and emit them at the end.
10409       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
10410     } else {
10411       assert(VA.isMemLoc() && "Argument not register or memory");
10412       assert(!IsTailCall && "Tail call not allowed if stack is used "
10413                             "for passing parameters");
10414 
10415       // Work out the address of the stack slot.
10416       if (!StackPtr.getNode())
10417         StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
10418       SDValue Address =
10419           DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
10420                       DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
10421 
10422       // Emit the store.
10423       MemOpChains.push_back(
10424           DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
10425     }
10426   }
10427 
10428   // Join the stores, which are independent of one another.
10429   if (!MemOpChains.empty())
10430     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
10431 
10432   SDValue Glue;
10433 
10434   // Build a sequence of copy-to-reg nodes, chained and glued together.
10435   for (auto &Reg : RegsToPass) {
10436     Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
10437     Glue = Chain.getValue(1);
10438   }
10439 
10440   // Validate that none of the argument registers have been marked as
10441   // reserved, if so report an error. Do the same for the return address if this
10442   // is not a tailcall.
10443   validateCCReservedRegs(RegsToPass, MF);
10444   if (!IsTailCall &&
10445       MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
10446     MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10447         MF.getFunction(),
10448         "Return address register required, but has been reserved."});
10449 
10450   // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
10451   // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
10452   // split it and then direct call can be matched by PseudoCALL.
10453   if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
10454     const GlobalValue *GV = S->getGlobal();
10455 
10456     unsigned OpFlags = RISCVII::MO_CALL;
10457     if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
10458       OpFlags = RISCVII::MO_PLT;
10459 
10460     Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
10461   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
10462     unsigned OpFlags = RISCVII::MO_CALL;
10463 
10464     if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
10465                                                  nullptr))
10466       OpFlags = RISCVII::MO_PLT;
10467 
10468     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
10469   }
10470 
10471   // The first call operand is the chain and the second is the target address.
10472   SmallVector<SDValue, 8> Ops;
10473   Ops.push_back(Chain);
10474   Ops.push_back(Callee);
10475 
10476   // Add argument registers to the end of the list so that they are
10477   // known live into the call.
10478   for (auto &Reg : RegsToPass)
10479     Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
10480 
10481   if (!IsTailCall) {
10482     // Add a register mask operand representing the call-preserved registers.
10483     const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
10484     const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
10485     assert(Mask && "Missing call preserved mask for calling convention");
10486     Ops.push_back(DAG.getRegisterMask(Mask));
10487   }
10488 
10489   // Glue the call to the argument copies, if any.
10490   if (Glue.getNode())
10491     Ops.push_back(Glue);
10492 
10493   // Emit the call.
10494   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10495 
10496   if (IsTailCall) {
10497     MF.getFrameInfo().setHasTailCall();
10498     return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
10499   }
10500 
10501   Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
10502   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
10503   Glue = Chain.getValue(1);
10504 
10505   // Mark the end of the call, which is glued to the call itself.
10506   Chain = DAG.getCALLSEQ_END(Chain,
10507                              DAG.getConstant(NumBytes, DL, PtrVT, true),
10508                              DAG.getConstant(0, DL, PtrVT, true),
10509                              Glue, DL);
10510   Glue = Chain.getValue(1);
10511 
10512   // Assign locations to each value returned by this call.
10513   SmallVector<CCValAssign, 16> RVLocs;
10514   CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
10515   analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
10516 
10517   // Copy all of the result registers out of their specified physreg.
10518   for (auto &VA : RVLocs) {
10519     // Copy the value out
10520     SDValue RetValue =
10521         DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
10522     // Glue the RetValue to the end of the call sequence
10523     Chain = RetValue.getValue(1);
10524     Glue = RetValue.getValue(2);
10525 
10526     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10527       assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
10528       SDValue RetValue2 =
10529           DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
10530       Chain = RetValue2.getValue(1);
10531       Glue = RetValue2.getValue(2);
10532       RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
10533                              RetValue2);
10534     }
10535 
10536     RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
10537 
10538     InVals.push_back(RetValue);
10539   }
10540 
10541   return Chain;
10542 }
10543 
10544 bool RISCVTargetLowering::CanLowerReturn(
10545     CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
10546     const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
10547   SmallVector<CCValAssign, 16> RVLocs;
10548   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
10549 
10550   Optional<unsigned> FirstMaskArgument;
10551   if (Subtarget.hasVInstructions())
10552     FirstMaskArgument = preAssignMask(Outs);
10553 
10554   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
10555     MVT VT = Outs[i].VT;
10556     ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
10557     RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
10558     if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
10559                  ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
10560                  *this, FirstMaskArgument))
10561       return false;
10562   }
10563   return true;
10564 }
10565 
10566 SDValue
10567 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
10568                                  bool IsVarArg,
10569                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
10570                                  const SmallVectorImpl<SDValue> &OutVals,
10571                                  const SDLoc &DL, SelectionDAG &DAG) const {
10572   const MachineFunction &MF = DAG.getMachineFunction();
10573   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10574 
10575   // Stores the assignment of the return value to a location.
10576   SmallVector<CCValAssign, 16> RVLocs;
10577 
10578   // Info about the registers and stack slot.
10579   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
10580                  *DAG.getContext());
10581 
10582   analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
10583                     nullptr, CC_RISCV);
10584 
10585   if (CallConv == CallingConv::GHC && !RVLocs.empty())
10586     report_fatal_error("GHC functions return void only");
10587 
10588   SDValue Glue;
10589   SmallVector<SDValue, 4> RetOps(1, Chain);
10590 
10591   // Copy the result values into the output registers.
10592   for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
10593     SDValue Val = OutVals[i];
10594     CCValAssign &VA = RVLocs[i];
10595     assert(VA.isRegLoc() && "Can only return in registers!");
10596 
10597     if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
10598       // Handle returning f64 on RV32D with a soft float ABI.
10599       assert(VA.isRegLoc() && "Expected return via registers");
10600       SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
10601                                      DAG.getVTList(MVT::i32, MVT::i32), Val);
10602       SDValue Lo = SplitF64.getValue(0);
10603       SDValue Hi = SplitF64.getValue(1);
10604       Register RegLo = VA.getLocReg();
10605       assert(RegLo < RISCV::X31 && "Invalid register pair");
10606       Register RegHi = RegLo + 1;
10607 
10608       if (STI.isRegisterReservedByUser(RegLo) ||
10609           STI.isRegisterReservedByUser(RegHi))
10610         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10611             MF.getFunction(),
10612             "Return value register required, but has been reserved."});
10613 
10614       Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
10615       Glue = Chain.getValue(1);
10616       RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
10617       Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
10618       Glue = Chain.getValue(1);
10619       RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
10620     } else {
10621       // Handle a 'normal' return.
10622       Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
10623       Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
10624 
10625       if (STI.isRegisterReservedByUser(VA.getLocReg()))
10626         MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
10627             MF.getFunction(),
10628             "Return value register required, but has been reserved."});
10629 
10630       // Guarantee that all emitted copies are stuck together.
10631       Glue = Chain.getValue(1);
10632       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
10633     }
10634   }
10635 
10636   RetOps[0] = Chain; // Update chain.
10637 
10638   // Add the glue node if we have it.
10639   if (Glue.getNode()) {
10640     RetOps.push_back(Glue);
10641   }
10642 
10643   unsigned RetOpc = RISCVISD::RET_FLAG;
10644   // Interrupt service routines use different return instructions.
10645   const Function &Func = DAG.getMachineFunction().getFunction();
10646   if (Func.hasFnAttribute("interrupt")) {
10647     if (!Func.getReturnType()->isVoidTy())
10648       report_fatal_error(
10649           "Functions with the interrupt attribute must have void return type!");
10650 
10651     MachineFunction &MF = DAG.getMachineFunction();
10652     StringRef Kind =
10653       MF.getFunction().getFnAttribute("interrupt").getValueAsString();
10654 
10655     if (Kind == "user")
10656       RetOpc = RISCVISD::URET_FLAG;
10657     else if (Kind == "supervisor")
10658       RetOpc = RISCVISD::SRET_FLAG;
10659     else
10660       RetOpc = RISCVISD::MRET_FLAG;
10661   }
10662 
10663   return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
10664 }
10665 
10666 void RISCVTargetLowering::validateCCReservedRegs(
10667     const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
10668     MachineFunction &MF) const {
10669   const Function &F = MF.getFunction();
10670   const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
10671 
10672   if (llvm::any_of(Regs, [&STI](auto Reg) {
10673         return STI.isRegisterReservedByUser(Reg.first);
10674       }))
10675     F.getContext().diagnose(DiagnosticInfoUnsupported{
10676         F, "Argument register required, but has been reserved."});
10677 }
10678 
10679 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10680   return CI->isTailCall();
10681 }
10682 
10683 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
10684 #define NODE_NAME_CASE(NODE)                                                   \
10685   case RISCVISD::NODE:                                                         \
10686     return "RISCVISD::" #NODE;
10687   // clang-format off
10688   switch ((RISCVISD::NodeType)Opcode) {
10689   case RISCVISD::FIRST_NUMBER:
10690     break;
10691   NODE_NAME_CASE(RET_FLAG)
10692   NODE_NAME_CASE(URET_FLAG)
10693   NODE_NAME_CASE(SRET_FLAG)
10694   NODE_NAME_CASE(MRET_FLAG)
10695   NODE_NAME_CASE(CALL)
10696   NODE_NAME_CASE(SELECT_CC)
10697   NODE_NAME_CASE(BR_CC)
10698   NODE_NAME_CASE(BuildPairF64)
10699   NODE_NAME_CASE(SplitF64)
10700   NODE_NAME_CASE(TAIL)
10701   NODE_NAME_CASE(MULHSU)
10702   NODE_NAME_CASE(SLLW)
10703   NODE_NAME_CASE(SRAW)
10704   NODE_NAME_CASE(SRLW)
10705   NODE_NAME_CASE(DIVW)
10706   NODE_NAME_CASE(DIVUW)
10707   NODE_NAME_CASE(REMUW)
10708   NODE_NAME_CASE(ROLW)
10709   NODE_NAME_CASE(RORW)
10710   NODE_NAME_CASE(CLZW)
10711   NODE_NAME_CASE(CTZW)
10712   NODE_NAME_CASE(FSLW)
10713   NODE_NAME_CASE(FSRW)
10714   NODE_NAME_CASE(FSL)
10715   NODE_NAME_CASE(FSR)
10716   NODE_NAME_CASE(FMV_H_X)
10717   NODE_NAME_CASE(FMV_X_ANYEXTH)
10718   NODE_NAME_CASE(FMV_X_SIGNEXTH)
10719   NODE_NAME_CASE(FMV_W_X_RV64)
10720   NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
10721   NODE_NAME_CASE(FCVT_X)
10722   NODE_NAME_CASE(FCVT_XU)
10723   NODE_NAME_CASE(FCVT_W_RV64)
10724   NODE_NAME_CASE(FCVT_WU_RV64)
10725   NODE_NAME_CASE(STRICT_FCVT_W_RV64)
10726   NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
10727   NODE_NAME_CASE(READ_CYCLE_WIDE)
10728   NODE_NAME_CASE(GREV)
10729   NODE_NAME_CASE(GREVW)
10730   NODE_NAME_CASE(GORC)
10731   NODE_NAME_CASE(GORCW)
10732   NODE_NAME_CASE(SHFL)
10733   NODE_NAME_CASE(SHFLW)
10734   NODE_NAME_CASE(UNSHFL)
10735   NODE_NAME_CASE(UNSHFLW)
10736   NODE_NAME_CASE(BFP)
10737   NODE_NAME_CASE(BFPW)
10738   NODE_NAME_CASE(BCOMPRESS)
10739   NODE_NAME_CASE(BCOMPRESSW)
10740   NODE_NAME_CASE(BDECOMPRESS)
10741   NODE_NAME_CASE(BDECOMPRESSW)
10742   NODE_NAME_CASE(VMV_V_X_VL)
10743   NODE_NAME_CASE(VFMV_V_F_VL)
10744   NODE_NAME_CASE(VMV_X_S)
10745   NODE_NAME_CASE(VMV_S_X_VL)
10746   NODE_NAME_CASE(VFMV_S_F_VL)
10747   NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
10748   NODE_NAME_CASE(READ_VLENB)
10749   NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
10750   NODE_NAME_CASE(VSLIDEUP_VL)
10751   NODE_NAME_CASE(VSLIDE1UP_VL)
10752   NODE_NAME_CASE(VSLIDEDOWN_VL)
10753   NODE_NAME_CASE(VSLIDE1DOWN_VL)
10754   NODE_NAME_CASE(VID_VL)
10755   NODE_NAME_CASE(VFNCVT_ROD_VL)
10756   NODE_NAME_CASE(VECREDUCE_ADD_VL)
10757   NODE_NAME_CASE(VECREDUCE_UMAX_VL)
10758   NODE_NAME_CASE(VECREDUCE_SMAX_VL)
10759   NODE_NAME_CASE(VECREDUCE_UMIN_VL)
10760   NODE_NAME_CASE(VECREDUCE_SMIN_VL)
10761   NODE_NAME_CASE(VECREDUCE_AND_VL)
10762   NODE_NAME_CASE(VECREDUCE_OR_VL)
10763   NODE_NAME_CASE(VECREDUCE_XOR_VL)
10764   NODE_NAME_CASE(VECREDUCE_FADD_VL)
10765   NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
10766   NODE_NAME_CASE(VECREDUCE_FMIN_VL)
10767   NODE_NAME_CASE(VECREDUCE_FMAX_VL)
10768   NODE_NAME_CASE(ADD_VL)
10769   NODE_NAME_CASE(AND_VL)
10770   NODE_NAME_CASE(MUL_VL)
10771   NODE_NAME_CASE(OR_VL)
10772   NODE_NAME_CASE(SDIV_VL)
10773   NODE_NAME_CASE(SHL_VL)
10774   NODE_NAME_CASE(SREM_VL)
10775   NODE_NAME_CASE(SRA_VL)
10776   NODE_NAME_CASE(SRL_VL)
10777   NODE_NAME_CASE(SUB_VL)
10778   NODE_NAME_CASE(UDIV_VL)
10779   NODE_NAME_CASE(UREM_VL)
10780   NODE_NAME_CASE(XOR_VL)
10781   NODE_NAME_CASE(SADDSAT_VL)
10782   NODE_NAME_CASE(UADDSAT_VL)
10783   NODE_NAME_CASE(SSUBSAT_VL)
10784   NODE_NAME_CASE(USUBSAT_VL)
10785   NODE_NAME_CASE(FADD_VL)
10786   NODE_NAME_CASE(FSUB_VL)
10787   NODE_NAME_CASE(FMUL_VL)
10788   NODE_NAME_CASE(FDIV_VL)
10789   NODE_NAME_CASE(FNEG_VL)
10790   NODE_NAME_CASE(FABS_VL)
10791   NODE_NAME_CASE(FSQRT_VL)
10792   NODE_NAME_CASE(FMA_VL)
10793   NODE_NAME_CASE(FCOPYSIGN_VL)
10794   NODE_NAME_CASE(SMIN_VL)
10795   NODE_NAME_CASE(SMAX_VL)
10796   NODE_NAME_CASE(UMIN_VL)
10797   NODE_NAME_CASE(UMAX_VL)
10798   NODE_NAME_CASE(FMINNUM_VL)
10799   NODE_NAME_CASE(FMAXNUM_VL)
10800   NODE_NAME_CASE(MULHS_VL)
10801   NODE_NAME_CASE(MULHU_VL)
10802   NODE_NAME_CASE(FP_TO_SINT_VL)
10803   NODE_NAME_CASE(FP_TO_UINT_VL)
10804   NODE_NAME_CASE(SINT_TO_FP_VL)
10805   NODE_NAME_CASE(UINT_TO_FP_VL)
10806   NODE_NAME_CASE(FP_EXTEND_VL)
10807   NODE_NAME_CASE(FP_ROUND_VL)
10808   NODE_NAME_CASE(VWMUL_VL)
10809   NODE_NAME_CASE(VWMULU_VL)
10810   NODE_NAME_CASE(VWMULSU_VL)
10811   NODE_NAME_CASE(VWADD_VL)
10812   NODE_NAME_CASE(VWADDU_VL)
10813   NODE_NAME_CASE(VWSUB_VL)
10814   NODE_NAME_CASE(VWSUBU_VL)
10815   NODE_NAME_CASE(VWADD_W_VL)
10816   NODE_NAME_CASE(VWADDU_W_VL)
10817   NODE_NAME_CASE(VWSUB_W_VL)
10818   NODE_NAME_CASE(VWSUBU_W_VL)
10819   NODE_NAME_CASE(SETCC_VL)
10820   NODE_NAME_CASE(VSELECT_VL)
10821   NODE_NAME_CASE(VP_MERGE_VL)
10822   NODE_NAME_CASE(VMAND_VL)
10823   NODE_NAME_CASE(VMOR_VL)
10824   NODE_NAME_CASE(VMXOR_VL)
10825   NODE_NAME_CASE(VMCLR_VL)
10826   NODE_NAME_CASE(VMSET_VL)
10827   NODE_NAME_CASE(VRGATHER_VX_VL)
10828   NODE_NAME_CASE(VRGATHER_VV_VL)
10829   NODE_NAME_CASE(VRGATHEREI16_VV_VL)
10830   NODE_NAME_CASE(VSEXT_VL)
10831   NODE_NAME_CASE(VZEXT_VL)
10832   NODE_NAME_CASE(VCPOP_VL)
10833   NODE_NAME_CASE(VLE_VL)
10834   NODE_NAME_CASE(VSE_VL)
10835   NODE_NAME_CASE(READ_CSR)
10836   NODE_NAME_CASE(WRITE_CSR)
10837   NODE_NAME_CASE(SWAP_CSR)
10838   }
10839   // clang-format on
10840   return nullptr;
10841 #undef NODE_NAME_CASE
10842 }
10843 
10844 /// getConstraintType - Given a constraint letter, return the type of
10845 /// constraint it is for this target.
10846 RISCVTargetLowering::ConstraintType
10847 RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
10848   if (Constraint.size() == 1) {
10849     switch (Constraint[0]) {
10850     default:
10851       break;
10852     case 'f':
10853       return C_RegisterClass;
10854     case 'I':
10855     case 'J':
10856     case 'K':
10857       return C_Immediate;
10858     case 'A':
10859       return C_Memory;
10860     case 'S': // A symbolic address
10861       return C_Other;
10862     }
10863   } else {
10864     if (Constraint == "vr" || Constraint == "vm")
10865       return C_RegisterClass;
10866   }
10867   return TargetLowering::getConstraintType(Constraint);
10868 }
10869 
10870 std::pair<unsigned, const TargetRegisterClass *>
10871 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10872                                                   StringRef Constraint,
10873                                                   MVT VT) const {
10874   // First, see if this is a constraint that directly corresponds to a
10875   // RISCV register class.
10876   if (Constraint.size() == 1) {
10877     switch (Constraint[0]) {
10878     case 'r':
10879       // TODO: Support fixed vectors up to XLen for P extension?
10880       if (VT.isVector())
10881         break;
10882       return std::make_pair(0U, &RISCV::GPRRegClass);
10883     case 'f':
10884       if (Subtarget.hasStdExtZfh() && VT == MVT::f16)
10885         return std::make_pair(0U, &RISCV::FPR16RegClass);
10886       if (Subtarget.hasStdExtF() && VT == MVT::f32)
10887         return std::make_pair(0U, &RISCV::FPR32RegClass);
10888       if (Subtarget.hasStdExtD() && VT == MVT::f64)
10889         return std::make_pair(0U, &RISCV::FPR64RegClass);
10890       break;
10891     default:
10892       break;
10893     }
10894   } else if (Constraint == "vr") {
10895     for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
10896                            &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
10897       if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
10898         return std::make_pair(0U, RC);
10899     }
10900   } else if (Constraint == "vm") {
10901     if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
10902       return std::make_pair(0U, &RISCV::VMV0RegClass);
10903   }
10904 
10905   // Clang will correctly decode the usage of register name aliases into their
10906   // official names. However, other frontends like `rustc` do not. This allows
10907   // users of these frontends to use the ABI names for registers in LLVM-style
10908   // register constraints.
10909   unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
10910                                .Case("{zero}", RISCV::X0)
10911                                .Case("{ra}", RISCV::X1)
10912                                .Case("{sp}", RISCV::X2)
10913                                .Case("{gp}", RISCV::X3)
10914                                .Case("{tp}", RISCV::X4)
10915                                .Case("{t0}", RISCV::X5)
10916                                .Case("{t1}", RISCV::X6)
10917                                .Case("{t2}", RISCV::X7)
10918                                .Cases("{s0}", "{fp}", RISCV::X8)
10919                                .Case("{s1}", RISCV::X9)
10920                                .Case("{a0}", RISCV::X10)
10921                                .Case("{a1}", RISCV::X11)
10922                                .Case("{a2}", RISCV::X12)
10923                                .Case("{a3}", RISCV::X13)
10924                                .Case("{a4}", RISCV::X14)
10925                                .Case("{a5}", RISCV::X15)
10926                                .Case("{a6}", RISCV::X16)
10927                                .Case("{a7}", RISCV::X17)
10928                                .Case("{s2}", RISCV::X18)
10929                                .Case("{s3}", RISCV::X19)
10930                                .Case("{s4}", RISCV::X20)
10931                                .Case("{s5}", RISCV::X21)
10932                                .Case("{s6}", RISCV::X22)
10933                                .Case("{s7}", RISCV::X23)
10934                                .Case("{s8}", RISCV::X24)
10935                                .Case("{s9}", RISCV::X25)
10936                                .Case("{s10}", RISCV::X26)
10937                                .Case("{s11}", RISCV::X27)
10938                                .Case("{t3}", RISCV::X28)
10939                                .Case("{t4}", RISCV::X29)
10940                                .Case("{t5}", RISCV::X30)
10941                                .Case("{t6}", RISCV::X31)
10942                                .Default(RISCV::NoRegister);
10943   if (XRegFromAlias != RISCV::NoRegister)
10944     return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
10945 
10946   // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
10947   // TableGen record rather than the AsmName to choose registers for InlineAsm
10948   // constraints, plus we want to match those names to the widest floating point
10949   // register type available, manually select floating point registers here.
10950   //
10951   // The second case is the ABI name of the register, so that frontends can also
10952   // use the ABI names in register constraint lists.
10953   if (Subtarget.hasStdExtF()) {
10954     unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
10955                         .Cases("{f0}", "{ft0}", RISCV::F0_F)
10956                         .Cases("{f1}", "{ft1}", RISCV::F1_F)
10957                         .Cases("{f2}", "{ft2}", RISCV::F2_F)
10958                         .Cases("{f3}", "{ft3}", RISCV::F3_F)
10959                         .Cases("{f4}", "{ft4}", RISCV::F4_F)
10960                         .Cases("{f5}", "{ft5}", RISCV::F5_F)
10961                         .Cases("{f6}", "{ft6}", RISCV::F6_F)
10962                         .Cases("{f7}", "{ft7}", RISCV::F7_F)
10963                         .Cases("{f8}", "{fs0}", RISCV::F8_F)
10964                         .Cases("{f9}", "{fs1}", RISCV::F9_F)
10965                         .Cases("{f10}", "{fa0}", RISCV::F10_F)
10966                         .Cases("{f11}", "{fa1}", RISCV::F11_F)
10967                         .Cases("{f12}", "{fa2}", RISCV::F12_F)
10968                         .Cases("{f13}", "{fa3}", RISCV::F13_F)
10969                         .Cases("{f14}", "{fa4}", RISCV::F14_F)
10970                         .Cases("{f15}", "{fa5}", RISCV::F15_F)
10971                         .Cases("{f16}", "{fa6}", RISCV::F16_F)
10972                         .Cases("{f17}", "{fa7}", RISCV::F17_F)
10973                         .Cases("{f18}", "{fs2}", RISCV::F18_F)
10974                         .Cases("{f19}", "{fs3}", RISCV::F19_F)
10975                         .Cases("{f20}", "{fs4}", RISCV::F20_F)
10976                         .Cases("{f21}", "{fs5}", RISCV::F21_F)
10977                         .Cases("{f22}", "{fs6}", RISCV::F22_F)
10978                         .Cases("{f23}", "{fs7}", RISCV::F23_F)
10979                         .Cases("{f24}", "{fs8}", RISCV::F24_F)
10980                         .Cases("{f25}", "{fs9}", RISCV::F25_F)
10981                         .Cases("{f26}", "{fs10}", RISCV::F26_F)
10982                         .Cases("{f27}", "{fs11}", RISCV::F27_F)
10983                         .Cases("{f28}", "{ft8}", RISCV::F28_F)
10984                         .Cases("{f29}", "{ft9}", RISCV::F29_F)
10985                         .Cases("{f30}", "{ft10}", RISCV::F30_F)
10986                         .Cases("{f31}", "{ft11}", RISCV::F31_F)
10987                         .Default(RISCV::NoRegister);
10988     if (FReg != RISCV::NoRegister) {
10989       assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
10990       if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
10991         unsigned RegNo = FReg - RISCV::F0_F;
10992         unsigned DReg = RISCV::F0_D + RegNo;
10993         return std::make_pair(DReg, &RISCV::FPR64RegClass);
10994       }
10995       if (VT == MVT::f32 || VT == MVT::Other)
10996         return std::make_pair(FReg, &RISCV::FPR32RegClass);
10997       if (Subtarget.hasStdExtZfh() && VT == MVT::f16) {
10998         unsigned RegNo = FReg - RISCV::F0_F;
10999         unsigned HReg = RISCV::F0_H + RegNo;
11000         return std::make_pair(HReg, &RISCV::FPR16RegClass);
11001       }
11002     }
11003   }
11004 
11005   if (Subtarget.hasVInstructions()) {
11006     Register VReg = StringSwitch<Register>(Constraint.lower())
11007                         .Case("{v0}", RISCV::V0)
11008                         .Case("{v1}", RISCV::V1)
11009                         .Case("{v2}", RISCV::V2)
11010                         .Case("{v3}", RISCV::V3)
11011                         .Case("{v4}", RISCV::V4)
11012                         .Case("{v5}", RISCV::V5)
11013                         .Case("{v6}", RISCV::V6)
11014                         .Case("{v7}", RISCV::V7)
11015                         .Case("{v8}", RISCV::V8)
11016                         .Case("{v9}", RISCV::V9)
11017                         .Case("{v10}", RISCV::V10)
11018                         .Case("{v11}", RISCV::V11)
11019                         .Case("{v12}", RISCV::V12)
11020                         .Case("{v13}", RISCV::V13)
11021                         .Case("{v14}", RISCV::V14)
11022                         .Case("{v15}", RISCV::V15)
11023                         .Case("{v16}", RISCV::V16)
11024                         .Case("{v17}", RISCV::V17)
11025                         .Case("{v18}", RISCV::V18)
11026                         .Case("{v19}", RISCV::V19)
11027                         .Case("{v20}", RISCV::V20)
11028                         .Case("{v21}", RISCV::V21)
11029                         .Case("{v22}", RISCV::V22)
11030                         .Case("{v23}", RISCV::V23)
11031                         .Case("{v24}", RISCV::V24)
11032                         .Case("{v25}", RISCV::V25)
11033                         .Case("{v26}", RISCV::V26)
11034                         .Case("{v27}", RISCV::V27)
11035                         .Case("{v28}", RISCV::V28)
11036                         .Case("{v29}", RISCV::V29)
11037                         .Case("{v30}", RISCV::V30)
11038                         .Case("{v31}", RISCV::V31)
11039                         .Default(RISCV::NoRegister);
11040     if (VReg != RISCV::NoRegister) {
11041       if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
11042         return std::make_pair(VReg, &RISCV::VMRegClass);
11043       if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
11044         return std::make_pair(VReg, &RISCV::VRRegClass);
11045       for (const auto *RC :
11046            {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
11047         if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
11048           VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
11049           return std::make_pair(VReg, RC);
11050         }
11051       }
11052     }
11053   }
11054 
11055   std::pair<Register, const TargetRegisterClass *> Res =
11056       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11057 
11058   // If we picked one of the Zfinx register classes, remap it to the GPR class.
11059   // FIXME: When Zfinx is supported in CodeGen this will need to take the
11060   // Subtarget into account.
11061   if (Res.second == &RISCV::GPRF16RegClass ||
11062       Res.second == &RISCV::GPRF32RegClass ||
11063       Res.second == &RISCV::GPRF64RegClass)
11064     return std::make_pair(Res.first, &RISCV::GPRRegClass);
11065 
11066   return Res;
11067 }
11068 
11069 unsigned
11070 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
11071   // Currently only support length 1 constraints.
11072   if (ConstraintCode.size() == 1) {
11073     switch (ConstraintCode[0]) {
11074     case 'A':
11075       return InlineAsm::Constraint_A;
11076     default:
11077       break;
11078     }
11079   }
11080 
11081   return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
11082 }
11083 
11084 void RISCVTargetLowering::LowerAsmOperandForConstraint(
11085     SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
11086     SelectionDAG &DAG) const {
11087   // Currently only support length 1 constraints.
11088   if (Constraint.length() == 1) {
11089     switch (Constraint[0]) {
11090     case 'I':
11091       // Validate & create a 12-bit signed immediate operand.
11092       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11093         uint64_t CVal = C->getSExtValue();
11094         if (isInt<12>(CVal))
11095           Ops.push_back(
11096               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11097       }
11098       return;
11099     case 'J':
11100       // Validate & create an integer zero operand.
11101       if (auto *C = dyn_cast<ConstantSDNode>(Op))
11102         if (C->getZExtValue() == 0)
11103           Ops.push_back(
11104               DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
11105       return;
11106     case 'K':
11107       // Validate & create a 5-bit unsigned immediate operand.
11108       if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
11109         uint64_t CVal = C->getZExtValue();
11110         if (isUInt<5>(CVal))
11111           Ops.push_back(
11112               DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
11113       }
11114       return;
11115     case 'S':
11116       if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
11117         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
11118                                                  GA->getValueType(0)));
11119       } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
11120         Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
11121                                                 BA->getValueType(0)));
11122       }
11123       return;
11124     default:
11125       break;
11126     }
11127   }
11128   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11129 }
11130 
11131 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
11132                                                    Instruction *Inst,
11133                                                    AtomicOrdering Ord) const {
11134   if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
11135     return Builder.CreateFence(Ord);
11136   if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
11137     return Builder.CreateFence(AtomicOrdering::Release);
11138   return nullptr;
11139 }
11140 
11141 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
11142                                                     Instruction *Inst,
11143                                                     AtomicOrdering Ord) const {
11144   if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
11145     return Builder.CreateFence(AtomicOrdering::Acquire);
11146   return nullptr;
11147 }
11148 
11149 TargetLowering::AtomicExpansionKind
11150 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11151   // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
11152   // point operations can't be used in an lr/sc sequence without breaking the
11153   // forward-progress guarantee.
11154   if (AI->isFloatingPointOperation())
11155     return AtomicExpansionKind::CmpXChg;
11156 
11157   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11158   if (Size == 8 || Size == 16)
11159     return AtomicExpansionKind::MaskedIntrinsic;
11160   return AtomicExpansionKind::None;
11161 }
11162 
11163 static Intrinsic::ID
11164 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
11165   if (XLen == 32) {
11166     switch (BinOp) {
11167     default:
11168       llvm_unreachable("Unexpected AtomicRMW BinOp");
11169     case AtomicRMWInst::Xchg:
11170       return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
11171     case AtomicRMWInst::Add:
11172       return Intrinsic::riscv_masked_atomicrmw_add_i32;
11173     case AtomicRMWInst::Sub:
11174       return Intrinsic::riscv_masked_atomicrmw_sub_i32;
11175     case AtomicRMWInst::Nand:
11176       return Intrinsic::riscv_masked_atomicrmw_nand_i32;
11177     case AtomicRMWInst::Max:
11178       return Intrinsic::riscv_masked_atomicrmw_max_i32;
11179     case AtomicRMWInst::Min:
11180       return Intrinsic::riscv_masked_atomicrmw_min_i32;
11181     case AtomicRMWInst::UMax:
11182       return Intrinsic::riscv_masked_atomicrmw_umax_i32;
11183     case AtomicRMWInst::UMin:
11184       return Intrinsic::riscv_masked_atomicrmw_umin_i32;
11185     }
11186   }
11187 
11188   if (XLen == 64) {
11189     switch (BinOp) {
11190     default:
11191       llvm_unreachable("Unexpected AtomicRMW BinOp");
11192     case AtomicRMWInst::Xchg:
11193       return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
11194     case AtomicRMWInst::Add:
11195       return Intrinsic::riscv_masked_atomicrmw_add_i64;
11196     case AtomicRMWInst::Sub:
11197       return Intrinsic::riscv_masked_atomicrmw_sub_i64;
11198     case AtomicRMWInst::Nand:
11199       return Intrinsic::riscv_masked_atomicrmw_nand_i64;
11200     case AtomicRMWInst::Max:
11201       return Intrinsic::riscv_masked_atomicrmw_max_i64;
11202     case AtomicRMWInst::Min:
11203       return Intrinsic::riscv_masked_atomicrmw_min_i64;
11204     case AtomicRMWInst::UMax:
11205       return Intrinsic::riscv_masked_atomicrmw_umax_i64;
11206     case AtomicRMWInst::UMin:
11207       return Intrinsic::riscv_masked_atomicrmw_umin_i64;
11208     }
11209   }
11210 
11211   llvm_unreachable("Unexpected XLen\n");
11212 }
11213 
11214 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
11215     IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
11216     Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
11217   unsigned XLen = Subtarget.getXLen();
11218   Value *Ordering =
11219       Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
11220   Type *Tys[] = {AlignedAddr->getType()};
11221   Function *LrwOpScwLoop = Intrinsic::getDeclaration(
11222       AI->getModule(),
11223       getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
11224 
11225   if (XLen == 64) {
11226     Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
11227     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11228     ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
11229   }
11230 
11231   Value *Result;
11232 
11233   // Must pass the shift amount needed to sign extend the loaded value prior
11234   // to performing a signed comparison for min/max. ShiftAmt is the number of
11235   // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
11236   // is the number of bits to left+right shift the value in order to
11237   // sign-extend.
11238   if (AI->getOperation() == AtomicRMWInst::Min ||
11239       AI->getOperation() == AtomicRMWInst::Max) {
11240     const DataLayout &DL = AI->getModule()->getDataLayout();
11241     unsigned ValWidth =
11242         DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
11243     Value *SextShamt =
11244         Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
11245     Result = Builder.CreateCall(LrwOpScwLoop,
11246                                 {AlignedAddr, Incr, Mask, SextShamt, Ordering});
11247   } else {
11248     Result =
11249         Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
11250   }
11251 
11252   if (XLen == 64)
11253     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11254   return Result;
11255 }
11256 
11257 TargetLowering::AtomicExpansionKind
11258 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
11259     AtomicCmpXchgInst *CI) const {
11260   unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
11261   if (Size == 8 || Size == 16)
11262     return AtomicExpansionKind::MaskedIntrinsic;
11263   return AtomicExpansionKind::None;
11264 }
11265 
11266 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
11267     IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
11268     Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
11269   unsigned XLen = Subtarget.getXLen();
11270   Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
11271   Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
11272   if (XLen == 64) {
11273     CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
11274     NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
11275     Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
11276     CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
11277   }
11278   Type *Tys[] = {AlignedAddr->getType()};
11279   Function *MaskedCmpXchg =
11280       Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
11281   Value *Result = Builder.CreateCall(
11282       MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
11283   if (XLen == 64)
11284     Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
11285   return Result;
11286 }
11287 
11288 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
11289   return false;
11290 }
11291 
11292 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
11293                                                EVT VT) const {
11294   if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
11295     return false;
11296 
11297   switch (FPVT.getSimpleVT().SimpleTy) {
11298   case MVT::f16:
11299     return Subtarget.hasStdExtZfh();
11300   case MVT::f32:
11301     return Subtarget.hasStdExtF();
11302   case MVT::f64:
11303     return Subtarget.hasStdExtD();
11304   default:
11305     return false;
11306   }
11307 }
11308 
11309 unsigned RISCVTargetLowering::getJumpTableEncoding() const {
11310   // If we are using the small code model, we can reduce size of jump table
11311   // entry to 4 bytes.
11312   if (Subtarget.is64Bit() && !isPositionIndependent() &&
11313       getTargetMachine().getCodeModel() == CodeModel::Small) {
11314     return MachineJumpTableInfo::EK_Custom32;
11315   }
11316   return TargetLowering::getJumpTableEncoding();
11317 }
11318 
11319 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
11320     const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
11321     unsigned uid, MCContext &Ctx) const {
11322   assert(Subtarget.is64Bit() && !isPositionIndependent() &&
11323          getTargetMachine().getCodeModel() == CodeModel::Small);
11324   return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
11325 }
11326 
11327 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
11328                                                      EVT VT) const {
11329   VT = VT.getScalarType();
11330 
11331   if (!VT.isSimple())
11332     return false;
11333 
11334   switch (VT.getSimpleVT().SimpleTy) {
11335   case MVT::f16:
11336     return Subtarget.hasStdExtZfh();
11337   case MVT::f32:
11338     return Subtarget.hasStdExtF();
11339   case MVT::f64:
11340     return Subtarget.hasStdExtD();
11341   default:
11342     break;
11343   }
11344 
11345   return false;
11346 }
11347 
11348 Register RISCVTargetLowering::getExceptionPointerRegister(
11349     const Constant *PersonalityFn) const {
11350   return RISCV::X10;
11351 }
11352 
11353 Register RISCVTargetLowering::getExceptionSelectorRegister(
11354     const Constant *PersonalityFn) const {
11355   return RISCV::X11;
11356 }
11357 
11358 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
11359   // Return false to suppress the unnecessary extensions if the LibCall
11360   // arguments or return value is f32 type for LP64 ABI.
11361   RISCVABI::ABI ABI = Subtarget.getTargetABI();
11362   if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
11363     return false;
11364 
11365   return true;
11366 }
11367 
11368 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
11369   if (Subtarget.is64Bit() && Type == MVT::i32)
11370     return true;
11371 
11372   return IsSigned;
11373 }
11374 
11375 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
11376                                                  SDValue C) const {
11377   // Check integral scalar types.
11378   if (VT.isScalarInteger()) {
11379     // Omit the optimization if the sub target has the M extension and the data
11380     // size exceeds XLen.
11381     if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen())
11382       return false;
11383     if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
11384       // Break the MUL to a SLLI and an ADD/SUB.
11385       const APInt &Imm = ConstNode->getAPIntValue();
11386       if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
11387           (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
11388         return true;
11389       // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
11390       if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
11391           ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
11392            (Imm - 8).isPowerOf2()))
11393         return true;
11394       // Omit the following optimization if the sub target has the M extension
11395       // and the data size >= XLen.
11396       if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen())
11397         return false;
11398       // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
11399       // a pair of LUI/ADDI.
11400       if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
11401         APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
11402         if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
11403             (1 - ImmS).isPowerOf2())
11404         return true;
11405       }
11406     }
11407   }
11408 
11409   return false;
11410 }
11411 
11412 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
11413                                                       SDValue ConstNode) const {
11414   // Let the DAGCombiner decide for vectors.
11415   EVT VT = AddNode.getValueType();
11416   if (VT.isVector())
11417     return true;
11418 
11419   // Let the DAGCombiner decide for larger types.
11420   if (VT.getScalarSizeInBits() > Subtarget.getXLen())
11421     return true;
11422 
11423   // It is worse if c1 is simm12 while c1*c2 is not.
11424   ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
11425   ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
11426   const APInt &C1 = C1Node->getAPIntValue();
11427   const APInt &C2 = C2Node->getAPIntValue();
11428   if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
11429     return false;
11430 
11431   // Default to true and let the DAGCombiner decide.
11432   return true;
11433 }
11434 
11435 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
11436     EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
11437     bool *Fast) const {
11438   if (!VT.isVector())
11439     return false;
11440 
11441   EVT ElemVT = VT.getVectorElementType();
11442   if (Alignment >= ElemVT.getStoreSize()) {
11443     if (Fast)
11444       *Fast = true;
11445     return true;
11446   }
11447 
11448   return false;
11449 }
11450 
11451 bool RISCVTargetLowering::splitValueIntoRegisterParts(
11452     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
11453     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
11454   bool IsABIRegCopy = CC.hasValue();
11455   EVT ValueVT = Val.getValueType();
11456   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11457     // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
11458     // and cast to f32.
11459     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
11460     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
11461     Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
11462                       DAG.getConstant(0xFFFF0000, DL, MVT::i32));
11463     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
11464     Parts[0] = Val;
11465     return true;
11466   }
11467 
11468   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11469     LLVMContext &Context = *DAG.getContext();
11470     EVT ValueEltVT = ValueVT.getVectorElementType();
11471     EVT PartEltVT = PartVT.getVectorElementType();
11472     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11473     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11474     if (PartVTBitSize % ValueVTBitSize == 0) {
11475       assert(PartVTBitSize >= ValueVTBitSize);
11476       // If the element types are different, bitcast to the same element type of
11477       // PartVT first.
11478       // Give an example here, we want copy a <vscale x 1 x i8> value to
11479       // <vscale x 4 x i16>.
11480       // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
11481       // subvector, then we can bitcast to <vscale x 4 x i16>.
11482       if (ValueEltVT != PartEltVT) {
11483         if (PartVTBitSize > ValueVTBitSize) {
11484           unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11485           assert(Count != 0 && "The number of element should not be zero.");
11486           EVT SameEltTypeVT =
11487               EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11488           Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
11489                             DAG.getUNDEF(SameEltTypeVT), Val,
11490                             DAG.getVectorIdxConstant(0, DL));
11491         }
11492         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
11493       } else {
11494         Val =
11495             DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
11496                         Val, DAG.getVectorIdxConstant(0, DL));
11497       }
11498       Parts[0] = Val;
11499       return true;
11500     }
11501   }
11502   return false;
11503 }
11504 
11505 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
11506     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
11507     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
11508   bool IsABIRegCopy = CC.hasValue();
11509   if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
11510     SDValue Val = Parts[0];
11511 
11512     // Cast the f32 to i32, truncate to i16, and cast back to f16.
11513     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
11514     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
11515     Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
11516     return Val;
11517   }
11518 
11519   if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
11520     LLVMContext &Context = *DAG.getContext();
11521     SDValue Val = Parts[0];
11522     EVT ValueEltVT = ValueVT.getVectorElementType();
11523     EVT PartEltVT = PartVT.getVectorElementType();
11524     unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize();
11525     unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize();
11526     if (PartVTBitSize % ValueVTBitSize == 0) {
11527       assert(PartVTBitSize >= ValueVTBitSize);
11528       EVT SameEltTypeVT = ValueVT;
11529       // If the element types are different, convert it to the same element type
11530       // of PartVT.
11531       // Give an example here, we want copy a <vscale x 1 x i8> value from
11532       // <vscale x 4 x i16>.
11533       // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
11534       // then we can extract <vscale x 1 x i8>.
11535       if (ValueEltVT != PartEltVT) {
11536         unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
11537         assert(Count != 0 && "The number of element should not be zero.");
11538         SameEltTypeVT =
11539             EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
11540         Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
11541       }
11542       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
11543                         DAG.getVectorIdxConstant(0, DL));
11544       return Val;
11545     }
11546   }
11547   return SDValue();
11548 }
11549 
11550 SDValue
11551 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
11552                                    SelectionDAG &DAG,
11553                                    SmallVectorImpl<SDNode *> &Created) const {
11554   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
11555   if (isIntDivCheap(N->getValueType(0), Attr))
11556     return SDValue(N, 0); // Lower SDIV as SDIV
11557 
11558   assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) &&
11559          "Unexpected divisor!");
11560 
11561   // Conditional move is needed, so do the transformation iff Zbt is enabled.
11562   if (!Subtarget.hasStdExtZbt())
11563     return SDValue();
11564 
11565   // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation.
11566   // Besides, more critical path instructions will be generated when dividing
11567   // by 2. So we keep using the original DAGs for these cases.
11568   unsigned Lg2 = Divisor.countTrailingZeros();
11569   if (Lg2 == 1 || Lg2 >= 12)
11570     return SDValue();
11571 
11572   // fold (sdiv X, pow2)
11573   EVT VT = N->getValueType(0);
11574   if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64))
11575     return SDValue();
11576 
11577   SDLoc DL(N);
11578   SDValue N0 = N->getOperand(0);
11579   SDValue Zero = DAG.getConstant(0, DL, VT);
11580   SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
11581 
11582   // Add (N0 < 0) ? Pow2 - 1 : 0;
11583   SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT);
11584   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
11585   SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
11586 
11587   Created.push_back(Cmp.getNode());
11588   Created.push_back(Add.getNode());
11589   Created.push_back(Sel.getNode());
11590 
11591   // Divide by pow2.
11592   SDValue SRA =
11593       DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT));
11594 
11595   // If we're dividing by a positive value, we're done.  Otherwise, we must
11596   // negate the result.
11597   if (Divisor.isNonNegative())
11598     return SRA;
11599 
11600   Created.push_back(SRA.getNode());
11601   return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
11602 }
11603 
11604 #define GET_REGISTER_MATCHER
11605 #include "RISCVGenAsmMatcher.inc"
11606 
11607 Register
11608 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
11609                                        const MachineFunction &MF) const {
11610   Register Reg = MatchRegisterAltName(RegName);
11611   if (Reg == RISCV::NoRegister)
11612     Reg = MatchRegisterName(RegName);
11613   if (Reg == RISCV::NoRegister)
11614     report_fatal_error(
11615         Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
11616   BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
11617   if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
11618     report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
11619                              StringRef(RegName) + "\"."));
11620   return Reg;
11621 }
11622 
11623 namespace llvm {
11624 namespace RISCVVIntrinsicsTable {
11625 
11626 #define GET_RISCVVIntrinsicsTable_IMPL
11627 #include "RISCVGenSearchableTables.inc"
11628 
11629 } // namespace RISCVVIntrinsicsTable
11630 
11631 } // namespace llvm
11632